1
0

test.cc 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418
  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_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. #ifndef _WIN32
  253. TEST(SocketStream, wait_writable_UNIX) {
  254. int fds[2];
  255. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  256. const auto asSocketStream = [&](socket_t fd,
  257. std::function<bool(Stream &)> func) {
  258. return detail::process_client_socket(
  259. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  260. };
  261. asSocketStream(fds[0], [&](Stream &s0) {
  262. EXPECT_EQ(s0.socket(), fds[0]);
  263. EXPECT_TRUE(s0.wait_writable());
  264. EXPECT_TRUE(s0.is_peer_alive());
  265. EXPECT_EQ(0, close(fds[1]));
  266. EXPECT_FALSE(s0.is_peer_alive());
  267. return true;
  268. });
  269. EXPECT_EQ(0, close(fds[0]));
  270. }
  271. TEST(SocketStream, wait_writable_INET) {
  272. sockaddr_in addr;
  273. memset(&addr, 0, sizeof(addr));
  274. addr.sin_family = AF_INET;
  275. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  276. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  277. int disconnected_svr_sock = -1;
  278. std::thread svr{[&] {
  279. const int s = socket(AF_INET, SOCK_STREAM, 0);
  280. ASSERT_LE(0, s);
  281. // PORT + 1 is shared with the SSL redirect tests and with
  282. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  283. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  284. // because that happens on a worker thread the ASSERT does not stop the
  285. // test: it runs on and fails at the disconnected_svr_sock check instead.
  286. default_socket_options(s);
  287. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  288. ASSERT_EQ(0, listen(s, 1));
  289. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  290. ASSERT_EQ(0, close(s));
  291. }};
  292. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  293. std::thread cli{[&] {
  294. const int s = socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_LE(0, s);
  296. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  297. ASSERT_EQ(0, close(s));
  298. }};
  299. cli.join();
  300. svr.join();
  301. ASSERT_NE(disconnected_svr_sock, -1);
  302. const auto asSocketStream = [&](socket_t fd,
  303. std::function<bool(Stream &)> func) {
  304. return detail::process_client_socket(
  305. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  306. };
  307. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  308. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  309. // wait_writable() returns true because select_write() only checks if the
  310. // send buffer has space. Peer disconnection is detected later by send().
  311. EXPECT_TRUE(ss.wait_writable());
  312. return true;
  313. });
  314. ASSERT_EQ(0, close(disconnected_svr_sock));
  315. }
  316. #endif // #ifndef _WIN32
  317. TEST(SetSocketOptTest, TcpNoDelay) {
  318. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  319. ASSERT_NE(sock, INVALID_SOCKET);
  320. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  321. int val = 0;
  322. socklen_t len = sizeof(val);
  323. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  324. reinterpret_cast<char *>(&val), &len));
  325. EXPECT_NE(val, 0);
  326. detail::close_socket(sock);
  327. }
  328. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  329. // accept() reports failures through WSAGetLastError() on Windows and through
  330. // errno everywhere else. Asking the wrong one is what made the accept loop
  331. // treat every recoverable failure as fatal on Windows.
  332. struct Classification {
  333. bool resource;
  334. bool transient;
  335. };
  336. auto classify = [](int err) {
  337. #ifdef _WIN32
  338. WSASetLastError(err);
  339. #else
  340. errno = err;
  341. #endif
  342. // Read both before asserting: an assertion may clobber the error slot.
  343. Classification c;
  344. c.resource = detail::is_accept_resource_error();
  345. c.transient = detail::is_accept_transient_error();
  346. return c;
  347. };
  348. #ifdef _WIN32
  349. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  350. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  351. WSAECONNRESET, WSAECONNABORTED};
  352. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  353. #else
  354. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  355. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  356. ECONNABORTED};
  357. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  358. #endif
  359. for (auto err : resource_errors) {
  360. const auto c = classify(err);
  361. EXPECT_TRUE(c.resource) << "error " << err;
  362. EXPECT_FALSE(c.transient) << "error " << err;
  363. }
  364. for (auto err : transient_errors) {
  365. const auto c = classify(err);
  366. EXPECT_TRUE(c.transient) << "error " << err;
  367. EXPECT_FALSE(c.resource) << "error " << err;
  368. }
  369. for (auto err : fatal_errors) {
  370. const auto c = classify(err);
  371. EXPECT_FALSE(c.resource) << "error " << err;
  372. EXPECT_FALSE(c.transient) << "error " << err;
  373. }
  374. #ifdef _WIN32
  375. WSASetLastError(0);
  376. #else
  377. errno = 0;
  378. #endif
  379. }
  380. TEST(ClientTest, MoveConstructible) {
  381. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  382. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  383. }
  384. TEST(ClientTest, MoveAssignable) {
  385. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  386. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  387. }
  388. #ifdef _WIN32
  389. TEST(StartupTest, WSAStartup) {
  390. WSADATA wsaData;
  391. int ret = WSAStartup(0x0002, &wsaData);
  392. ASSERT_EQ(0, ret);
  393. }
  394. #endif
  395. TEST(DecodePathTest, PercentCharacter) {
  396. EXPECT_EQ(
  397. decode_path_component(
  398. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  399. U8("descrip=Gastos áéíóúñÑ 6"));
  400. }
  401. TEST(DecodePathTest, PercentCharacterNUL) {
  402. string expected;
  403. expected.push_back('x');
  404. expected.push_back('\0');
  405. expected.push_back('x');
  406. EXPECT_EQ(decode_path_component("x%00x"), expected);
  407. }
  408. TEST(DecodePathTest, UnicodeEncoding) {
  409. // %u0041 = 'A' (1-byte UTF-8)
  410. EXPECT_EQ("A", decode_path_component("%u0041"));
  411. // %u00E9 = 'é' (2-byte UTF-8)
  412. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  413. // %u3042 = 'あ' (3-byte UTF-8)
  414. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  415. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  416. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  417. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  418. // neighbours)
  419. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  420. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  421. }
  422. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  423. // A sign or whitespace inside the two-character escape window must not be
  424. // accepted as a valid percent-encoding; the sequence is passed through
  425. // literally, matching decode_uri_component / decode_path_component.
  426. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  427. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  428. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  429. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  430. // Well-formed escapes still decode.
  431. EXPECT_EQ("-", decode_query_component("%2D", false));
  432. EXPECT_EQ("A", decode_query_component("%41", false));
  433. }
  434. TEST(SanitizeFilenameTest, VariousPatterns) {
  435. // Path traversal
  436. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  437. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  438. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  439. // Normal and edge cases
  440. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  441. EXPECT_EQ("filename.txt",
  442. httplib::sanitize_filename("/path/to/filename.txt"));
  443. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  444. EXPECT_EQ("", httplib::sanitize_filename(".."));
  445. EXPECT_EQ("", httplib::sanitize_filename(""));
  446. // Null bytes stripped
  447. EXPECT_EQ("safe.txt",
  448. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  449. // Whitespace-only rejected
  450. EXPECT_EQ("", httplib::sanitize_filename(" "));
  451. }
  452. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  453. // before it is dropped; anywhere else it is an ordinary file name character.
  454. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  455. #ifdef _WIN32
  456. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  457. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  458. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  459. #else
  460. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  461. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  462. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  463. #endif
  464. }
  465. // Forward declaration (see the base64_encode note below): split builds move the
  466. // definition into httplib.cc, so re-declaring it here lets the test link.
  467. namespace httplib {
  468. namespace detail {
  469. bool is_chunked_transfer_encoding(const Headers &headers);
  470. } // namespace detail
  471. } // namespace httplib
  472. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  473. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  474. auto make = [](std::initializer_list<const char *> lines) {
  475. Headers h;
  476. for (auto te : lines) {
  477. if (te) { h.emplace("Transfer-Encoding", te); }
  478. }
  479. return h;
  480. };
  481. // Sole coding, matched case-insensitively.
  482. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  483. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  484. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  485. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  486. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  487. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  488. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  489. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  490. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  491. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  492. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  493. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  494. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  495. // were received, into one list. Headers preserves that order, so the answer
  496. // is decided by the last coding of the last line and the order the lines
  497. // arrived in is significant.
  498. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  499. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  500. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  501. // The split can fall anywhere in the list.
  502. EXPECT_TRUE(
  503. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  504. EXPECT_FALSE(
  505. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  506. // A trailing line naming no coding leaves the list ending in nothing, so it
  507. // must not inherit the chunked from the line before it.
  508. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  509. }
  510. // Forward declarations (see the base64_encode note below).
  511. namespace httplib {
  512. namespace detail {
  513. bool parse_status_line(const char *line, std::string &version, int &status,
  514. std::string &reason);
  515. std::string file_extension(const std::string &path);
  516. std::string
  517. find_content_type(const std::string &path,
  518. const std::map<std::string, std::string> &user_data,
  519. const std::string &default_content_type);
  520. bool can_compress_content_type(const std::string &content_type);
  521. bool is_prohibited_header_name(const std::string &name);
  522. bool is_valid_path(const std::string &path);
  523. #ifdef CPPHTTPLIB_SSL_ENABLED
  524. bool match_hostname(const std::string &pattern, const std::string &hostname);
  525. #endif
  526. } // namespace detail
  527. } // namespace httplib
  528. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  529. struct {
  530. const char *line;
  531. const char *version;
  532. int status;
  533. const char *reason;
  534. } cases[] = {
  535. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  536. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  537. // The reason phrase may be empty, or left out along with its space.
  538. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  539. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  540. };
  541. for (const auto &c : cases) {
  542. std::string version;
  543. int status = 0;
  544. std::string reason = "unset";
  545. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  546. << c.line;
  547. EXPECT_EQ(c.version, version);
  548. EXPECT_EQ(c.status, status);
  549. EXPECT_EQ(c.reason, reason);
  550. }
  551. }
  552. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  553. const char *lines[] = {
  554. "HTTP/2 200 OK\r\n",
  555. "HTTP/1.2 200 OK\r\n",
  556. "HTTP/1.1 20 OK\r\n",
  557. "HTTP/1.1 2000 OK\r\n",
  558. "HTTP/1.1 2x0 OK\r\n",
  559. "HTTP/1.1 200 OK\r\n",
  560. "HTTP/1.1 200OK\r\n",
  561. "HTTP/1.1 200 O\rK\r\n",
  562. "HTTP/1.1 200 OK",
  563. "HTTP/1.1 200 OK\r\nX",
  564. "",
  565. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  566. "HTTP/1.1 200 OK\n",
  567. #endif
  568. };
  569. for (auto line : lines) {
  570. std::string version;
  571. int status = 0;
  572. std::string reason;
  573. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  574. << line;
  575. }
  576. }
  577. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  578. // Long enough to overflow the stack when matched with std::regex.
  579. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  580. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  581. std::string version;
  582. int status = 0;
  583. std::string reason;
  584. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  585. EXPECT_EQ(200, status);
  586. EXPECT_EQ(long_reason, reason);
  587. }
  588. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  589. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  590. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  591. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  592. EXPECT_EQ("", detail::file_extension("noext"));
  593. EXPECT_EQ("", detail::file_extension("a."));
  594. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  595. EXPECT_EQ("", detail::file_extension("a.b-c"));
  596. // Long enough to overflow the stack when matched with std::regex.
  597. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  598. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  599. }
  600. #ifdef CPPHTTPLIB_SSL_ENABLED
  601. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  602. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  603. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  604. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  605. // A wildcard needs two labels after it, in the leftmost label only
  606. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  607. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  608. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  609. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  610. EXPECT_FALSE(
  611. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  612. // No name may have an empty label
  613. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  614. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  615. }
  616. #endif
  617. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  618. detail::case_ignore::hash hash;
  619. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  620. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  621. // Long enough to overflow the stack if hashed one call per character.
  622. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  623. }
  624. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  625. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  626. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  627. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  628. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  629. // Same 26-bit hash as html, svg and js.
  630. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  631. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  632. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  633. }
  634. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  635. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  636. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  637. }
  638. }
  639. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  640. // name anywhere else.
  641. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  642. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  643. #ifdef _WIN32
  644. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  645. #else
  646. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  647. #endif
  648. }
  649. }
  650. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  651. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  652. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  653. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  654. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  655. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  656. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  657. // Same 26-bit hash as application/json.
  658. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  659. }
  660. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  661. Request req;
  662. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  663. EXPECT_TRUE(req.is_multipart_form_data());
  664. std::string boundary;
  665. EXPECT_TRUE(detail::parse_multipart_boundary(
  666. req.get_header_value("Content-Type"), boundary));
  667. EXPECT_EQ("x", boundary);
  668. }
  669. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  670. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  671. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  672. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  673. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  674. // Same 26-bit hash as REMOTE_ADDR.
  675. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  676. }
  677. // Forward declaration: in split builds split.py strips `inline` and moves the
  678. // definition into httplib.cc, so detail::base64_encode is not visible from the
  679. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  680. // in both header-only and split builds.
  681. namespace httplib {
  682. namespace detail {
  683. std::string base64_encode(const std::string &in);
  684. } // namespace detail
  685. } // namespace httplib
  686. TEST(Base64EncodeTest, KnownAnswers) {
  687. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  688. // where the accumulator's top bit is already set before the next shift.
  689. EXPECT_EQ("", detail::base64_encode(""));
  690. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  691. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  692. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  693. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  694. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  695. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  696. // High bytes keep the top bit set across several rounds.
  697. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  698. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  699. }
  700. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  701. string unescapedCharacters = "-_.!~*'()";
  702. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  703. }
  704. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  705. string reservedCharacters = ";,/?:@&=+$";
  706. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  707. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  708. }
  709. TEST(ClientQueryOrder, PreserveOrder) {
  710. // This test reproduces Issue #2259: client may reorder query parameters
  711. // when sending a GET request. The expected behavior is that the client
  712. // preserves the original query string order when the caller supplied it
  713. // as part of the path.
  714. Server svr;
  715. svr.Get("/", [&](const Request &req, Response &res) {
  716. // Echo back the raw target so the test can assert ordering
  717. res.set_content(req.target, "text/plain");
  718. });
  719. std::thread t{[&] { svr.listen(HOST, PORT); }};
  720. auto se = detail::scope_exit([&] {
  721. svr.stop();
  722. t.join();
  723. ASSERT_FALSE(svr.is_running());
  724. });
  725. svr.wait_until_ready();
  726. Client cli(HOST, PORT);
  727. ASSERT_TRUE(cli.is_valid());
  728. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  729. auto res = cli.Get(original);
  730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  731. // Expect the echoed target to exactly match the original path (order
  732. // preserved)
  733. EXPECT_EQ(res->body, original);
  734. }
  735. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  736. string chineseCharacters = U8("中国語");
  737. string russianCharacters = U8("дом");
  738. string brazilianCharacters = U8("óculos");
  739. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  740. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  741. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  742. "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  746. string unescapedCharacters = "-_.!~*'()";
  747. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  748. }
  749. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  750. string reservedCharacters = ";,/?:@&=+$";
  751. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  752. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  753. }
  754. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  755. string chineseCharacters = U8("中国語");
  756. string russianCharacters = U8("дом");
  757. string brazilianCharacters = U8("óculos");
  758. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  759. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  760. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  761. "%D0%B4%D0%BE%D0%BC");
  762. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  763. }
  764. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  765. // Issue #2082 use case: encoding path component with ampersand
  766. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  767. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  768. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  769. }
  770. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  775. string reservedCharacters = ";,/?:@&=+$#";
  776. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  777. }
  778. TEST(EncodeUriTest, TestUTF8Characters) {
  779. string chineseCharacters = U8("中国語");
  780. string russianCharacters = U8("дом");
  781. string brazilianCharacters = U8("óculos");
  782. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  783. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  784. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  785. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  786. }
  787. TEST(EncodeUriTest, TestCompleteUri) {
  788. string uri =
  789. "https://example.com/path/to/resource?query=value&param=test#fragment";
  790. EXPECT_EQ(
  791. httplib::encode_uri(uri),
  792. "https://example.com/path/to/resource?query=value&param=test#fragment");
  793. }
  794. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  795. string uri =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. EXPECT_EQ(httplib::encode_uri(uri),
  798. "https://example.com/path%20with%20spaces/"
  799. "file%20name.html?q=hello%20world");
  800. }
  801. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  802. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  803. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  804. }
  805. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  806. string unescapedCharacters = "-_.!~*'()";
  807. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  808. }
  809. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  810. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  811. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  812. string encodedBrazilian = "%C3%B3culos";
  813. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  814. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  815. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  816. }
  817. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  818. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  819. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  820. "Piri Tommy Villiers - on & on");
  821. }
  822. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  823. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  824. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  825. }
  826. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  827. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  828. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  829. }
  830. TEST(DecodeUriTest, TestUTF8Characters) {
  831. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  832. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  833. string encodedBrazilian = "%C3%B3culos";
  834. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  835. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  836. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  837. }
  838. TEST(DecodeUriTest, TestCompleteUri) {
  839. string encodedUri = "https://example.com/path%20with%20spaces/"
  840. "file%20name.html?q=hello%20world";
  841. EXPECT_EQ(
  842. httplib::decode_uri(encodedUri),
  843. "https://example.com/path with spaces/file name.html?q=hello world");
  844. }
  845. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  846. string original =
  847. "https://example.com/path with spaces/file name.html?q=hello world";
  848. string encoded = httplib::encode_uri(original);
  849. string decoded = httplib::decode_uri(encoded);
  850. EXPECT_EQ(decoded, original);
  851. }
  852. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  853. // decode_uri is the inverse of encode_uri: an escaped reserved character
  854. // stays encoded so it is not promoted into a real delimiter, while
  855. // non-reserved escapes still decode (like JS decodeURI).
  856. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  857. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  858. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  859. "%3F%3A%40%26%3D%2B%24%2C%3B");
  860. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  861. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  862. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  863. "http://example.com/a%2Fb");
  864. // decode_uri_component still decodes the reserved character.
  865. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  866. }
  867. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  868. string original = "Piri Tommy Villiers - on & on";
  869. string encoded = httplib::encode_uri_component(original);
  870. string decoded = httplib::decode_uri_component(encoded);
  871. EXPECT_EQ(decoded, original);
  872. }
  873. TEST(TrimTests, TrimStringTests) {
  874. EXPECT_EQ("abc", detail::trim_copy("abc"));
  875. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  876. EXPECT_TRUE(detail::trim_copy("").empty());
  877. }
  878. TEST(AsciiTest, LocaleIndependentClassification) {
  879. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  880. // which consult the global C locale: std::isalnum(0xC5) can return true
  881. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  882. // helpers must classify every byte by the ASCII grammar alone.
  883. for (int i = 0; i < 256; i++) {
  884. auto c = static_cast<char>(i);
  885. auto is_digit = i >= '0' && i <= '9';
  886. auto is_upper = i >= 'A' && i <= 'Z';
  887. auto is_lower = i >= 'a' && i <= 'z';
  888. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  889. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  890. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  891. << "byte " << i;
  892. }
  893. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  894. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  895. // Non-ASCII bytes must be percent-encoded, never passed through as
  896. // alphanumeric.
  897. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  898. }
  899. TEST(FromCharsTest, Double) {
  900. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  901. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  902. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  903. auto parse = [](const std::string &s, double &v) {
  904. return detail::from_chars(s.data(), s.data() + s.size(), v);
  905. };
  906. double v = -1.0;
  907. // Representative quality values.
  908. EXPECT_EQ(parse("0", v).ec, std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse("1", v).ec, std::errc{});
  911. EXPECT_DOUBLE_EQ(v, 1.0);
  912. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  913. EXPECT_DOUBLE_EQ(v, 0.8);
  914. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  915. EXPECT_DOUBLE_EQ(v, 0.001);
  916. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  917. EXPECT_DOUBLE_EQ(v, 1.0);
  918. // A missing integer or fractional part is tolerated.
  919. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  920. EXPECT_DOUBLE_EQ(v, 0.5);
  921. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  922. EXPECT_DOUBLE_EQ(v, 5.0);
  923. // Values outside [0, 1] still parse; the caller range-checks them.
  924. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  925. EXPECT_DOUBLE_EQ(v, 123.456);
  926. // Stops at the first byte that is not part of the number and reports where.
  927. std::string trailing = "0.9, text/html";
  928. auto r = parse(trailing, v);
  929. EXPECT_EQ(r.ec, std::errc{});
  930. EXPECT_DOUBLE_EQ(v, 0.9);
  931. EXPECT_EQ(*r.ptr, ',');
  932. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  933. // outright, and an 'e'/'E' simply ends the number.
  934. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  935. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  936. std::string exp_input = "1.5e3";
  937. r = parse(exp_input, v);
  938. EXPECT_EQ(r.ec, std::errc{});
  939. EXPECT_DOUBLE_EQ(v, 1.5);
  940. EXPECT_EQ(*r.ptr, 'e');
  941. // Invalid inputs.
  942. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  943. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  944. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  945. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  946. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  947. // Pathological but well-formed inputs must stay bounded (no overflow, no
  948. // out-of-bounds table access) and stay within [0, 1] for the caller.
  949. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  950. std::errc{});
  951. EXPECT_DOUBLE_EQ(v, 0.0);
  952. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  953. std::errc{});
  954. EXPECT_GE(v, 0.0);
  955. EXPECT_LE(v, 1.0);
  956. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  957. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  958. }
  959. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  960. // Simple case without quality values
  961. std::vector<std::string> result1;
  962. EXPECT_TRUE(detail::parse_accept_header(
  963. "text/html,application/json,text/plain", result1));
  964. EXPECT_EQ(result1.size(), 3U);
  965. EXPECT_EQ(result1[0], "text/html");
  966. EXPECT_EQ(result1[1], "application/json");
  967. EXPECT_EQ(result1[2], "text/plain");
  968. // With quality values
  969. std::vector<std::string> result2;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  972. EXPECT_EQ(result2.size(), 3U);
  973. EXPECT_EQ(result2[0], "application/json"); // highest q value
  974. EXPECT_EQ(result2[1], "text/html");
  975. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  976. }
  977. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  978. // Mixed with and without quality values
  979. std::vector<std::string> result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  982. EXPECT_EQ(result.size(), 3U);
  983. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  984. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  985. EXPECT_EQ(result[2], "application/json"); // q=0.5
  986. }
  987. TEST(ParseAcceptHeaderTest, EdgeCases) {
  988. // Empty header
  989. std::vector<std::string> empty_result;
  990. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  991. EXPECT_TRUE(empty_result.empty());
  992. // Single type
  993. std::vector<std::string> single_result;
  994. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  995. EXPECT_EQ(single_result.size(), 1U);
  996. EXPECT_EQ(single_result[0], "application/json");
  997. // Wildcard types
  998. std::vector<std::string> wildcard_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1001. EXPECT_EQ(wildcard_result.size(), 3U);
  1002. EXPECT_EQ(wildcard_result[0], "application/json");
  1003. EXPECT_EQ(wildcard_result[1], "text/*");
  1004. EXPECT_EQ(wildcard_result[2], "*/*");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1007. // Common browser Accept header
  1008. std::vector<std::string> browser_result;
  1009. EXPECT_TRUE(
  1010. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1011. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1012. browser_result));
  1013. EXPECT_EQ(browser_result.size(), 6U);
  1014. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1015. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1016. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1017. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1018. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1019. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1020. // API client header
  1021. std::vector<std::string> api_result;
  1022. EXPECT_TRUE(detail::parse_accept_header(
  1023. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1024. api_result));
  1025. EXPECT_EQ(api_result.size(), 3U);
  1026. EXPECT_EQ(api_result[0], "application/json");
  1027. EXPECT_EQ(api_result[1], "application/xml");
  1028. EXPECT_EQ(api_result[2], "text/plain");
  1029. }
  1030. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1031. // Quality value with 3 decimal places
  1032. std::vector<std::string> decimal_result;
  1033. EXPECT_TRUE(detail::parse_accept_header(
  1034. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1035. EXPECT_EQ(decimal_result.size(), 2U);
  1036. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1037. EXPECT_EQ(decimal_result[1], "text/html");
  1038. // Zero quality (should still be included but with lowest priority)
  1039. std::vector<std::string> zero_q_result;
  1040. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1041. zero_q_result));
  1042. EXPECT_EQ(zero_q_result.size(), 2U);
  1043. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1044. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1045. // No spaces around commas
  1046. std::vector<std::string> no_space_result;
  1047. EXPECT_TRUE(detail::parse_accept_header(
  1048. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1049. no_space_result));
  1050. EXPECT_EQ(no_space_result.size(), 3U);
  1051. EXPECT_EQ(no_space_result[0], "text/html");
  1052. EXPECT_EQ(no_space_result[1], "application/json");
  1053. EXPECT_EQ(no_space_result[2], "text/plain");
  1054. }
  1055. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1056. // Quality values always use '.' as the decimal separator, so parsing must
  1057. // not depend on the process locale. An embedding application may have
  1058. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1059. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1060. std::string saved = cur ? cur : "C";
  1061. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1062. "fr_FR.UTF-8"};
  1063. bool switched = false;
  1064. for (const auto loc : comma_locales) {
  1065. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1066. std::localeconv()->decimal_point[0] == ',') {
  1067. switched = true;
  1068. break;
  1069. }
  1070. }
  1071. if (!switched) {
  1072. std::setlocale(LC_NUMERIC, saved.c_str());
  1073. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1074. }
  1075. // The higher-weighted type appears later in the list, so a correct parse
  1076. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1077. // sensitive parse reads both weights as 0 and leaves the original order.
  1078. std::vector<std::string> result;
  1079. EXPECT_TRUE(detail::parse_accept_header(
  1080. "application/json;q=0.1,text/html;q=0.9", result));
  1081. ASSERT_EQ(result.size(), 2U);
  1082. EXPECT_EQ(result[0], "text/html");
  1083. EXPECT_EQ(result[1], "application/json");
  1084. std::setlocale(LC_NUMERIC, saved.c_str());
  1085. }
  1086. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1087. std::vector<std::string> result;
  1088. // Invalid quality value (> 1.0)
  1089. EXPECT_FALSE(
  1090. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1091. // Invalid quality value (< 0.0)
  1092. EXPECT_FALSE(
  1093. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1094. // Invalid quality value (not a number)
  1095. EXPECT_FALSE(detail::parse_accept_header(
  1096. "text/html;q=invalid,application/json", result));
  1097. // A valid numeric prefix does not make the entire quality value valid.
  1098. EXPECT_FALSE(detail::parse_accept_header(
  1099. "text/html;q=0.5junk,application/json", result));
  1100. // Empty quality value
  1101. EXPECT_FALSE(
  1102. detail::parse_accept_header("text/html;q=,application/json", result));
  1103. // Invalid media type format (no slash and not wildcard)
  1104. EXPECT_FALSE(
  1105. detail::parse_accept_header("invalidtype,application/json", result));
  1106. // Valid cases should still work
  1107. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1108. EXPECT_EQ(result.size(), 1U);
  1109. EXPECT_EQ(result[0], "*/*");
  1110. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1111. EXPECT_EQ(result.size(), 1U);
  1112. EXPECT_EQ(result[0], "*");
  1113. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1114. EXPECT_EQ(result.size(), 1U);
  1115. EXPECT_EQ(result[0], "text/*");
  1116. }
  1117. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1118. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1119. // and must not be answered with 400 Bad Request.
  1120. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1121. struct {
  1122. const char *value;
  1123. std::vector<std::string> expected;
  1124. } cases[] = {
  1125. {",application/json", {"application/json"}},
  1126. {"text/html,", {"text/html"}},
  1127. {"text/html,,*/*", {"text/html", "*/*"}},
  1128. // An empty element may be spelled with whitespace in it
  1129. {"text/html, , application/json", {"text/html", "application/json"}},
  1130. // Nothing but empty elements is an empty list, which means the same
  1131. // thing as no Accept header at all
  1132. {",,,", {}},
  1133. // Quality values still apply across ignored empty elements
  1134. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1135. };
  1136. for (const auto &c : cases) {
  1137. std::vector<std::string> result;
  1138. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1139. << "value: " << c.value;
  1140. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1141. }
  1142. // An invalid entry is still rejected when empty elements surround it
  1143. std::vector<std::string> result;
  1144. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1145. }
  1146. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1147. // or ';' inside one does not end the list element or the parameter. Section
  1148. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1149. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1150. struct {
  1151. const char *value;
  1152. std::vector<std::string> expected;
  1153. } cases[] = {
  1154. {"text/html;profile=\"a,b\",application/json",
  1155. {"text/html", "application/json"}},
  1156. // A "q=" inside a quoted value is not the weight
  1157. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1158. {"text/html", "application/json"}},
  1159. // The weight after a quoted value still applies
  1160. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1161. {"application/json", "text/html"}},
  1162. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1163. {"application/json", "text/html"}},
  1164. {"text/html;profile=\"a\\\"b\",application/json",
  1165. {"text/html", "application/json"}},
  1166. // An escaped backslash does not escape the '"' after it
  1167. {"text/html;profile=\"a\\\\\",application/json",
  1168. {"text/html", "application/json"}},
  1169. };
  1170. for (const auto &c : cases) {
  1171. std::vector<std::string> result;
  1172. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1173. << "value: " << c.value;
  1174. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1175. }
  1176. }
  1177. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1178. Server svr;
  1179. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1180. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1181. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1182. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1183. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1184. res.set_content("ok", "text/plain");
  1185. });
  1186. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1187. EXPECT_TRUE(false);
  1188. res.set_content("bad request", "text/plain");
  1189. });
  1190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1191. auto se = detail::scope_exit([&] {
  1192. svr.stop();
  1193. listen_thread.join();
  1194. ASSERT_FALSE(svr.is_running());
  1195. });
  1196. svr.wait_until_ready();
  1197. Client cli("localhost", PORT);
  1198. {
  1199. auto res = cli.Get(
  1200. "/accept_ok",
  1201. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1203. EXPECT_EQ(StatusCode::OK_200, res->status);
  1204. }
  1205. {
  1206. auto res = cli.Get("/accept_bad_request",
  1207. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1209. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1210. }
  1211. }
  1212. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1213. Server svr;
  1214. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1215. res.set_content("ok", "text/plain");
  1216. });
  1217. std::atomic<int> start_count{0};
  1218. std::atomic<bool> running_when_called{false};
  1219. svr.set_start_handler([&]() {
  1220. running_when_called = svr.is_running();
  1221. start_count++;
  1222. });
  1223. auto port = svr.bind_to_any_port(HOST);
  1224. std::thread t([&]() { svr.listen_after_bind(); });
  1225. auto se = detail::scope_exit([&] {
  1226. svr.stop();
  1227. t.join();
  1228. ASSERT_FALSE(svr.is_running());
  1229. });
  1230. svr.wait_until_ready();
  1231. // A successful request proves the accept loop is running, which the start
  1232. // handler precedes; so by now the handler must have run exactly once.
  1233. Client cli(HOST, port);
  1234. cli.set_connection_timeout(std::chrono::seconds(5));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1237. EXPECT_EQ(StatusCode::OK_200, res->status);
  1238. EXPECT_EQ(1, start_count.load());
  1239. EXPECT_TRUE(running_when_called.load());
  1240. }
  1241. TEST(DivideTest, DivideStringTests) {
  1242. auto divide = [](const std::string &str, char d) {
  1243. std::string lhs;
  1244. std::string rhs;
  1245. detail::divide(str, d,
  1246. [&](const char *lhs_data, std::size_t lhs_size,
  1247. const char *rhs_data, std::size_t rhs_size) {
  1248. lhs.assign(lhs_data, lhs_size);
  1249. rhs.assign(rhs_data, rhs_size);
  1250. });
  1251. return std::make_pair(std::move(lhs), std::move(rhs));
  1252. };
  1253. {
  1254. const auto res = divide("", '=');
  1255. EXPECT_EQ(res.first, "");
  1256. EXPECT_EQ(res.second, "");
  1257. }
  1258. {
  1259. const auto res = divide("=", '=');
  1260. EXPECT_EQ(res.first, "");
  1261. EXPECT_EQ(res.second, "");
  1262. }
  1263. {
  1264. const auto res = divide(" ", '=');
  1265. EXPECT_EQ(res.first, " ");
  1266. EXPECT_EQ(res.second, "");
  1267. }
  1268. {
  1269. const auto res = divide("a", '=');
  1270. EXPECT_EQ(res.first, "a");
  1271. EXPECT_EQ(res.second, "");
  1272. }
  1273. {
  1274. const auto res = divide("a=", '=');
  1275. EXPECT_EQ(res.first, "a");
  1276. EXPECT_EQ(res.second, "");
  1277. }
  1278. {
  1279. const auto res = divide("=b", '=');
  1280. EXPECT_EQ(res.first, "");
  1281. EXPECT_EQ(res.second, "b");
  1282. }
  1283. {
  1284. const auto res = divide("a=b", '=');
  1285. EXPECT_EQ(res.first, "a");
  1286. EXPECT_EQ(res.second, "b");
  1287. }
  1288. {
  1289. const auto res = divide("a=b=", '=');
  1290. EXPECT_EQ(res.first, "a");
  1291. EXPECT_EQ(res.second, "b=");
  1292. }
  1293. {
  1294. const auto res = divide("a=b=c", '=');
  1295. EXPECT_EQ(res.first, "a");
  1296. EXPECT_EQ(res.second, "b=c");
  1297. }
  1298. }
  1299. TEST(SplitTest, ParseQueryString) {
  1300. string s = "key1=val1&key2=val2&key3=val3";
  1301. Params dic;
  1302. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1303. [&](const char *b, const char *e) {
  1304. string key, val;
  1305. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1306. if (key.empty()) {
  1307. key.assign(b2, e2);
  1308. } else {
  1309. val.assign(b2, e2);
  1310. }
  1311. });
  1312. dic.emplace(key, val);
  1313. });
  1314. EXPECT_EQ("val1", dic.find("key1")->second);
  1315. EXPECT_EQ("val2", dic.find("key2")->second);
  1316. EXPECT_EQ("val3", dic.find("key3")->second);
  1317. }
  1318. TEST(SplitTest, ParseInvalidQueryTests) {
  1319. {
  1320. string s = " ";
  1321. Params dict;
  1322. detail::parse_query_text(s, dict);
  1323. EXPECT_TRUE(dict.empty());
  1324. }
  1325. {
  1326. string s = " = =";
  1327. Params dict;
  1328. detail::parse_query_text(s, dict);
  1329. EXPECT_TRUE(dict.empty());
  1330. }
  1331. }
  1332. TEST(ParseQueryTest, ParseQueryString) {
  1333. {
  1334. std::string s = "key1=val1&key2=val2&key3=val3";
  1335. Params dic;
  1336. detail::parse_query_text(s, dic);
  1337. EXPECT_EQ("val1", dic.find("key1")->second);
  1338. EXPECT_EQ("val2", dic.find("key2")->second);
  1339. EXPECT_EQ("val3", dic.find("key3")->second);
  1340. }
  1341. {
  1342. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1343. Params dic;
  1344. detail::parse_query_text(s, dic);
  1345. EXPECT_EQ("", dic.find("key1")->second);
  1346. EXPECT_EQ("val1", dic.find("key2")->second);
  1347. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1348. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1349. }
  1350. }
  1351. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1352. Params dic;
  1353. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1354. dic.emplace("key1", "val1");
  1355. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1356. dic.emplace("key2", "val2");
  1357. dic.emplace("key3", "val3");
  1358. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1359. }
  1360. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1361. Params params;
  1362. params.emplace("a", "1");
  1363. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1364. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1365. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1366. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1367. // Long enough to overflow the stack when matched with std::regex.
  1368. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1369. EXPECT_EQ("/p?" + long_query + "&a=1",
  1370. append_query_params("/p?" + long_query, params));
  1371. }
  1372. // Joins every entry of a Headers or Params into "key=value " so a whole
  1373. // traversal can be compared in one assertion. Both are instantiations of the
  1374. // same insertion-ordered container, so one helper serves both.
  1375. template <typename Map> static std::string entries_to_string(const Map &m) {
  1376. std::string s;
  1377. for (const auto &entry : m) {
  1378. s += entry.first + "=" + entry.second + " ";
  1379. }
  1380. return s;
  1381. }
  1382. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1383. // Params used to be a std::multimap, which sorted by name and handed the
  1384. // caller's query back alphabetised. A client signing its query string could
  1385. // not reproduce the order it asked for.
  1386. Params dic;
  1387. dic.emplace("zulu", "1");
  1388. dic.emplace("alpha", "2");
  1389. dic.emplace("mike", "3");
  1390. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1391. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1392. }
  1393. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1394. Params dic;
  1395. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1396. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1397. }
  1398. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1399. Request req;
  1400. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1401. req.params);
  1402. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1403. EXPECT_EQ("first", req.get_param_value("tag"));
  1404. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1405. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1406. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1407. EXPECT_EQ("", req.get_param_value("tag", 3));
  1408. }
  1409. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1410. // Params shares its container with Headers, which matches field names
  1411. // case-insensitively. Parameter names must not pick that up.
  1412. Params dic;
  1413. dic.emplace("Key", "upper");
  1414. dic.emplace("key", "lower");
  1415. EXPECT_EQ(2U, dic.size());
  1416. EXPECT_EQ(1U, dic.count("Key"));
  1417. EXPECT_EQ(1U, dic.count("key"));
  1418. EXPECT_EQ("upper", dic.find("Key")->second);
  1419. EXPECT_EQ("lower", dic.find("key")->second);
  1420. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1421. }
  1422. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1423. Server svr;
  1424. std::string order;
  1425. svr.Get("/order", [&](const Request &req, Response &res) {
  1426. order = entries_to_string(req.params);
  1427. res.set_content("ok", "text/plain");
  1428. });
  1429. auto port = svr.bind_to_any_port(HOST);
  1430. thread t = thread([&] { svr.listen_after_bind(); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. t.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, port);
  1438. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1439. ASSERT_TRUE(res);
  1440. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1441. }
  1442. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1443. Server svr;
  1444. std::string field_order, file_order;
  1445. svr.Post("/order", [&](const Request &req, Response &res) {
  1446. for (const auto &field : req.form.fields) {
  1447. field_order += field.first + "=" + field.second.content + " ";
  1448. }
  1449. for (const auto &file : req.form.files) {
  1450. file_order += file.first + "=" + file.second.filename + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. UploadFormDataItems items = {
  1463. {"zulu", "1", "", ""},
  1464. {"alpha", "2", "", ""},
  1465. {"mike", "3", "", ""},
  1466. {"zebra", "z", "z.txt", "text/plain"},
  1467. {"apple", "a", "a.txt", "text/plain"},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/order", items);
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1473. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1474. }
  1475. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1476. Server svr;
  1477. std::vector<std::string> values;
  1478. std::string first, second, out_of_range, order;
  1479. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1480. values = req.form.get_fields("tag");
  1481. first = req.form.get_field("tag", 0);
  1482. second = req.form.get_field("tag", 1);
  1483. out_of_range = req.form.get_field("tag", 2);
  1484. for (const auto &field : req.form.fields) {
  1485. order += field.first + "=" + field.second.content + " ";
  1486. }
  1487. res.set_content("ok", "text/plain");
  1488. });
  1489. auto port = svr.bind_to_any_port(HOST);
  1490. thread t = thread([&] { svr.listen_after_bind(); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. t.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1498. // not adjacent in the container.
  1499. UploadFormDataItems items = {
  1500. {"tag", "first", "", ""},
  1501. {"other", "x", "", ""},
  1502. {"tag", "second", "", ""},
  1503. };
  1504. Client cli(HOST, port);
  1505. auto res = cli.Post("/repeated", items);
  1506. ASSERT_TRUE(res);
  1507. ASSERT_EQ(2U, values.size());
  1508. EXPECT_EQ("first", values[0]);
  1509. EXPECT_EQ("second", values[1]);
  1510. EXPECT_EQ("first", first);
  1511. EXPECT_EQ("second", second);
  1512. // std::multimap already kept entries sharing a name in insertion order, so
  1513. // everything above passes without this change too. The whole traversal is
  1514. // what tells the two apart: sorting by name would hoist "other" to the front
  1515. // and the two "tag" parts would end up adjacent.
  1516. EXPECT_EQ("tag=first other=x tag=second ", order);
  1517. // Advancing past the last entry of a name used to run off the container;
  1518. // the container's saturating increment makes it return the default instead.
  1519. EXPECT_EQ("", out_of_range);
  1520. }
  1521. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1522. Server svr;
  1523. std::string file_names;
  1524. svr.Post("/upload", [&](const Request &req, Response &res) {
  1525. for (const auto &file : req.form.files) {
  1526. file_names += file.first + "|" + file.second.filename + " ";
  1527. }
  1528. res.set_content("ok", "text/plain");
  1529. });
  1530. auto port = svr.bind_to_any_port(HOST);
  1531. thread t = thread([&] { svr.listen_after_bind(); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. t.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. // A trailing backslash would otherwise escape the closing quote.
  1539. UploadFormDataItems items = {
  1540. {"dir\\", "x", "a.txt", "text/plain"},
  1541. {"b", "y", "a\\\\b.txt", "text/plain"},
  1542. };
  1543. Client cli(HOST, port);
  1544. auto res = cli.Post("/upload", items);
  1545. ASSERT_TRUE(res);
  1546. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1547. }
  1548. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1549. // Server::read_content() keeps a FormFields::iterator alive across the
  1550. // content callbacks that fill the part it points at. The container is
  1551. // vector-backed, so a later emplace can reallocate and invalidate an older
  1552. // iterator; 64 parts grow the vector through seven reallocations, which
  1553. // checks that every part's content still lands in its own entry.
  1554. const size_t part_count = 64;
  1555. // One formula for both the parts sent and the values expected back, so the
  1556. // two cannot drift apart.
  1557. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1558. auto content_of = [](size_t i) {
  1559. return std::string(64, static_cast<char>('a' + (i % 26)));
  1560. };
  1561. Server svr;
  1562. std::vector<std::pair<std::string, std::string>> received;
  1563. svr.Post("/many", [&](const Request &req, Response &res) {
  1564. for (const auto &field : req.form.fields) {
  1565. received.emplace_back(field.first, field.second.content);
  1566. }
  1567. res.set_content("ok", "text/plain");
  1568. });
  1569. auto port = svr.bind_to_any_port(HOST);
  1570. thread t = thread([&] { svr.listen_after_bind(); });
  1571. auto se = detail::scope_exit([&] {
  1572. svr.stop();
  1573. t.join();
  1574. ASSERT_FALSE(svr.is_running());
  1575. });
  1576. svr.wait_until_ready();
  1577. UploadFormDataItems items;
  1578. for (size_t i = 0; i < part_count; i++) {
  1579. items.push_back({name_of(i), content_of(i), "", ""});
  1580. }
  1581. Client cli(HOST, port);
  1582. auto res = cli.Post("/many", items);
  1583. ASSERT_TRUE(res);
  1584. ASSERT_EQ(part_count, received.size());
  1585. for (size_t i = 0; i < part_count; i++) {
  1586. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1587. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1588. }
  1589. }
  1590. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1591. string content_type = "multipart/form-data; boundary=something";
  1592. string boundary;
  1593. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1594. EXPECT_TRUE(ret);
  1595. EXPECT_EQ(boundary, "something");
  1596. }
  1597. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1598. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1599. string boundary;
  1600. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1601. EXPECT_TRUE(ret);
  1602. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1603. }
  1604. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1605. string content_type =
  1606. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1607. string boundary;
  1608. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1609. EXPECT_TRUE(ret);
  1610. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1613. string content_type =
  1614. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1615. string boundary;
  1616. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1617. EXPECT_TRUE(ret);
  1618. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1619. }
  1620. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1621. const string boundary(70, 'a');
  1622. string content_type = "multipart/form-data; boundary=" + boundary;
  1623. string parsed;
  1624. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1625. EXPECT_TRUE(ret);
  1626. EXPECT_EQ(parsed, boundary);
  1627. }
  1628. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1629. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1630. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1631. string parsed;
  1632. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1633. EXPECT_FALSE(ret);
  1634. }
  1635. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1636. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1637. // is 72 characters on the wire and still valid.
  1638. const string boundary(70, 'a');
  1639. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1640. string parsed;
  1641. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1642. EXPECT_EQ(parsed, boundary);
  1643. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1644. parsed.clear();
  1645. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1646. }
  1647. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1648. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1649. // The parameter parser must not treat that '=' as the key/value separator.
  1650. string content_type =
  1651. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1652. "charset=UTF-8";
  1653. string parsed;
  1654. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1655. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1656. }
  1657. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1658. // A ';' inside the quoted-string is part of the value, not a parameter
  1659. // separator, so it must not truncate the boundary.
  1660. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1661. string parsed;
  1662. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1663. EXPECT_EQ(parsed, "a;b");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1666. string parsed;
  1667. EXPECT_TRUE(detail::parse_multipart_boundary(
  1668. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1669. EXPECT_EQ("a\\b", parsed);
  1670. EXPECT_TRUE(detail::parse_multipart_boundary(
  1671. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1672. EXPECT_EQ("a\"b", parsed);
  1673. }
  1674. TEST(ParseDispositionParamsTest, QuotedValues) {
  1675. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1676. // ';' and '=' are ordinary characters inside one.
  1677. struct {
  1678. const char *value;
  1679. std::vector<std::pair<const char *, const char *>> expected;
  1680. } cases[] = {
  1681. {"name=\"file1\"; filename=\"a.txt\"",
  1682. {{"name", "file1"}, {"filename", "a.txt"}}},
  1683. // Whitespace around '=' and ';' is still trimmed
  1684. {"name=\"file2\" ;filename = \"a.html\"",
  1685. {{"name", "file2"}, {"filename", "a.html"}}},
  1686. // '=' inside the value used to leave only the text after the last one
  1687. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1688. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1689. {"name=\"x=y\"", {{"name", "x=y"}}},
  1690. // ';' inside the value used to truncate the pair and leave a bogus one
  1691. {"name=\"file3\"; filename=\"a;b.txt\"",
  1692. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1693. // An unquoted value keeps working, and so does filename*
  1694. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1695. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1696. // A parameter with no key is dropped rather than turned into one whose
  1697. // key is the value
  1698. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1699. // An escaped quote does not end the value
  1700. {"name=\"a\\\"; filename=evil.php\"",
  1701. {{"name", "a\"; filename=evil.php"}}},
  1702. // Other backslashes, as in a Windows path, are kept
  1703. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1704. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1705. };
  1706. for (const auto &c : cases) {
  1707. Params params;
  1708. detail::parse_disposition_params(c.value, params);
  1709. for (const auto &kv : c.expected) {
  1710. auto it = params.find(kv.first);
  1711. ASSERT_NE(it, params.end())
  1712. << "value: " << c.value << ", key: " << kv.first;
  1713. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1714. }
  1715. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1716. }
  1717. }
  1718. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1719. Server svr;
  1720. std::string filename;
  1721. std::string content;
  1722. svr.Post("/upload", [&](const Request &req, Response &) {
  1723. const auto &file = req.form.get_file("file");
  1724. filename = file.filename;
  1725. content = file.content;
  1726. });
  1727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1728. auto se = detail::scope_exit([&] {
  1729. svr.stop();
  1730. thread.join();
  1731. ASSERT_FALSE(svr.is_running());
  1732. });
  1733. svr.wait_until_ready();
  1734. std::string body = "--B\r\n"
  1735. "Content-Disposition: form-data; name=\"file\"; "
  1736. "filename=\"a.txt\"\r\n"
  1737. "Content-Type: text/plain\r\n"
  1738. "\r\n"
  1739. "hello\r\n"
  1740. "--B--\r\n";
  1741. Client cli(HOST, PORT);
  1742. auto res = cli.Post(
  1743. "/upload",
  1744. [&](size_t offset, DataSink &sink) {
  1745. if (offset < body.size()) {
  1746. sink.write(&body[offset], 1);
  1747. } else {
  1748. sink.done();
  1749. }
  1750. return true;
  1751. },
  1752. "multipart/form-data; boundary=B");
  1753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1754. EXPECT_EQ(StatusCode::OK_200, res->status);
  1755. EXPECT_EQ("a.txt", filename);
  1756. EXPECT_EQ("hello", content);
  1757. }
  1758. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1759. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1760. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1761. Server svr;
  1762. std::string field_value, file_name, file_filename;
  1763. bool has_field = false, has_file = false;
  1764. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1765. has_field = req.form.has_field("x=y");
  1766. field_value = req.form.get_field("x=y");
  1767. has_file = req.form.has_file("file1");
  1768. const auto &file = req.form.get_file("file1");
  1769. file_name = file.name;
  1770. file_filename = file.filename;
  1771. res.set_content("ok", "text/plain");
  1772. });
  1773. auto port = svr.bind_to_any_port(HOST);
  1774. thread t = thread([&] { svr.listen_after_bind(); });
  1775. auto se = detail::scope_exit([&] {
  1776. svr.stop();
  1777. t.join();
  1778. ASSERT_FALSE(svr.is_running());
  1779. });
  1780. svr.wait_until_ready();
  1781. UploadFormDataItems items = {
  1782. {"x=y", "field-value", "", ""},
  1783. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1784. };
  1785. Client cli(HOST, port);
  1786. auto res = cli.Post("/quoted", items);
  1787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1788. ASSERT_EQ(StatusCode::OK_200, res->status);
  1789. EXPECT_TRUE(has_field);
  1790. EXPECT_EQ("field-value", field_value);
  1791. EXPECT_TRUE(has_file);
  1792. EXPECT_EQ("file1", file_name);
  1793. EXPECT_EQ("a;b=report.pdf", file_filename);
  1794. }
  1795. TEST(GetHeaderValueTest, DefaultValue) {
  1796. Headers headers = {{"Dummy", "Dummy"}};
  1797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1798. EXPECT_STREQ("text/plain", val);
  1799. }
  1800. TEST(GetHeaderValueTest, DefaultValueInt) {
  1801. Headers headers = {{"Dummy", "Dummy"}};
  1802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1803. EXPECT_EQ(100ull, val);
  1804. }
  1805. TEST(GetHeaderValueTest, RegularValue) {
  1806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1808. EXPECT_STREQ("text/html", val);
  1809. }
  1810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1813. EXPECT_STREQ("text/html", val);
  1814. }
  1815. TEST(GetHeaderValueTest, SetContent) {
  1816. Response res;
  1817. res.set_content("html", "text/html");
  1818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1819. res.set_content("text", "text/plain");
  1820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1822. }
  1823. TEST(GetHeaderValueTest, RegularValueInt) {
  1824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1826. EXPECT_EQ(100ull, val);
  1827. }
  1828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1829. Headers headers = {{"Content-Length", "x"}};
  1830. auto is_invalid_value = false;
  1831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1832. is_invalid_value);
  1833. EXPECT_EQ(0ull, val);
  1834. EXPECT_TRUE(is_invalid_value);
  1835. }
  1836. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1837. // An all-digit value that overflows size_t must be reported as invalid, not
  1838. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1839. // a large length to a small one on 32-bit builds, leaving the framing length
  1840. // wrong while is_invalid_value stayed false.
  1841. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1842. auto is_invalid_value = false;
  1843. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1844. is_invalid_value);
  1845. EXPECT_TRUE(is_invalid_value);
  1846. // A well-formed length is unaffected.
  1847. Headers ok = {{"Content-Length", "1234"}};
  1848. is_invalid_value = false;
  1849. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1850. is_invalid_value);
  1851. EXPECT_EQ(1234ull, val);
  1852. EXPECT_FALSE(is_invalid_value);
  1853. }
  1854. TEST(GetHeaderValueTest, Range) {
  1855. {
  1856. Headers headers = {make_range_header({{1, -1}})};
  1857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1858. EXPECT_STREQ("bytes=1-", val);
  1859. }
  1860. {
  1861. Headers headers = {make_range_header({{-1, 1}})};
  1862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1863. EXPECT_STREQ("bytes=-1", val);
  1864. }
  1865. {
  1866. Headers headers = {make_range_header({{1, 10}})};
  1867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1868. EXPECT_STREQ("bytes=1-10", val);
  1869. }
  1870. {
  1871. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1873. EXPECT_STREQ("bytes=1-10, 100-", val);
  1874. }
  1875. {
  1876. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1878. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1879. }
  1880. {
  1881. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1882. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1883. EXPECT_STREQ("bytes=0-0, -1", val);
  1884. }
  1885. }
  1886. TEST(BearerTokenAuthTest, SchemeValidation) {
  1887. // A value shorter than "Bearer " must not throw from the fixed-length
  1888. // substr, and a non-Bearer scheme must not be reported as a token.
  1889. struct {
  1890. const char *value;
  1891. const char *expected;
  1892. } cases[] = {
  1893. {"x", ""},
  1894. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1895. {"Bearer abc123", "abc123"},
  1896. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1897. };
  1898. for (const auto &c : cases) {
  1899. Request req;
  1900. req.set_header("Authorization", c.value);
  1901. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1905. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1906. // to depend on the standard library (libstdc++ handed back duplicates in
  1907. // reverse insertion order, libc++ in insertion order).
  1908. Request req;
  1909. req.set_header("Accept-Encoding", "gzip");
  1910. req.set_header("Accept-Encoding", "deflate");
  1911. req.set_header("Accept-Encoding", "br");
  1912. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1913. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1914. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1915. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1916. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1917. }
  1918. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1919. Request req;
  1920. req.set_header("X-Test", "only");
  1921. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1922. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1923. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1924. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1925. }
  1926. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1927. Request req;
  1928. req.set_header("X-First", "1");
  1929. req.set_header("X-Test", "2");
  1930. req.params.emplace("first", "1");
  1931. req.params.emplace("test", "2");
  1932. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1933. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1934. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1935. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1936. // The second one is negative when read as a signed value
  1937. const auto max_id = (std::numeric_limits<size_t>::max)();
  1938. for (auto id : {max_id / 2, max_id}) {
  1939. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1940. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1941. EXPECT_EQ("", req.get_param_value("test", id));
  1942. EXPECT_EQ("", req.form.get_field("test", id));
  1943. EXPECT_EQ("", req.form.get_file("test", id).content);
  1944. }
  1945. }
  1946. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1947. Headers headers;
  1948. headers.emplace("Host", "example.com");
  1949. headers.emplace("Accept-Encoding", "gzip");
  1950. headers.emplace("User-Agent", "test");
  1951. headers.emplace("Accept-Encoding", "deflate");
  1952. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1953. "Accept-Encoding=deflate ",
  1954. entries_to_string(headers));
  1955. }
  1956. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1957. Headers headers = {{"Content-Type", "text/html"},
  1958. {"CONTENT-TYPE", "text/xml"}};
  1959. EXPECT_EQ(2U, headers.count("content-type"));
  1960. auto it = headers.find("content-type");
  1961. ASSERT_TRUE(it != headers.end());
  1962. EXPECT_EQ("text/html", it->second);
  1963. }
  1964. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1965. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1966. // drop only those fields and leave everything positioned between them.
  1967. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1968. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1969. auto rng = headers.equal_range("a");
  1970. headers.erase(rng.first, rng.second);
  1971. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1972. }
  1973. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1974. Headers headers = {
  1975. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1976. EXPECT_EQ(3U, headers.erase("A"));
  1977. EXPECT_EQ(0U, headers.count("A"));
  1978. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1979. }
  1980. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1981. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1982. headers.emplace_front("Host", "example.com");
  1983. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1984. entries_to_string(headers));
  1985. }
  1986. TEST(ParseHeaderValueTest, Range) {
  1987. {
  1988. Ranges ranges;
  1989. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1990. EXPECT_TRUE(ret);
  1991. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1992. }
  1993. {
  1994. Ranges ranges;
  1995. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1996. EXPECT_TRUE(ret);
  1997. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1998. }
  1999. {
  2000. Ranges ranges;
  2001. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2002. EXPECT_TRUE(ret);
  2003. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2004. }
  2005. {
  2006. Ranges ranges;
  2007. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2008. EXPECT_FALSE(ret);
  2009. }
  2010. {
  2011. Ranges ranges;
  2012. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2013. EXPECT_TRUE(ret);
  2014. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2015. }
  2016. {
  2017. Ranges ranges;
  2018. auto ret =
  2019. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2020. EXPECT_TRUE(ret);
  2021. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2022. }
  2023. {
  2024. Ranges ranges;
  2025. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2026. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2027. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2028. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2029. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2030. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2031. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2032. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2033. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2034. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2035. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2036. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2037. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2038. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2039. EXPECT_FALSE(
  2040. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2041. EXPECT_TRUE(ranges.empty());
  2042. }
  2043. {
  2044. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2045. // remainder of the representation, so it stays accepted.
  2046. Ranges ranges;
  2047. auto ret =
  2048. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2049. EXPECT_TRUE(ret);
  2050. ASSERT_EQ(1u, ranges.size());
  2051. EXPECT_EQ(0, ranges[0].first);
  2052. EXPECT_EQ(-1, ranges[0].second);
  2053. }
  2054. // RFC 9110 14.1: range unit names are case-insensitive.
  2055. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2056. Ranges ranges;
  2057. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2058. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2059. }
  2060. }
  2061. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2062. Request req;
  2063. req.set_header("Accept-Encoding", "gzip");
  2064. Response res;
  2065. res.set_header("Content-Type", "text/plain");
  2066. auto ret = detail::encoding_type(req, res);
  2067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2074. Request req;
  2075. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2076. Response res;
  2077. res.set_header("Content-Type", "text/plain");
  2078. auto ret = detail::encoding_type(req, res);
  2079. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2081. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2082. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2083. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2084. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2085. #else
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. #endif
  2088. }
  2089. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding",
  2092. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2098. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2100. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2102. #else
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. #endif
  2105. }
  2106. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2107. // All supported encodings rejected with q=0 should return None
  2108. Request req;
  2109. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2110. Response res;
  2111. res.set_header("Content-Type", "text/plain");
  2112. auto ret = detail::encoding_type(req, res);
  2113. EXPECT_TRUE(ret == detail::EncodingType::None);
  2114. }
  2115. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2116. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. EXPECT_TRUE(ret == detail::EncodingType::None);
  2123. }
  2124. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2125. Request req;
  2126. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2127. Response res;
  2128. res.set_header("Content-Type", "text/plain");
  2129. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2130. }
  2131. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2132. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2133. Request req;
  2134. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2135. Response res;
  2136. res.set_header("Content-Type", "text/plain");
  2137. auto ret = detail::encoding_type(req, res);
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. }
  2140. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2141. // RFC 7231: Accept-Encoding values are case-insensitive
  2142. Request req;
  2143. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2144. Response res;
  2145. res.set_header("Content-Type", "text/plain");
  2146. auto ret = detail::encoding_type(req, res);
  2147. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2149. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2151. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2152. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2153. #else
  2154. EXPECT_TRUE(ret == detail::EncodingType::None);
  2155. #endif
  2156. }
  2157. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2158. // q value should determine priority, not hardcoded order
  2159. Request req;
  2160. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2161. Response res;
  2162. res.set_header("Content-Type", "text/plain");
  2163. auto ret = detail::encoding_type(req, res);
  2164. // gzip has highest q=1.0, so it should be selected even though
  2165. // br and zstd are also supported
  2166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2168. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2169. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2170. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2171. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2172. #else
  2173. EXPECT_TRUE(ret == detail::EncodingType::None);
  2174. #endif
  2175. }
  2176. TEST(BufferStreamTest, read) {
  2177. detail::BufferStream strm1;
  2178. Stream &strm = strm1;
  2179. EXPECT_EQ(5, strm.write("hello"));
  2180. char buf[512];
  2181. EXPECT_EQ(2, strm.read(buf, 2));
  2182. EXPECT_EQ('h', buf[0]);
  2183. EXPECT_EQ('e', buf[1]);
  2184. EXPECT_EQ(2, strm.read(buf, 2));
  2185. EXPECT_EQ('l', buf[0]);
  2186. EXPECT_EQ('l', buf[1]);
  2187. EXPECT_EQ(1, strm.read(buf, 1));
  2188. EXPECT_EQ('o', buf[0]);
  2189. EXPECT_EQ(0, strm.read(buf, 1));
  2190. }
  2191. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2192. auto host = "www.httpwatch.com";
  2193. auto ip = hosted_at(host);
  2194. EXPECT_EQ("23.96.13.243", ip);
  2195. std::vector<std::string> addrs;
  2196. hosted_at(host, addrs);
  2197. EXPECT_EQ(1u, addrs.size());
  2198. }
  2199. #if 0 // It depends on each test environment...
  2200. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2201. auto host = "www.youtube.com";
  2202. std::vector<std::string> addrs;
  2203. hosted_at(host, addrs);
  2204. EXPECT_EQ(20u, addrs.size());
  2205. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2206. EXPECT_TRUE(it != addrs.end());
  2207. }
  2208. #endif
  2209. class ChunkedEncodingTest : public ::testing::Test {
  2210. protected:
  2211. ChunkedEncodingTest()
  2212. : cli_(HOST, PORT)
  2213. #ifdef CPPHTTPLIB_SSL_ENABLED
  2214. ,
  2215. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2216. #endif
  2217. {
  2218. cli_.set_connection_timeout(2);
  2219. #ifdef CPPHTTPLIB_SSL_ENABLED
  2220. cli_.enable_server_certificate_verification(false);
  2221. #endif
  2222. }
  2223. virtual void SetUp() {
  2224. read_file("./image.jpg", image_data_);
  2225. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2226. res.set_content("Hello World!", "text/plain");
  2227. });
  2228. svr_.Get(
  2229. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2230. res.set_chunked_content_provider(
  2231. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2232. size_t remaining = image_data_.size() - offset;
  2233. if (remaining == 0) {
  2234. sink.done();
  2235. } else {
  2236. constexpr size_t CHUNK_SIZE = 1024;
  2237. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2238. sink.write(&image_data_[offset], send_size);
  2239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2240. }
  2241. return true;
  2242. });
  2243. });
  2244. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2245. svr_.wait_until_ready();
  2246. }
  2247. virtual void TearDown() {
  2248. svr_.stop();
  2249. if (!request_threads_.empty()) {
  2250. std::this_thread::sleep_for(std::chrono::seconds(1));
  2251. for (auto &t : request_threads_) {
  2252. t.join();
  2253. }
  2254. }
  2255. t_.join();
  2256. }
  2257. #ifdef CPPHTTPLIB_SSL_ENABLED
  2258. SSLClient cli_;
  2259. SSLServer svr_;
  2260. #else
  2261. Client cli_;
  2262. Server svr_;
  2263. #endif
  2264. thread t_;
  2265. std::vector<thread> request_threads_;
  2266. std::string image_data_;
  2267. };
  2268. TEST_F(ChunkedEncodingTest, NormalGet) {
  2269. auto res = cli_.Get("/chunked");
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. std::string out;
  2272. read_file("./image.jpg", out);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. EXPECT_EQ(out, res->body);
  2275. }
  2276. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2277. std::string body;
  2278. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2279. body.append(data, data_length);
  2280. return true;
  2281. });
  2282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2283. std::string out;
  2284. read_file("./image.jpg", out);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. EXPECT_EQ(out, body);
  2287. }
  2288. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2289. std::string body;
  2290. auto res = cli_.Get(
  2291. "/chunked",
  2292. [&](const Response &response) {
  2293. EXPECT_EQ(StatusCode::OK_200, response.status);
  2294. return true;
  2295. },
  2296. [&](const char *data, size_t data_length) {
  2297. body.append(data, data_length);
  2298. return true;
  2299. });
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. std::string out;
  2302. read_file("./image.jpg", out);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ(out, body);
  2305. }
  2306. TEST(RangeTest, FromHTTPBin_Online) {
  2307. auto host = "httpbingo.org";
  2308. auto path = std::string{"/range/32"};
  2309. #ifdef CPPHTTPLIB_SSL_ENABLED
  2310. auto port = 443;
  2311. SSLClient cli(host, port);
  2312. #else
  2313. auto port = 80;
  2314. Client cli(host, port);
  2315. #endif
  2316. cli.set_connection_timeout(5);
  2317. {
  2318. auto res = cli.Get(path);
  2319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2320. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2321. EXPECT_EQ(StatusCode::OK_200, res->status);
  2322. }
  2323. {
  2324. Headers headers = {make_range_header({{1, -1}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2329. }
  2330. {
  2331. Headers headers = {make_range_header({{1, 10}})};
  2332. auto res = cli.Get(path, headers);
  2333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2334. EXPECT_EQ("bcdefghijk", res->body);
  2335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2336. }
  2337. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2338. // entire resource, while the original httpbin returned 200. Both are
  2339. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2340. {
  2341. Headers headers = {make_range_header({{0, 31}})};
  2342. auto res = cli.Get(path, headers);
  2343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2344. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2345. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2346. res->status == StatusCode::PartialContent_206);
  2347. }
  2348. {
  2349. Headers headers = {make_range_header({{0, -1}})};
  2350. auto res = cli.Get(path, headers);
  2351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2352. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2353. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2354. res->status == StatusCode::PartialContent_206);
  2355. }
  2356. // go-httpbin returns 206 with clamped range for over-range requests,
  2357. // while the original httpbin returned 416. Both behaviors are observed
  2358. // in real servers, so we only verify the request succeeds.
  2359. {
  2360. Headers headers = {make_range_header({{0, 32}})};
  2361. auto res = cli.Get(path, headers);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. }
  2364. }
  2365. TEST(RangeTest, IgnoredForPost) {
  2366. Server svr;
  2367. svr.Post("/", [](const Request &, Response &res) {
  2368. res.set_content("abcdefg", "text/plain");
  2369. });
  2370. auto port = svr.bind_to_any_port(HOST);
  2371. ASSERT_GT(port, 0);
  2372. thread t = thread([&] { svr.listen_after_bind(); });
  2373. auto se = detail::scope_exit([&] {
  2374. svr.stop();
  2375. t.join();
  2376. ASSERT_FALSE(svr.is_running());
  2377. });
  2378. svr.wait_until_ready();
  2379. Client cli(HOST, port);
  2380. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2381. auto res = cli.Post("/", Headers{{"Range", range}});
  2382. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2383. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2384. EXPECT_EQ("abcdefg", res->body) << range;
  2385. }
  2386. }
  2387. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2388. auto host = "unresolvableaddress.local";
  2389. auto path = std::string{"/"};
  2390. #ifdef CPPHTTPLIB_SSL_ENABLED
  2391. auto port = 443;
  2392. SSLClient cli(host, port);
  2393. #else
  2394. auto port = 80;
  2395. Client cli(host, port);
  2396. #endif
  2397. cli.set_connection_timeout(1);
  2398. {
  2399. auto res = cli.Get(path);
  2400. ASSERT_FALSE(res);
  2401. }
  2402. std::this_thread::sleep_for(std::chrono::seconds(8));
  2403. }
  2404. #if defined(__linux__) && defined(__GLIBC__) && \
  2405. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2406. // Forward declaration: in split builds split.py strips `inline` and moves the
  2407. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2408. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2409. // against the symbol in both header-only and split builds.
  2410. namespace httplib {
  2411. namespace detail {
  2412. int getaddrinfo_with_timeout(const char *node, const char *service,
  2413. const struct addrinfo *hints,
  2414. struct addrinfo **res, time_t timeout_sec);
  2415. } // namespace detail
  2416. } // namespace httplib
  2417. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2418. //
  2419. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2420. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2421. // gai_suspend() call hits the connection timeout the function calls
  2422. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2423. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2424. // still alive and still references the now-destroyed stack frame.
  2425. //
  2426. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2427. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2428. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2429. // and runs them in a container.
  2430. namespace {
  2431. bool should_run_issue_2431_tests() {
  2432. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2433. return v && *v && std::string(v) != "0";
  2434. }
  2435. std::string unique_unresolvable_host(int n) {
  2436. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2437. // glibc still asks the configured nameserver — which is exactly the path
  2438. // we want to exercise. A unique label per call avoids the resolver cache.
  2439. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2440. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2441. std::to_string(n) + ".invalid";
  2442. }
  2443. } // namespace
  2444. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2445. if (!should_run_issue_2431_tests()) {
  2446. GTEST_SKIP()
  2447. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2448. }
  2449. for (int i = 0; i < 8; ++i) {
  2450. struct addrinfo hints;
  2451. memset(&hints, 0, sizeof(hints));
  2452. hints.ai_family = AF_UNSPEC;
  2453. hints.ai_socktype = SOCK_STREAM;
  2454. auto host = unique_unresolvable_host(i);
  2455. struct addrinfo *result = nullptr;
  2456. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2457. &result, /*timeout_sec=*/1);
  2458. if (rc == 0 && result) { freeaddrinfo(result); }
  2459. }
  2460. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2461. // stack region they still believe holds their gaicb.
  2462. std::this_thread::sleep_for(std::chrono::seconds(3));
  2463. }
  2464. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2465. if (!should_run_issue_2431_tests()) {
  2466. GTEST_SKIP()
  2467. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2468. }
  2469. std::atomic<bool> stop{false};
  2470. std::vector<std::thread> threads;
  2471. for (int t = 0; t < 8; ++t) {
  2472. threads.emplace_back([t, &stop] {
  2473. int i = 0;
  2474. while (!stop.load(std::memory_order_relaxed)) {
  2475. struct addrinfo hints;
  2476. memset(&hints, 0, sizeof(hints));
  2477. hints.ai_family = AF_UNSPEC;
  2478. hints.ai_socktype = SOCK_STREAM;
  2479. auto host = unique_unresolvable_host(t * 100000 + i++);
  2480. struct addrinfo *result = nullptr;
  2481. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2482. &result, /*timeout_sec=*/1);
  2483. if (rc == 0 && result) { freeaddrinfo(result); }
  2484. }
  2485. });
  2486. }
  2487. std::this_thread::sleep_for(std::chrono::seconds(8));
  2488. stop.store(true, std::memory_order_relaxed);
  2489. for (auto &th : threads) {
  2490. th.join();
  2491. }
  2492. std::this_thread::sleep_for(std::chrono::seconds(3));
  2493. }
  2494. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2495. if (!should_run_issue_2431_tests()) {
  2496. GTEST_SKIP()
  2497. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2498. }
  2499. std::atomic<bool> stop{false};
  2500. std::vector<std::thread> threads;
  2501. for (int t = 0; t < 8; ++t) {
  2502. threads.emplace_back([t, &stop] {
  2503. int i = 0;
  2504. while (!stop.load(std::memory_order_relaxed)) {
  2505. auto host = unique_unresolvable_host(t * 100000 + i++);
  2506. Client cli(host, 80);
  2507. cli.set_connection_timeout(1, 0);
  2508. cli.set_read_timeout(1, 0);
  2509. cli.set_write_timeout(1, 0);
  2510. (void)cli.Get("/");
  2511. }
  2512. });
  2513. }
  2514. std::this_thread::sleep_for(std::chrono::seconds(8));
  2515. stop.store(true, std::memory_order_relaxed);
  2516. for (auto &th : threads) {
  2517. th.join();
  2518. }
  2519. std::this_thread::sleep_for(std::chrono::seconds(3));
  2520. }
  2521. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2522. TEST(ConnectionErrorTest, InvalidHost) {
  2523. auto host = "-abcde.com";
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. auto port = 443;
  2526. SSLClient cli(host, port);
  2527. #else
  2528. auto port = 80;
  2529. Client cli(host, port);
  2530. #endif
  2531. cli.set_connection_timeout(std::chrono::seconds(2));
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::Connection, res.error());
  2535. }
  2536. TEST(ConnectionErrorTest, InvalidHost2) {
  2537. auto host = "httpcan.org/";
  2538. #ifdef CPPHTTPLIB_SSL_ENABLED
  2539. SSLClient cli(host);
  2540. #else
  2541. Client cli(host);
  2542. #endif
  2543. cli.set_connection_timeout(std::chrono::seconds(2));
  2544. auto res = cli.Get("/");
  2545. ASSERT_TRUE(!res);
  2546. EXPECT_EQ(Error::Connection, res.error());
  2547. }
  2548. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2549. auto host = "httpcan.org/";
  2550. #ifdef CPPHTTPLIB_SSL_ENABLED
  2551. SSLClient cli(host);
  2552. #else
  2553. Client cli(host);
  2554. #endif
  2555. cli.set_connection_timeout(std::chrono::seconds(2));
  2556. auto res = cli.Get("/");
  2557. ASSERT_TRUE(!res);
  2558. stringstream s;
  2559. s << "error code: " << res.error();
  2560. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2561. }
  2562. TEST(ConnectionErrorTest, InvalidPort) {
  2563. auto host = "localhost";
  2564. auto port = 44380;
  2565. #ifdef CPPHTTPLIB_SSL_ENABLED
  2566. SSLClient cli(host, port);
  2567. #else
  2568. Client cli(host, port);
  2569. #endif
  2570. cli.set_connection_timeout(std::chrono::seconds(2));
  2571. auto res = cli.Get("/");
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_TRUE(Error::Connection == res.error() ||
  2574. Error::ConnectionTimeout == res.error());
  2575. }
  2576. TEST(ConnectionErrorTest, Timeout_Online) {
  2577. auto host = "google.com";
  2578. #ifdef CPPHTTPLIB_SSL_ENABLED
  2579. auto port = 44380;
  2580. SSLClient cli(host, port);
  2581. #else
  2582. auto port = 8080;
  2583. Client cli(host, port);
  2584. #endif
  2585. cli.set_connection_timeout(std::chrono::seconds(2));
  2586. // only probe one address type so that the error reason
  2587. // correlates to the timed-out IPv4, not the unsupported
  2588. // IPv6 connection attempt
  2589. cli.set_address_family(AF_INET);
  2590. auto res = cli.Get("/");
  2591. ASSERT_TRUE(!res);
  2592. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2593. }
  2594. TEST(CancelTest, NoCancel_Online) {
  2595. auto host = "httpbingo.org";
  2596. auto path = std::string{"/range/32"};
  2597. #ifdef CPPHTTPLIB_SSL_ENABLED
  2598. auto port = 443;
  2599. SSLClient cli(host, port);
  2600. #else
  2601. auto port = 80;
  2602. Client cli(host, port);
  2603. #endif
  2604. cli.set_connection_timeout(std::chrono::seconds(5));
  2605. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. }
  2610. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2611. // Use /bytes with a large payload so that the DownloadProgress callback
  2612. // (which only fires for Content-Length responses) is invoked before the
  2613. // entire body is received, giving cancellation a chance to fire.
  2614. auto host = "httpbingo.org";
  2615. auto path = std::string{"/bytes/524288"};
  2616. #ifdef CPPHTTPLIB_SSL_ENABLED
  2617. auto port = 443;
  2618. SSLClient cli(host, port);
  2619. #else
  2620. auto port = 80;
  2621. Client cli(host, port);
  2622. #endif
  2623. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayload_Online) {
  2629. auto host = "httpbingo.org";
  2630. auto path = std::string{"/bytes/524288"};
  2631. #ifdef CPPHTTPLIB_SSL_ENABLED
  2632. auto port = 443;
  2633. SSLClient cli(host, port);
  2634. #else
  2635. auto port = 80;
  2636. Client cli(host, port);
  2637. #endif
  2638. cli.set_connection_timeout(std::chrono::seconds(5));
  2639. uint32_t count = 0;
  2640. auto res =
  2641. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2642. ASSERT_TRUE(!res);
  2643. EXPECT_EQ(Error::Canceled, res.error());
  2644. }
  2645. TEST(CancelTest, NoCancelPost) {
  2646. Server svr;
  2647. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2648. res.set_content("Hello World!", "text/plain");
  2649. });
  2650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. thread.join();
  2654. ASSERT_FALSE(svr.is_running());
  2655. });
  2656. svr.wait_until_ready();
  2657. Client cli(HOST, PORT);
  2658. cli.set_connection_timeout(std::chrono::seconds(5));
  2659. auto res =
  2660. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2661. "application/json", [](uint64_t, uint64_t) { return true; });
  2662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2663. EXPECT_EQ("Hello World!", res->body);
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. }
  2666. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2667. Server svr;
  2668. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2669. res.set_content("Hello World!", "text/plain");
  2670. });
  2671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2672. auto se = detail::scope_exit([&] {
  2673. svr.stop();
  2674. thread.join();
  2675. ASSERT_FALSE(svr.is_running());
  2676. });
  2677. svr.wait_until_ready();
  2678. Client cli(HOST, PORT);
  2679. cli.set_connection_timeout(std::chrono::seconds(5));
  2680. auto res =
  2681. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2682. "application/json", [](uint64_t, uint64_t) { return false; });
  2683. ASSERT_TRUE(!res);
  2684. EXPECT_EQ(Error::Canceled, res.error());
  2685. }
  2686. TEST(CancelTest, WithCancelLargePayloadPost) {
  2687. Server svr;
  2688. svr.set_payload_max_length(200 * 1024 * 1024);
  2689. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2690. res.set_content(LARGE_DATA, "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, PORT);
  2700. cli.set_payload_max_length(200 * 1024 * 1024);
  2701. cli.set_connection_timeout(std::chrono::seconds(5));
  2702. auto res =
  2703. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2704. "application/json", [](uint64_t, uint64_t) { return false; });
  2705. ASSERT_TRUE(!res);
  2706. EXPECT_EQ(Error::Canceled, res.error());
  2707. }
  2708. TEST(CancelTest, NoCancelPut) {
  2709. Server svr;
  2710. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2711. res.set_content("Hello World!", "text/plain");
  2712. });
  2713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2714. auto se = detail::scope_exit([&] {
  2715. svr.stop();
  2716. thread.join();
  2717. ASSERT_FALSE(svr.is_running());
  2718. });
  2719. svr.wait_until_ready();
  2720. Client cli(HOST, PORT);
  2721. cli.set_connection_timeout(std::chrono::seconds(5));
  2722. auto res =
  2723. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2724. "application/json", [](uint64_t, uint64_t) { return true; });
  2725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2726. EXPECT_EQ("Hello World!", res->body);
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. }
  2729. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2730. Server svr;
  2731. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2732. res.set_content("Hello World!", "text/plain");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. Client cli(HOST, PORT);
  2742. cli.set_connection_timeout(std::chrono::seconds(5));
  2743. auto res =
  2744. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2745. "application/json", [](uint64_t, uint64_t) { return false; });
  2746. ASSERT_TRUE(!res);
  2747. EXPECT_EQ(Error::Canceled, res.error());
  2748. }
  2749. TEST(CancelTest, WithCancelLargePayloadPut) {
  2750. Server svr;
  2751. svr.set_payload_max_length(200 * 1024 * 1024);
  2752. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2753. res.set_content(LARGE_DATA, "text/plain");
  2754. });
  2755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli(HOST, PORT);
  2763. cli.set_payload_max_length(200 * 1024 * 1024);
  2764. cli.set_connection_timeout(std::chrono::seconds(5));
  2765. auto res =
  2766. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2767. "application/json", [](uint64_t, uint64_t) { return false; });
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. TEST(CancelTest, NoCancelPatch) {
  2772. Server svr;
  2773. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2777. auto se = detail::scope_exit([&] {
  2778. svr.stop();
  2779. thread.join();
  2780. ASSERT_FALSE(svr.is_running());
  2781. });
  2782. svr.wait_until_ready();
  2783. Client cli(HOST, PORT);
  2784. cli.set_connection_timeout(std::chrono::seconds(5));
  2785. auto res =
  2786. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2787. "application/json", [](uint64_t, uint64_t) { return true; });
  2788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2789. EXPECT_EQ("Hello World!", res->body);
  2790. EXPECT_EQ(StatusCode::OK_200, res->status);
  2791. }
  2792. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2793. Server svr;
  2794. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(HOST, PORT);
  2805. cli.set_connection_timeout(std::chrono::seconds(5));
  2806. auto res =
  2807. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return false; });
  2809. ASSERT_TRUE(!res);
  2810. EXPECT_EQ(Error::Canceled, res.error());
  2811. }
  2812. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2813. Server svr;
  2814. svr.set_payload_max_length(200 * 1024 * 1024);
  2815. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content(LARGE_DATA, "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. cli.set_payload_max_length(200 * 1024 * 1024);
  2827. cli.set_connection_timeout(std::chrono::seconds(5));
  2828. auto res =
  2829. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2830. "application/json", [](uint64_t, uint64_t) { return false; });
  2831. ASSERT_TRUE(!res);
  2832. EXPECT_EQ(Error::Canceled, res.error());
  2833. }
  2834. TEST(CancelTest, NoCancelDelete) {
  2835. Server svr;
  2836. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content("Hello World!", "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. cli.set_connection_timeout(std::chrono::seconds(5));
  2848. auto res =
  2849. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2850. "application/json", [](uint64_t, uint64_t) { return true; });
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. EXPECT_EQ("Hello World!", res->body);
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2856. Server svr;
  2857. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2858. res.set_content("Hello World!", "text/plain");
  2859. });
  2860. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. thread.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. Client cli(HOST, PORT);
  2868. cli.set_connection_timeout(std::chrono::seconds(5));
  2869. auto res =
  2870. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2871. "application/json", [](uint64_t, uint64_t) { return false; });
  2872. ASSERT_TRUE(!res);
  2873. EXPECT_EQ(Error::Canceled, res.error());
  2874. }
  2875. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2876. Server svr;
  2877. svr.set_payload_max_length(200 * 1024 * 1024);
  2878. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2879. res.set_content(LARGE_DATA, "text/plain");
  2880. });
  2881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. thread.join();
  2885. ASSERT_FALSE(svr.is_running());
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, PORT);
  2889. cli.set_payload_max_length(200 * 1024 * 1024);
  2890. cli.set_connection_timeout(std::chrono::seconds(5));
  2891. auto res =
  2892. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2893. "application/json", [](uint64_t, uint64_t) { return false; });
  2894. ASSERT_TRUE(!res);
  2895. EXPECT_EQ(Error::Canceled, res.error());
  2896. }
  2897. static std::string remove_whitespace(const std::string &input) {
  2898. std::string output;
  2899. output.reserve(input.size());
  2900. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2901. [](unsigned char c) { return !std::isspace(c); });
  2902. return output;
  2903. }
  2904. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2905. auto host = "httpbingo.org";
  2906. auto path = std::string{"/basic-auth/hello/world"};
  2907. #ifdef CPPHTTPLIB_SSL_ENABLED
  2908. auto port = 443;
  2909. SSLClient cli(host, port);
  2910. #else
  2911. auto port = 80;
  2912. Client cli(host, port);
  2913. #endif
  2914. {
  2915. auto res = cli.Get(path);
  2916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2917. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2918. }
  2919. {
  2920. auto res = cli.Get(
  2921. path, Headers{make_basic_authentication_header("hello", "world")});
  2922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2923. auto body = remove_whitespace(res->body);
  2924. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2925. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2926. EXPECT_EQ(StatusCode::OK_200, res->status);
  2927. }
  2928. {
  2929. cli.set_basic_auth("hello", "world");
  2930. auto res = cli.Get(path);
  2931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2932. auto body = remove_whitespace(res->body);
  2933. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2934. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. }
  2937. {
  2938. cli.set_basic_auth("hello", "bad");
  2939. auto res = cli.Get(path);
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2942. }
  2943. {
  2944. cli.set_basic_auth("bad", "world");
  2945. auto res = cli.Get(path);
  2946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2947. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2948. }
  2949. }
  2950. #ifdef CPPHTTPLIB_SSL_ENABLED
  2951. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2952. auto host = "httpbingo.org";
  2953. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2954. auto paths = std::vector<std::string>{
  2955. "/digest-auth/auth/hello/world/MD5",
  2956. "/digest-auth/auth/hello/world/SHA-256",
  2957. };
  2958. auto port = 443;
  2959. SSLClient cli(host, port);
  2960. {
  2961. auto res = cli.Get(unauth_path);
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2964. }
  2965. {
  2966. cli.set_digest_auth("hello", "world");
  2967. for (const auto &path : paths) {
  2968. auto res = cli.Get(path.c_str());
  2969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2970. auto body = remove_whitespace(res->body);
  2971. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2972. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2973. EXPECT_EQ(StatusCode::OK_200, res->status);
  2974. }
  2975. cli.set_digest_auth("hello", "bad");
  2976. for (const auto &path : paths) {
  2977. auto res = cli.Get(path.c_str());
  2978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2979. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2980. }
  2981. }
  2982. }
  2983. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2984. // comma-separated list of challenges, and each challenge may itself carry a
  2985. // comma-separated auth-param list, so a server can legally offer Basic
  2986. // before Digest, either as two field lines or packed into one. Runs one 401
  2987. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2988. // value() joins them in receipt order) and checks that the retry carries a
  2989. // well-formed Digest Authorization header naming expected_realm.
  2990. static void
  2991. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2992. const std::string &expected_realm) {
  2993. std::atomic<int> hits{0};
  2994. Server svr;
  2995. svr.Get("/x", [&](const Request &req, Response &res) {
  2996. if (++hits == 1) {
  2997. res.status = StatusCode::Unauthorized_401;
  2998. for (const auto &challenge : challenges) {
  2999. res.set_header("WWW-Authenticate", challenge);
  3000. }
  3001. } else {
  3002. auto authorization = req.get_header_value("Authorization");
  3003. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3004. EXPECT_NE(std::string::npos,
  3005. authorization.find("realm=\"" + expected_realm + "\""));
  3006. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3007. res.set_content("ok", "text/plain");
  3008. }
  3009. });
  3010. auto port = svr.bind_to_any_port(HOST);
  3011. std::thread t([&]() { svr.listen_after_bind(); });
  3012. auto se = detail::scope_exit([&] {
  3013. svr.stop();
  3014. t.join();
  3015. });
  3016. svr.wait_until_ready();
  3017. Client cli(HOST, port);
  3018. cli.set_digest_auth("hello", "world");
  3019. auto res = cli.Get("/x");
  3020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3021. EXPECT_EQ(2, hits.load());
  3022. }
  3023. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3024. static const char *kDigestChallenge =
  3025. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3026. "algorithm=MD5";
  3027. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3028. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3029. "testrealm");
  3030. }
  3031. // Same challenge list with the schemes in the opposite order, to make sure
  3032. // the fix above didn't just special-case "Basic first".
  3033. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3034. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3035. "testrealm");
  3036. }
  3037. // A comma inside a quoted auth-param value must not be mistaken for the
  3038. // separator between two challenges (or two auth-params).
  3039. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3040. run_digest_challenge_list_test(
  3041. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3042. "algorithm=MD5"},
  3043. "test,realm");
  3044. }
  3045. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3046. // the params and leaves out the fragment.
  3047. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3048. Server svr;
  3049. std::string uri, target;
  3050. svr.Get("/a b", [&](const Request &req, Response &res) {
  3051. auto auth = req.get_header_value("Authorization");
  3052. if (auth.empty()) {
  3053. res.status = StatusCode::Unauthorized_401;
  3054. res.set_header("WWW-Authenticate",
  3055. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3056. return;
  3057. }
  3058. auto b = auth.find("uri=\"") + 5;
  3059. uri = auth.substr(b, auth.find('"', b) - b);
  3060. target = req.target;
  3061. });
  3062. auto port = svr.bind_to_any_port(HOST);
  3063. std::thread t([&]() { svr.listen_after_bind(); });
  3064. auto se = detail::scope_exit([&] {
  3065. svr.stop();
  3066. t.join();
  3067. });
  3068. svr.wait_until_ready();
  3069. Client cli(HOST, port);
  3070. cli.set_digest_auth("hello", "world");
  3071. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3073. EXPECT_EQ("/a%20b?x=1", target);
  3074. EXPECT_EQ(target, uri);
  3075. }
  3076. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3077. // make_digest_authentication_header() dereferences both unconditionally, so
  3078. // a server sending a challenge missing either one must not be treated as
  3079. // usable -- doing so used to crash the client with std::out_of_range.
  3080. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3081. Server svr;
  3082. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3083. res.status = StatusCode::Unauthorized_401;
  3084. res.set_header("WWW-Authenticate", challenge);
  3085. });
  3086. auto port = svr.bind_to_any_port(HOST);
  3087. std::thread t([&]() { svr.listen_after_bind(); });
  3088. auto se = detail::scope_exit([&] {
  3089. svr.stop();
  3090. t.join();
  3091. });
  3092. svr.wait_until_ready();
  3093. Client cli(HOST, port);
  3094. cli.set_digest_auth("hello", "world");
  3095. auto res = cli.Get("/x");
  3096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3097. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3098. }
  3099. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3100. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3101. }
  3102. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3103. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3104. }
  3105. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3106. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3107. }
  3108. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3109. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3110. // when storing the values, so the header builder has to re-escape them (and
  3111. // keep algorithm a bare token); otherwise the value breaks out of its
  3112. // quoted-string and injects extra auth-params into the client's Authorization.
  3113. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3114. std::atomic<int> hits{0};
  3115. std::string authorization;
  3116. Server svr;
  3117. svr.Get("/x", [&](const Request &req, Response &res) {
  3118. if (++hits == 1) {
  3119. res.status = StatusCode::Unauthorized_401;
  3120. // On the wire the quotes embedded in the values are backslash-escaped.
  3121. res.set_header("WWW-Authenticate",
  3122. "Digest realm=\"testrealm\", "
  3123. "nonce=\"n\\\"; injected=\\\"x\", "
  3124. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3125. } else {
  3126. authorization = req.get_header_value("Authorization");
  3127. res.set_content("ok", "text/plain");
  3128. }
  3129. });
  3130. auto port = svr.bind_to_any_port(HOST);
  3131. std::thread t([&]() { svr.listen_after_bind(); });
  3132. auto se = detail::scope_exit([&] {
  3133. svr.stop();
  3134. t.join();
  3135. });
  3136. svr.wait_until_ready();
  3137. Client cli(HOST, port);
  3138. cli.set_digest_auth("hello", "world");
  3139. auto res = cli.Get("/x");
  3140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3141. EXPECT_EQ(2, hits.load());
  3142. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3143. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3144. // inside its quoted-string rather than starting an "injected" auth-param.
  3145. EXPECT_NE(std::string::npos,
  3146. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3147. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3148. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3149. }
  3150. #endif
  3151. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3152. auto host = "google.com";
  3153. auto another_host = "example.com";
  3154. auto wrong_ip = "0.0.0.0";
  3155. #ifdef CPPHTTPLIB_SSL_ENABLED
  3156. SSLClient cli(host);
  3157. #else
  3158. Client cli(host);
  3159. #endif
  3160. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3161. auto res = cli.Get("/");
  3162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3163. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3164. }
  3165. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3166. auto host = "google.com";
  3167. auto wrong_ip = "0.0.0.0";
  3168. #ifdef CPPHTTPLIB_SSL_ENABLED
  3169. SSLClient cli(host);
  3170. #else
  3171. Client cli(host);
  3172. #endif
  3173. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3174. auto res = cli.Get("/");
  3175. ASSERT_TRUE(!res);
  3176. EXPECT_EQ(Error::Connection, res.error());
  3177. }
  3178. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3179. // A mapped value that is not an IP literal must be resolved. "localhost"
  3180. // resolves from the hosts file, so this test needs no external DNS.
  3181. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3182. auto host = "target.invalid";
  3183. Server svr;
  3184. std::string received_host;
  3185. svr.Get("/hi", [&](const Request &req, Response &res) {
  3186. received_host = req.get_header_value("Host");
  3187. res.set_content("Hello World!", "text/plain");
  3188. });
  3189. auto port = svr.bind_to_any_port(HOST);
  3190. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3191. auto se = detail::scope_exit([&] {
  3192. svr.stop();
  3193. thread.join();
  3194. ASSERT_FALSE(svr.is_running());
  3195. });
  3196. svr.wait_until_ready();
  3197. Client cli(host, port);
  3198. cli.set_direct_hostname_addr_map({{host, HOST}});
  3199. auto res = cli.Get("/hi");
  3200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3201. EXPECT_EQ(StatusCode::OK_200, res->status);
  3202. // The mapping only redirects the connection; the identity stays host_.
  3203. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3204. }
  3205. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3206. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3207. auto host = "target.invalid";
  3208. Server svr;
  3209. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3210. res.set_content("Hello World!", "text/plain");
  3211. });
  3212. auto port = svr.bind_to_any_port("127.0.0.1");
  3213. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3214. auto se = detail::scope_exit([&] {
  3215. svr.stop();
  3216. thread.join();
  3217. ASSERT_FALSE(svr.is_running());
  3218. });
  3219. svr.wait_until_ready();
  3220. Client cli(host, port);
  3221. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3222. auto res = cli.Get("/hi");
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::OK_200, res->status);
  3225. }
  3226. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3227. // An empty mapped value must leave host_ as the connection target. Without
  3228. // that guard the empty value would become the host argument, getaddrinfo
  3229. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3230. // loopback - silently connecting somewhere the caller never asked for.
  3231. // The server listens on loopback, so such a fallback would succeed and is
  3232. // therefore observable as a failure of this test.
  3233. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3234. Server svr;
  3235. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3236. res.set_content("Hello World!", "text/plain");
  3237. });
  3238. auto port = svr.bind_to_any_port(HOST);
  3239. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3240. auto se = detail::scope_exit([&] {
  3241. svr.stop();
  3242. thread.join();
  3243. ASSERT_FALSE(svr.is_running());
  3244. });
  3245. svr.wait_until_ready();
  3246. Client cli(blackhole, port);
  3247. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3248. cli.set_connection_timeout(1);
  3249. auto res = cli.Get("/hi");
  3250. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3251. }
  3252. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3253. auto host = "target.invalid";
  3254. Server svr;
  3255. std::string received_host;
  3256. svr.Get("/hi", [&](const Request &req, Response &res) {
  3257. received_host = req.get_header_value("Host");
  3258. res.set_content("Hello World!", "text/plain");
  3259. });
  3260. auto port = svr.bind_to_any_port("127.0.0.1");
  3261. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3262. auto se = detail::scope_exit([&] {
  3263. svr.stop();
  3264. thread.join();
  3265. ASSERT_FALSE(svr.is_running());
  3266. });
  3267. svr.wait_until_ready();
  3268. Client cli(host, port);
  3269. #pragma GCC diagnostic push
  3270. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3271. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3272. #pragma GCC diagnostic pop
  3273. auto res = cli.Get("/hi");
  3274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3275. EXPECT_EQ(StatusCode::OK_200, res->status);
  3276. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3277. }
  3278. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3279. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3280. Server svr;
  3281. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3282. res.set_content("Hello World!", "text/plain");
  3283. });
  3284. auto port = svr.bind_to_any_port("127.0.0.1");
  3285. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3286. auto se = detail::scope_exit([&] {
  3287. svr.stop();
  3288. thread.join();
  3289. ASSERT_FALSE(svr.is_running());
  3290. });
  3291. svr.wait_until_ready();
  3292. Client cli("127.0.0.1", port);
  3293. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3294. cli.set_connection_timeout(1);
  3295. auto res = cli.Get("/hi");
  3296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3297. EXPECT_EQ(StatusCode::OK_200, res->status);
  3298. }
  3299. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3300. auto host = "httpbingo.org";
  3301. auto path = std::string{"/absolute-redirect/3"};
  3302. #ifdef CPPHTTPLIB_SSL_ENABLED
  3303. SSLClient cli(host);
  3304. #else
  3305. Client cli(host);
  3306. #endif
  3307. cli.set_follow_location(true);
  3308. auto res = cli.Get(path);
  3309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3310. EXPECT_EQ(StatusCode::OK_200, res->status);
  3311. }
  3312. TEST(RedirectTest, Redirect_Online) {
  3313. auto host = "httpbingo.org";
  3314. auto path = std::string{"/redirect/3"};
  3315. #ifdef CPPHTTPLIB_SSL_ENABLED
  3316. SSLClient cli(host);
  3317. #else
  3318. Client cli(host);
  3319. #endif
  3320. cli.set_follow_location(true);
  3321. auto res = cli.Get(path);
  3322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3323. EXPECT_EQ(StatusCode::OK_200, res->status);
  3324. }
  3325. TEST(RelativeRedirectTest, Redirect_Online) {
  3326. auto host = "httpbingo.org";
  3327. auto path = std::string{"/relative-redirect/3"};
  3328. #ifdef CPPHTTPLIB_SSL_ENABLED
  3329. SSLClient cli(host);
  3330. #else
  3331. Client cli(host);
  3332. #endif
  3333. cli.set_follow_location(true);
  3334. auto res = cli.Get(path);
  3335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3336. EXPECT_EQ(StatusCode::OK_200, res->status);
  3337. }
  3338. TEST(TooManyRedirectTest, Redirect_Online) {
  3339. auto host = "httpbingo.org";
  3340. auto path = std::string{"/redirect/21"};
  3341. #ifdef CPPHTTPLIB_SSL_ENABLED
  3342. SSLClient cli(host);
  3343. #else
  3344. Client cli(host);
  3345. #endif
  3346. cli.set_follow_location(true);
  3347. auto res = cli.Get(path);
  3348. ASSERT_TRUE(!res);
  3349. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3350. }
  3351. #ifdef CPPHTTPLIB_SSL_ENABLED
  3352. TEST(YahooRedirectTest, Redirect_Online) {
  3353. Client cli("yahoo.com");
  3354. auto res = cli.Get("/");
  3355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3356. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3357. cli.set_follow_location(true);
  3358. res = cli.Get("/");
  3359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3360. EXPECT_EQ(StatusCode::OK_200, res->status);
  3361. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3362. }
  3363. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3364. #define REDIR_HOST "httpbingo.org"
  3365. #define REDIR_PATH "/redirect-to"
  3366. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3367. SSLClient cli(REDIR_HOST);
  3368. cli.set_follow_location(true);
  3369. auto res =
  3370. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3372. EXPECT_EQ(StatusCode::OK_200, res->status);
  3373. }
  3374. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3375. SSLClient cli(REDIR_HOST);
  3376. cli.set_follow_location(true);
  3377. Params params;
  3378. params.emplace("url", "http://example.com");
  3379. params.emplace("status_code", "302");
  3380. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3382. EXPECT_EQ(StatusCode::OK_200, res->status);
  3383. }
  3384. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3385. SSLClient cli(REDIR_HOST);
  3386. cli.set_follow_location(true);
  3387. Params params;
  3388. params.emplace("url", "http://example.com");
  3389. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. }
  3393. TEST(UrlWithSpace, Redirect_Online) {
  3394. SSLClient cli("edge.forgecdn.net");
  3395. cli.set_follow_location(true);
  3396. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3398. EXPECT_EQ(StatusCode::OK_200, res->status);
  3399. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3400. }
  3401. #endif
  3402. #if !defined(_WIN32) && !defined(_WIN64)
  3403. TEST(ReceiveSignals, Signal) {
  3404. auto setupSignalHandlers = []() {
  3405. struct sigaction act;
  3406. sigemptyset(&act.sa_mask);
  3407. act.sa_flags = SA_SIGINFO;
  3408. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3409. switch (sig) {
  3410. case SIGINT:
  3411. default: break;
  3412. }
  3413. };
  3414. ::sigaction(SIGINT, &act, nullptr);
  3415. };
  3416. Server svr;
  3417. int port = 0;
  3418. auto thread = std::thread([&]() {
  3419. setupSignalHandlers();
  3420. port = svr.bind_to_any_port(HOST);
  3421. svr.listen_after_bind();
  3422. });
  3423. auto se = detail::scope_exit([&] {
  3424. svr.stop();
  3425. thread.join();
  3426. ASSERT_FALSE(svr.is_running());
  3427. });
  3428. svr.wait_until_ready();
  3429. ASSERT_TRUE(svr.is_running());
  3430. pthread_kill(thread.native_handle(), SIGINT);
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3432. ASSERT_TRUE(svr.is_running());
  3433. }
  3434. #endif
  3435. TEST(RedirectToDifferentPort, Redirect) {
  3436. Server svr1;
  3437. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3438. res.set_content("Hello World!", "text/plain");
  3439. });
  3440. int svr1_port = 0;
  3441. auto thread1 = std::thread([&]() {
  3442. svr1_port = svr1.bind_to_any_port(HOST);
  3443. svr1.listen_after_bind();
  3444. });
  3445. Server svr2;
  3446. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3447. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3448. });
  3449. int svr2_port = 0;
  3450. auto thread2 = std::thread([&]() {
  3451. svr2_port = svr2.bind_to_any_port(HOST);
  3452. svr2.listen_after_bind();
  3453. });
  3454. auto se = detail::scope_exit([&] {
  3455. svr2.stop();
  3456. thread2.join();
  3457. svr1.stop();
  3458. thread1.join();
  3459. ASSERT_FALSE(svr2.is_running());
  3460. ASSERT_FALSE(svr1.is_running());
  3461. });
  3462. svr1.wait_until_ready();
  3463. svr2.wait_until_ready();
  3464. Client cli("localhost", svr2_port);
  3465. cli.set_follow_location(true);
  3466. auto res = cli.Get("/2");
  3467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3468. EXPECT_EQ(StatusCode::OK_200, res->status);
  3469. EXPECT_EQ("Hello World!", res->body);
  3470. }
  3471. // GET /redir on one server redirects to /target on another port, so the
  3472. // client follows it with a new client.
  3473. static Result
  3474. GetThroughRedirectToDifferentPort(Server::Handler target,
  3475. const std::function<void(Client &)> &setup,
  3476. const Headers &headers = Headers()) {
  3477. Server target_svr;
  3478. target_svr.Get("/target", target);
  3479. int target_port = 0;
  3480. auto target_thread = std::thread([&]() {
  3481. target_port = target_svr.bind_to_any_port(HOST);
  3482. target_svr.listen_after_bind();
  3483. });
  3484. Server origin_svr;
  3485. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3486. res.set_redirect(
  3487. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3488. });
  3489. int origin_port = 0;
  3490. auto origin_thread = std::thread([&]() {
  3491. origin_port = origin_svr.bind_to_any_port(HOST);
  3492. origin_svr.listen_after_bind();
  3493. });
  3494. auto se = detail::scope_exit([&] {
  3495. origin_svr.stop();
  3496. origin_thread.join();
  3497. target_svr.stop();
  3498. target_thread.join();
  3499. });
  3500. target_svr.wait_until_ready();
  3501. origin_svr.wait_until_ready();
  3502. Client cli("localhost", origin_port);
  3503. cli.set_follow_location(true);
  3504. setup(cli);
  3505. return cli.Get("/redir", headers);
  3506. }
  3507. static void
  3508. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3509. std::string captured_authorization;
  3510. auto result = GetThroughRedirectToDifferentPort(
  3511. [&](const Request &req, Response &res) {
  3512. captured_authorization = req.get_header_value("Authorization");
  3513. res.set_content("OK", "text/plain");
  3514. },
  3515. set_auth);
  3516. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3517. EXPECT_EQ(StatusCode::OK_200, result->status);
  3518. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3519. EXPECT_TRUE(captured_authorization.empty());
  3520. }
  3521. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3522. TestDoNotForwardCredentialsOnRedirect(
  3523. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3524. }
  3525. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3526. TestDoNotForwardCredentialsOnRedirect(
  3527. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3528. }
  3529. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3530. std::string captured_cookie;
  3531. auto result = GetThroughRedirectToDifferentPort(
  3532. [&](const Request &req, Response &res) {
  3533. captured_cookie = req.get_header_value("Cookie");
  3534. res.set_content("OK", "text/plain");
  3535. },
  3536. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3537. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3538. EXPECT_EQ(StatusCode::OK_200, result->status);
  3539. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3540. EXPECT_TRUE(captured_cookie.empty());
  3541. }
  3542. TEST(RedirectToSamePort, ForwardCookie) {
  3543. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3544. // header so that ordinary session flows keep working.
  3545. Server svr;
  3546. std::string captured_cookie;
  3547. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3548. res.set_redirect("/target", 302);
  3549. });
  3550. svr.Get("/target", [&](const Request &req, Response &res) {
  3551. captured_cookie = req.get_header_value("Cookie");
  3552. res.set_content("OK", "text/plain");
  3553. });
  3554. auto port = svr.bind_to_any_port(HOST);
  3555. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3556. auto se = detail::scope_exit([&] {
  3557. svr.stop();
  3558. thread.join();
  3559. ASSERT_FALSE(svr.is_running());
  3560. });
  3561. svr.wait_until_ready();
  3562. Client cli(HOST, port);
  3563. cli.set_follow_location(true);
  3564. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3565. auto res = cli.Get("/redir", headers);
  3566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3567. EXPECT_EQ(StatusCode::OK_200, res->status);
  3568. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3569. }
  3570. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3571. std::string authorization;
  3572. std::string trace_id;
  3573. auto result = GetThroughRedirectToDifferentPort(
  3574. [&](const Request &req, Response &res) {
  3575. authorization = req.get_header_value("Authorization");
  3576. trace_id = req.get_header_value("X-Trace-Id");
  3577. res.set_content("OK", "text/plain");
  3578. },
  3579. [](Client &cli) {
  3580. cli.set_default_headers(
  3581. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3582. });
  3583. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3584. EXPECT_EQ(StatusCode::OK_200, result->status);
  3585. // Like a header given with the request, a default one goes along unless it
  3586. // carries credentials (RFC 9110 15.4).
  3587. EXPECT_TRUE(authorization.empty());
  3588. EXPECT_EQ("42", trace_id);
  3589. }
  3590. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3591. auto result = GetThroughRedirectToDifferentPort(
  3592. [](const Request &, Response &res) {
  3593. res.set_content(std::string(2048, 'x'), "text/plain");
  3594. },
  3595. [](Client &cli) { cli.set_payload_max_length(1024); });
  3596. EXPECT_FALSE(result);
  3597. }
  3598. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3599. auto result = GetThroughRedirectToDifferentPort(
  3600. [](const Request &req, Response &res) {
  3601. // Answer after a second, or once the client gives up.
  3602. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3603. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3604. }
  3605. res.set_content("late", "text/plain");
  3606. },
  3607. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3608. ASSERT_FALSE(result);
  3609. EXPECT_EQ(Error::Read, result.error());
  3610. }
  3611. #ifdef CPPHTTPLIB_SSL_ENABLED
  3612. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3613. auto result = GetThroughRedirectToDifferentPort(
  3614. [](const Request &, Response &res) {
  3615. res.status = StatusCode::Unauthorized_401;
  3616. res.set_header("WWW-Authenticate",
  3617. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3618. },
  3619. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3620. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3621. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3622. }
  3623. #endif
  3624. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3625. Server svr;
  3626. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3627. // Port number that overflows int — should not crash
  3628. res.set_redirect("http://localhost:99999999999999999999/target");
  3629. });
  3630. auto port = svr.bind_to_any_port(HOST);
  3631. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3632. auto se = detail::scope_exit([&] {
  3633. svr.stop();
  3634. thread.join();
  3635. ASSERT_FALSE(svr.is_running());
  3636. });
  3637. svr.wait_until_ready();
  3638. Client cli(HOST, port);
  3639. cli.set_follow_location(true);
  3640. auto res = cli.Get("/redir");
  3641. // Should fail gracefully, not crash (no valid response due to bad port)
  3642. EXPECT_FALSE(res);
  3643. }
  3644. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3645. Server svr;
  3646. auto port = svr.bind_to_any_port(HOST);
  3647. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3648. // The server's own port followed by junk must not be followed
  3649. res.set_redirect("http://" + std::string(HOST) + ":" +
  3650. std::to_string(port) + "junk/target");
  3651. });
  3652. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3653. res.set_content("target", "text/plain");
  3654. });
  3655. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3656. auto se = detail::scope_exit([&] {
  3657. svr.stop();
  3658. thread.join();
  3659. ASSERT_FALSE(svr.is_running());
  3660. });
  3661. svr.wait_until_ready();
  3662. Client cli(HOST, port);
  3663. cli.set_follow_location(true);
  3664. auto res = cli.Get("/redir");
  3665. EXPECT_FALSE(res);
  3666. }
  3667. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3668. Server svr;
  3669. std::atomic<bool> followed{false};
  3670. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3671. res.status = StatusCode::NotModified_304;
  3672. res.set_header("Location", "/target");
  3673. });
  3674. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3675. res.status = StatusCode::UseProxy_305;
  3676. res.set_header("Location", "/target");
  3677. });
  3678. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3679. followed = true;
  3680. res.set_content("target", "text/plain");
  3681. });
  3682. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3683. auto se = detail::scope_exit([&] {
  3684. svr.stop();
  3685. th.join();
  3686. ASSERT_FALSE(svr.is_running());
  3687. });
  3688. svr.wait_until_ready();
  3689. Client cli("localhost", PORT);
  3690. cli.set_follow_location(true);
  3691. auto res = cli.Get("/304");
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3694. res = cli.Get("/305");
  3695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3696. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3697. EXPECT_FALSE(followed);
  3698. }
  3699. TEST(RedirectFromPageWithContent, Redirect) {
  3700. Server svr;
  3701. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3702. res.set_content("___", "text/plain");
  3703. res.set_redirect("/2");
  3704. });
  3705. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3706. res.set_content("Hello World!", "text/plain");
  3707. });
  3708. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3709. auto se = detail::scope_exit([&] {
  3710. svr.stop();
  3711. th.join();
  3712. ASSERT_FALSE(svr.is_running());
  3713. });
  3714. svr.wait_until_ready();
  3715. {
  3716. Client cli("localhost", PORT);
  3717. cli.set_follow_location(true);
  3718. std::string body;
  3719. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3720. body.append(data, data_length);
  3721. return true;
  3722. });
  3723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3724. EXPECT_EQ(StatusCode::OK_200, res->status);
  3725. EXPECT_EQ("Hello World!", body);
  3726. }
  3727. {
  3728. Client cli("localhost", PORT);
  3729. std::string body;
  3730. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3731. body.append(data, data_length);
  3732. return true;
  3733. });
  3734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3735. EXPECT_EQ(StatusCode::Found_302, res->status);
  3736. EXPECT_EQ("___", body);
  3737. }
  3738. }
  3739. // A server can close the connection after a request with "Connection: close"
  3740. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3741. // redirected request must go out on a new connection.
  3742. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3743. #ifndef _WIN32
  3744. signal(SIGPIPE, SIG_IGN);
  3745. #endif
  3746. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3747. default_socket_options(srv);
  3748. sockaddr_in addr{};
  3749. addr.sin_family = AF_INET;
  3750. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3751. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3752. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3753. ASSERT_EQ(0, ::listen(srv, 2));
  3754. auto send_text = [](socket_t sock, const std::string &text) {
  3755. ::send(sock,
  3756. #ifdef _WIN32
  3757. static_cast<const char *>(text.c_str()),
  3758. static_cast<int>(text.size()),
  3759. #else
  3760. text.c_str(), text.size(),
  3761. #endif
  3762. 0);
  3763. };
  3764. auto reused = false;
  3765. auto server_thread = std::thread([&] {
  3766. char buf[4096];
  3767. auto first = ::accept(srv, nullptr, nullptr);
  3768. if (first == INVALID_SOCKET) { return; }
  3769. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3770. ::recv(first, buf, sizeof(buf), 0);
  3771. send_text(
  3772. first,
  3773. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3774. auto next = first;
  3775. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3776. reused = true;
  3777. } else {
  3778. detail::close_socket(first);
  3779. next = ::accept(srv, nullptr, nullptr);
  3780. if (next == INVALID_SOCKET) { return; }
  3781. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3782. ::recv(next, buf, sizeof(buf), 0);
  3783. }
  3784. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3785. "Connection: close\r\n\r\nok");
  3786. detail::close_socket(next);
  3787. });
  3788. Client cli("127.0.0.1", PORT + 2);
  3789. cli.set_follow_location(true);
  3790. cli.set_read_timeout(5, 0);
  3791. auto res = cli.Get("/1");
  3792. server_thread.join();
  3793. detail::close_socket(srv);
  3794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3795. EXPECT_EQ(StatusCode::OK_200, res->status);
  3796. EXPECT_EQ("ok", res->body);
  3797. EXPECT_FALSE(reused);
  3798. }
  3799. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3800. Server svr;
  3801. auto port_str = std::to_string(PORT);
  3802. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3803. auto expected_host = "[::1]:" + port_str;
  3804. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3805. res.set_content("___", "text/plain");
  3806. // res.set_redirect("/2");
  3807. res.set_redirect(redirect_url);
  3808. });
  3809. svr.Get("/2", [&](const Request &req, Response &res) {
  3810. auto host_header = req.headers.find("Host");
  3811. ASSERT_TRUE(host_header != req.headers.end());
  3812. EXPECT_EQ(expected_host, host_header->second);
  3813. res.set_content("Hello World!", "text/plain");
  3814. });
  3815. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3816. auto se = detail::scope_exit([&] {
  3817. svr.stop();
  3818. th.join();
  3819. ASSERT_FALSE(svr.is_running());
  3820. });
  3821. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3822. // actually starts anything, so the condition !svr.is_running() will
  3823. // always remain true, and the loop never stops.
  3824. // This basically counts how many milliseconds have passed since the
  3825. // call to svr.listen(), and if after 5 seconds nothing started yet
  3826. // aborts the test.
  3827. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3828. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3829. ASSERT_LT(milliseconds, 5000U);
  3830. }
  3831. {
  3832. Client cli("::1", PORT);
  3833. cli.set_follow_location(true);
  3834. std::string body;
  3835. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3836. body.append(data, data_length);
  3837. return true;
  3838. });
  3839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. EXPECT_EQ("Hello World!", body);
  3842. }
  3843. {
  3844. Client cli("::1", PORT);
  3845. std::string body;
  3846. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3847. body.append(data, data_length);
  3848. return true;
  3849. });
  3850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3851. EXPECT_EQ(StatusCode::Found_302, res->status);
  3852. EXPECT_EQ("___", body);
  3853. }
  3854. }
  3855. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3856. Server svr;
  3857. svr.Get("/foo", [](const Request &req, Response &res) {
  3858. auto a = req.params.find("a");
  3859. if (a != req.params.end()) {
  3860. res.set_content((*a).second, "text/plain");
  3861. res.status = StatusCode::OK_200;
  3862. } else {
  3863. res.status = StatusCode::BadRequest_400;
  3864. }
  3865. });
  3866. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. thread.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. {
  3874. Client cli(HOST, PORT);
  3875. cli.set_path_encode(false);
  3876. auto res = cli.Get("/foo?a=explicitly+encoded");
  3877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3878. EXPECT_EQ(StatusCode::OK_200, res->status);
  3879. // This expects it back with a space, as the `+` won't have been
  3880. // url-encoded, and server-side the params get decoded turning `+`
  3881. // into spaces.
  3882. EXPECT_EQ("explicitly encoded", res->body);
  3883. }
  3884. }
  3885. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3886. // When path encoding is disabled the client must transmit the supplied
  3887. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3888. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3889. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3890. // than a space (0x20). Assert on the raw wire target to catch this.
  3891. Server svr;
  3892. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3893. svr.Get("/foo", [&](const Request &req, Response &res) {
  3894. EXPECT_EQ(expected_target, req.target);
  3895. res.status = StatusCode::OK_200;
  3896. });
  3897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3898. auto se = detail::scope_exit([&] {
  3899. svr.stop();
  3900. thread.join();
  3901. ASSERT_FALSE(svr.is_running());
  3902. });
  3903. svr.wait_until_ready();
  3904. {
  3905. Client cli(HOST, PORT);
  3906. cli.set_path_encode(false);
  3907. auto res = cli.Get(expected_target.c_str());
  3908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3909. EXPECT_EQ(StatusCode::OK_200, res->status);
  3910. }
  3911. }
  3912. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3913. // `open_stream()` used to skip the path encoding that the buffered send
  3914. // path applies, so the same `path` produced different bytes in the request
  3915. // line depending on which API was used. Assert the two agree.
  3916. Server svr;
  3917. std::string target;
  3918. svr.Get(".*", [&](const Request &req, Response &res) {
  3919. target = req.target;
  3920. res.status = StatusCode::OK_200;
  3921. });
  3922. auto port = svr.bind_to_any_port(HOST);
  3923. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3924. auto se = detail::scope_exit([&] {
  3925. svr.stop();
  3926. thread.join();
  3927. ASSERT_FALSE(svr.is_running());
  3928. });
  3929. svr.wait_until_ready();
  3930. struct {
  3931. const char *path;
  3932. const char *expected;
  3933. } cases[] = {
  3934. {"/a b?x=1", "/a%20b?x=1"},
  3935. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3936. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3937. };
  3938. for (const auto &c : cases) {
  3939. Client cli(HOST, port);
  3940. target.clear();
  3941. auto res = cli.Get(c.path);
  3942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3943. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3944. auto buffered_target = target;
  3945. target.clear();
  3946. auto handle = cli.open_stream("GET", c.path);
  3947. EXPECT_TRUE(handle.is_valid())
  3948. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3949. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3950. }
  3951. }
  3952. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3953. // The `set_path_encode(false)` contract — transmit the supplied target
  3954. // verbatim — must hold for the streaming API too.
  3955. Server svr;
  3956. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3957. std::string target;
  3958. svr.Get("/foo", [&](const Request &req, Response &res) {
  3959. target = req.target;
  3960. res.status = StatusCode::OK_200;
  3961. });
  3962. auto port = svr.bind_to_any_port(HOST);
  3963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3964. auto se = detail::scope_exit([&] {
  3965. svr.stop();
  3966. thread.join();
  3967. ASSERT_FALSE(svr.is_running());
  3968. });
  3969. svr.wait_until_ready();
  3970. {
  3971. Client cli(HOST, port);
  3972. cli.set_path_encode(false);
  3973. auto handle = cli.open_stream("GET", expected_target);
  3974. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3975. EXPECT_EQ(expected_target, target);
  3976. }
  3977. }
  3978. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3979. // With path encoding enabled a CR/LF in the target is percent-encoded
  3980. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3981. // write_request_line still backstops `set_path_encode(false)`, which is
  3982. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3983. Server svr;
  3984. // Captured before routing: the decoded path contains a newline, which a
  3985. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3986. std::string target;
  3987. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3988. target = req.target;
  3989. res.status = StatusCode::OK_200;
  3990. return Server::HandlerResponse::Handled;
  3991. });
  3992. auto port = svr.bind_to_any_port(HOST);
  3993. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3994. auto se = detail::scope_exit([&] {
  3995. svr.stop();
  3996. thread.join();
  3997. ASSERT_FALSE(svr.is_running());
  3998. });
  3999. svr.wait_until_ready();
  4000. {
  4001. Client cli(HOST, port);
  4002. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4003. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4004. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4005. }
  4006. }
  4007. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4008. // Every control character is percent-encoded, not just CR/LF, so the target
  4009. // passes the request-target check in write_request_line.
  4010. Server svr;
  4011. std::string target;
  4012. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4013. target = req.target;
  4014. res.status = StatusCode::OK_200;
  4015. return Server::HandlerResponse::Handled;
  4016. });
  4017. auto port = svr.bind_to_any_port(HOST);
  4018. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4019. auto se = detail::scope_exit([&] {
  4020. svr.stop();
  4021. thread.join();
  4022. ASSERT_FALSE(svr.is_running());
  4023. });
  4024. svr.wait_until_ready();
  4025. {
  4026. Client cli(HOST, port);
  4027. auto res = cli.Get("/a\tb\x1b\x7f");
  4028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4029. EXPECT_EQ("/a%09b%1B%7F", target);
  4030. }
  4031. }
  4032. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4033. // Nothing may reach the wire: a raw CR/LF target would split the request
  4034. // line and inject headers.
  4035. Server svr;
  4036. // Pre-routing so that "not called" means nothing reached the server at all,
  4037. // rather than merely failing to match a handler pattern.
  4038. auto handler_called = false;
  4039. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4040. handler_called = true;
  4041. res.status = StatusCode::OK_200;
  4042. return Server::HandlerResponse::Handled;
  4043. });
  4044. auto port = svr.bind_to_any_port(HOST);
  4045. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4046. auto se = detail::scope_exit([&] {
  4047. svr.stop();
  4048. thread.join();
  4049. ASSERT_FALSE(svr.is_running());
  4050. });
  4051. svr.wait_until_ready();
  4052. {
  4053. Client cli(HOST, port);
  4054. cli.set_path_encode(false);
  4055. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4056. EXPECT_FALSE(handle.is_valid());
  4057. EXPECT_EQ(Error::Write, handle.error);
  4058. EXPECT_FALSE(handler_called);
  4059. }
  4060. }
  4061. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4062. // Which of the two branches runs is decided by whether the query component
  4063. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4064. // an empty query and must still fall back to building one from
  4065. // `req.params`, while a non-empty query must win over `req.params`.
  4066. Server svr;
  4067. std::string target;
  4068. svr.Get("/foo", [&](const Request &req, Response &res) {
  4069. target = req.target;
  4070. res.status = StatusCode::OK_200;
  4071. });
  4072. auto port = svr.bind_to_any_port(HOST);
  4073. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4074. auto se = detail::scope_exit([&] {
  4075. svr.stop();
  4076. thread.join();
  4077. ASSERT_FALSE(svr.is_running());
  4078. });
  4079. svr.wait_until_ready();
  4080. {
  4081. // Trailing `?` -> empty query component -> `req.params` is used.
  4082. Client cli(HOST, port);
  4083. Request req;
  4084. req.method = "GET";
  4085. req.path = "/foo?";
  4086. req.params.emplace("a", "1");
  4087. target.clear();
  4088. auto res = cli.send(req);
  4089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4090. EXPECT_EQ("/foo?a=1", target);
  4091. }
  4092. {
  4093. // Non-empty query in `req.path` -> `req.params` is not appended.
  4094. Client cli(HOST, port);
  4095. Request req;
  4096. req.method = "GET";
  4097. req.path = "/foo?b=2";
  4098. req.params.emplace("a", "1");
  4099. target.clear();
  4100. auto res = cli.send(req);
  4101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4102. EXPECT_EQ("/foo?b=2", target);
  4103. }
  4104. }
  4105. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4106. Server svr;
  4107. svr.Get("/", [](const Request &req, Response &) {
  4108. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4109. });
  4110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. {
  4118. Client cli(HOST, PORT);
  4119. cli.set_path_encode(false);
  4120. auto res = cli.Get("/?something=%0A");
  4121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4122. EXPECT_EQ(StatusCode::OK_200, res->status);
  4123. }
  4124. }
  4125. TEST(BindServerTest, BindDualStack) {
  4126. Server svr;
  4127. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4128. res.set_content("Hello World!", "text/plain");
  4129. });
  4130. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4131. auto se = detail::scope_exit([&] {
  4132. svr.stop();
  4133. thread.join();
  4134. ASSERT_FALSE(svr.is_running());
  4135. });
  4136. svr.wait_until_ready();
  4137. {
  4138. Client cli("127.0.0.1", PORT);
  4139. auto res = cli.Get("/1");
  4140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4141. EXPECT_EQ(StatusCode::OK_200, res->status);
  4142. EXPECT_EQ("Hello World!", res->body);
  4143. }
  4144. {
  4145. Client cli("::1", PORT);
  4146. auto res = cli.Get("/1");
  4147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4148. EXPECT_EQ(StatusCode::OK_200, res->status);
  4149. EXPECT_EQ("Hello World!", res->body);
  4150. }
  4151. }
  4152. TEST(BindServerTest, BindAndListenSeparately) {
  4153. Server svr;
  4154. int port = svr.bind_to_any_port("0.0.0.0");
  4155. ASSERT_TRUE(svr.is_valid());
  4156. ASSERT_TRUE(port > 0);
  4157. svr.stop();
  4158. }
  4159. // Reports whether anything is still listening on a loopback port. A plain
  4160. // connect() is used instead of a Client request because a socket left bound by
  4161. // mistake accepts the connection into its backlog and never answers, which
  4162. // would hang the test instead of failing it.
  4163. static bool is_loopback_port_accepting(int port) {
  4164. sockaddr_in addr{};
  4165. addr.sin_family = AF_INET;
  4166. addr.sin_port = htons(static_cast<uint16_t>(port));
  4167. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4168. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4169. EXPECT_NE(sock, INVALID_SOCKET);
  4170. if (sock == INVALID_SOCKET) { return false; }
  4171. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4172. static_cast<socklen_t>(sizeof(addr)));
  4173. detail::close_socket(sock);
  4174. return ret == 0;
  4175. }
  4176. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4177. Server svr;
  4178. auto port = svr.bind_to_any_port("127.0.0.1");
  4179. ASSERT_TRUE(port > 0);
  4180. svr.stop();
  4181. // bind_to_any_port() already called listen(2), so until stop() closed the
  4182. // descriptor the port kept accepting connections into the backlog. ASSERT
  4183. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4184. // below blocks forever in the accept loop.
  4185. ASSERT_FALSE(is_loopback_port_accepting(port));
  4186. // Nothing is left to accept on, so listen_after_bind() must report failure
  4187. // instead of returning success without ever serving.
  4188. EXPECT_FALSE(svr.listen_after_bind());
  4189. // The failed listen marks the server decommissioned, so a waiter returns
  4190. // instead of spinning forever.
  4191. svr.wait_until_ready();
  4192. }
  4193. #ifdef CPPHTTPLIB_SSL_ENABLED
  4194. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4196. CLIENT_CA_CERT_DIR);
  4197. int port = svr.bind_to_any_port("0.0.0.0");
  4198. ASSERT_TRUE(svr.is_valid());
  4199. ASSERT_TRUE(port > 0);
  4200. svr.stop();
  4201. }
  4202. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4203. // or a rejected CustomRoute() registration would not stop the server binding.
  4204. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4206. CLIENT_CA_CERT_DIR);
  4207. ASSERT_TRUE(svr.is_valid());
  4208. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4209. EXPECT_FALSE(svr.is_valid());
  4210. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4211. }
  4212. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4213. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4214. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4215. int port = svr.bind_to_any_port("0.0.0.0");
  4216. ASSERT_TRUE(svr.is_valid());
  4217. ASSERT_TRUE(port > 0);
  4218. svr.stop();
  4219. }
  4220. TEST(BindServerTest, UpdateCertsPem) {
  4221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4222. int port = svr.bind_to_any_port("0.0.0.0");
  4223. ASSERT_TRUE(svr.is_valid());
  4224. ASSERT_TRUE(port > 0);
  4225. // Read PEM files
  4226. std::string cert_pem, key_pem, ca_pem;
  4227. read_file(SERVER_CERT_FILE, cert_pem);
  4228. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4229. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4230. // Update server certificates using PEM API
  4231. ASSERT_TRUE(
  4232. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4233. ASSERT_TRUE(svr.is_valid());
  4234. svr.stop();
  4235. }
  4236. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4237. // Start server with client CA (enables client auth)
  4238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4239. ASSERT_TRUE(svr.is_valid());
  4240. bool handler_called = false;
  4241. svr.Get("/test", [&](const Request &req, Response &res) {
  4242. handler_called = true;
  4243. // Verify client certificate is present
  4244. auto cert = req.peer_cert();
  4245. EXPECT_TRUE(static_cast<bool>(cert));
  4246. res.set_content("ok", "text/plain");
  4247. });
  4248. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4249. auto se = detail::scope_exit([&] {
  4250. svr.stop();
  4251. t.join();
  4252. ASSERT_FALSE(svr.is_running());
  4253. });
  4254. svr.wait_until_ready();
  4255. // Read PEM files
  4256. std::string cert_pem, key_pem, ca_pem;
  4257. read_file(SERVER_CERT_FILE, cert_pem);
  4258. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4259. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4260. // Update server certificates and client CA using PEM API while server running
  4261. ASSERT_TRUE(
  4262. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4263. // Connect with client certificate
  4264. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4265. cli.enable_server_certificate_verification(false);
  4266. cli.set_connection_timeout(30);
  4267. auto res = cli.Get("/test");
  4268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4269. ASSERT_EQ(StatusCode::OK_200, res->status);
  4270. ASSERT_TRUE(handler_called);
  4271. EXPECT_EQ("ok", res->body);
  4272. }
  4273. // Puts a CA that did not sign the client's certificate in the old one's place.
  4274. static bool replace_client_ca(SSLServer &svr) {
  4275. std::string cert_pem, key_pem, ca_pem;
  4276. read_file(SERVER_CERT_FILE, cert_pem);
  4277. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4278. read_file(SERVER_CERT2_FILE, ca_pem);
  4279. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4280. ca_pem.c_str());
  4281. }
  4282. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4284. ASSERT_TRUE(svr.is_valid());
  4285. svr.Get("/test", [](const Request &, Response &res) {
  4286. res.set_content("ok", "text/plain");
  4287. });
  4288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. t.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. auto get = [] {
  4296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4297. cli.enable_server_certificate_verification(false);
  4298. return cli.Get("/test");
  4299. };
  4300. ASSERT_TRUE(get());
  4301. ASSERT_TRUE(replace_client_ca(svr));
  4302. EXPECT_FALSE(get());
  4303. }
  4304. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4305. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4307. ASSERT_TRUE(svr.is_valid());
  4308. tls::set_verify_callback(svr.tls_context(),
  4309. [](const tls::VerifyContext &) -> bool {
  4310. throw std::runtime_error("verify");
  4311. });
  4312. svr.Get("/test", [](const Request &, Response &res) {
  4313. res.set_content("ok", "text/plain");
  4314. });
  4315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4316. auto se = detail::scope_exit([&] {
  4317. svr.stop();
  4318. t.join();
  4319. ASSERT_FALSE(svr.is_running());
  4320. });
  4321. svr.wait_until_ready();
  4322. auto get = [] {
  4323. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4324. cli.enable_server_certificate_verification(false);
  4325. return cli.Get("/test");
  4326. };
  4327. EXPECT_FALSE(get());
  4328. // The handshake is over, so an update does not wait for it.
  4329. std::string cert_pem, key_pem;
  4330. read_file(SERVER_CERT_FILE, cert_pem);
  4331. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4332. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4333. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4334. return v.preverify_ok;
  4335. });
  4336. auto res = get();
  4337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4338. EXPECT_EQ("ok", res->body);
  4339. }
  4340. #endif
  4341. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4342. // Sends each request over a new connection with a client certificate,
  4343. // resuming the session of the one before when there is one.
  4344. class ResumingClient {
  4345. public:
  4346. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4347. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4348. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4349. SSL_FILETYPE_PEM);
  4350. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4351. // callback, not through SSL_get1_session().
  4352. SSL_CTX_set_app_data(ctx_, this);
  4353. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4354. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4355. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4356. auto self = static_cast<ResumingClient *>(
  4357. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4358. SSL_SESSION_free(self->session_);
  4359. self->session_ = session;
  4360. return 1; // Keeps the reference
  4361. });
  4362. }
  4363. ~ResumingClient() {
  4364. SSL_SESSION_free(session_);
  4365. SSL_CTX_free(ctx_);
  4366. }
  4367. // Tells whether the request was answered.
  4368. bool get() {
  4369. auto error = Error::Success;
  4370. auto sock = detail::create_client_socket(
  4371. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4372. /*connection_timeout_sec=*/5, 0,
  4373. /*read_timeout_sec=*/5, 0,
  4374. /*write_timeout_sec=*/5, 0, std::string(), error);
  4375. if (sock == INVALID_SOCKET) { return false; }
  4376. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4377. auto ssl = SSL_new(ctx_);
  4378. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4379. SSL_set_fd(ssl, static_cast<int>(sock));
  4380. if (session_) { SSL_set_session(ssl, session_); }
  4381. if (SSL_connect(ssl) != 1) { return false; }
  4382. reused_ = SSL_session_reused(ssl) == 1;
  4383. // Reading the response also takes in a TLS 1.3 session ticket.
  4384. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4385. "Connection: close\r\n\r\n";
  4386. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4387. std::string res;
  4388. char buf[256];
  4389. int n;
  4390. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4391. res.append(buf, static_cast<size_t>(n));
  4392. }
  4393. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4394. SSL_shutdown(ssl);
  4395. return res.find("200 OK") != std::string::npos;
  4396. }
  4397. // Whether the last connection resumed a session
  4398. bool reused() const { return reused_; }
  4399. private:
  4400. SSL_CTX *ctx_;
  4401. SSL_SESSION *session_ = nullptr;
  4402. bool reused_ = false;
  4403. };
  4404. // A client that resumes its session gets through, but not once the client CA
  4405. // has changed, as a resumed session does not show the certificate again.
  4406. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4408. ASSERT_TRUE(svr.is_valid());
  4409. svr.Get("/test", [](const Request &, Response &res) {
  4410. res.set_content("ok", "text/plain");
  4411. });
  4412. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4413. auto se = detail::scope_exit([&] {
  4414. svr.stop();
  4415. t.join();
  4416. ASSERT_FALSE(svr.is_running());
  4417. });
  4418. svr.wait_until_ready();
  4419. ResumingClient cli;
  4420. ASSERT_TRUE(cli.get());
  4421. ASSERT_TRUE(cli.get());
  4422. EXPECT_TRUE(cli.reused());
  4423. ASSERT_TRUE(replace_client_ca(svr));
  4424. EXPECT_FALSE(cli.get());
  4425. }
  4426. // A resumed session does not show the certificate again, so the server does
  4427. // not resume one with a verify callback to run on it.
  4428. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4430. ASSERT_TRUE(svr.is_valid());
  4431. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4432. return v.preverify_ok;
  4433. });
  4434. svr.Get("/test", [](const Request &, Response &res) {
  4435. res.set_content("ok", "text/plain");
  4436. });
  4437. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4438. auto se = detail::scope_exit([&] {
  4439. svr.stop();
  4440. t.join();
  4441. ASSERT_FALSE(svr.is_running());
  4442. });
  4443. svr.wait_until_ready();
  4444. ResumingClient cli;
  4445. ASSERT_TRUE(cli.get());
  4446. ASSERT_TRUE(cli.get());
  4447. EXPECT_FALSE(cli.reused());
  4448. }
  4449. #endif
  4450. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4451. // wolfSSL shares its session cache between contexts, so a resumed session
  4452. // could carry a client certificate checked against another server's CA, or
  4453. // against a client CA since replaced.
  4454. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4456. ASSERT_TRUE(svr.is_valid());
  4457. // Trusts a CA that did not sign the client's certificate.
  4458. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4459. ASSERT_TRUE(other.is_valid());
  4460. for (auto s : {&svr, &other}) {
  4461. s->Get("/test", [](const Request &, Response &res) {
  4462. res.set_content("ok", "text/plain");
  4463. });
  4464. }
  4465. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4466. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4467. auto se = detail::scope_exit([&] {
  4468. other.stop();
  4469. svr.stop();
  4470. t2.join();
  4471. t.join();
  4472. });
  4473. svr.wait_until_ready();
  4474. other.wait_until_ready();
  4475. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4476. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4477. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4478. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4479. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4480. ASSERT_EQ(WOLFSSL_SUCCESS,
  4481. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4482. WOLFSSL_FILETYPE_PEM));
  4483. WOLFSSL_SESSION *session = nullptr;
  4484. auto session_se = detail::scope_exit([&] {
  4485. if (session) { wolfSSL_SESSION_free(session); }
  4486. });
  4487. // A request over a new connection, resuming `session` when there is one and
  4488. // keeping the connection's own in its place. Tells whether it was answered.
  4489. auto get = [&](int port) {
  4490. auto error = Error::Success;
  4491. auto sock = detail::create_client_socket(
  4492. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4493. /*connection_timeout_sec=*/5, 0,
  4494. /*read_timeout_sec=*/5, 0,
  4495. /*write_timeout_sec=*/5, 0, std::string(), error);
  4496. if (sock == INVALID_SOCKET) { return false; }
  4497. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4498. auto ssl = wolfSSL_new(ctx);
  4499. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4500. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4501. if (session) { wolfSSL_set_session(ssl, session); }
  4502. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4503. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4504. "Connection: close\r\n\r\n";
  4505. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4506. std::string res;
  4507. char buf[256];
  4508. int n;
  4509. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4510. res.append(buf, static_cast<size_t>(n));
  4511. }
  4512. wolfSSL_shutdown(ssl);
  4513. if (session) { wolfSSL_SESSION_free(session); }
  4514. session = wolfSSL_get1_session(ssl);
  4515. return res.find("200 OK") != std::string::npos;
  4516. };
  4517. ASSERT_TRUE(get(PORT));
  4518. EXPECT_FALSE(get(PORT + 1));
  4519. ASSERT_TRUE(get(PORT));
  4520. ASSERT_TRUE(replace_client_ca(svr));
  4521. EXPECT_FALSE(get(PORT));
  4522. }
  4523. #endif
  4524. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4525. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4526. ASSERT_TRUE(svr.is_valid());
  4527. svr.Get("/test", [](const Request &, Response &res) {
  4528. res.set_content("ok", "text/plain");
  4529. });
  4530. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4531. auto se = detail::scope_exit([&] {
  4532. svr.stop();
  4533. t.join();
  4534. ASSERT_FALSE(svr.is_running());
  4535. });
  4536. svr.wait_until_ready();
  4537. // A connection that sends no ClientHello keeps its handshake in progress,
  4538. // once the server has had a moment to start it.
  4539. auto error = Error::Success;
  4540. auto sock = detail::create_client_socket(
  4541. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4542. /*connection_timeout_sec=*/5, 0,
  4543. /*read_timeout_sec=*/5, 0,
  4544. /*write_timeout_sec=*/5, 0, std::string(), error);
  4545. ASSERT_NE(INVALID_SOCKET, sock);
  4546. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4547. std::string cert_pem, key_pem;
  4548. read_file(SERVER_CERT_FILE, cert_pem);
  4549. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4550. auto update = std::async(std::launch::async, [&]() {
  4551. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4552. });
  4553. EXPECT_EQ(std::future_status::timeout,
  4554. update.wait_for(std::chrono::milliseconds(200)));
  4555. detail::close_socket(sock);
  4556. EXPECT_TRUE(update.get());
  4557. SSLClient cli(HOST, PORT);
  4558. cli.enable_server_certificate_verification(false);
  4559. auto res = cli.Get("/test");
  4560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. }
  4563. #endif
  4564. TEST(ErrorHandlerTest, ContentLength) {
  4565. Server svr;
  4566. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4567. res.status = StatusCode::OK_200;
  4568. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4569. "text/html"); // <= Content-Length still 13
  4570. });
  4571. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4572. res.set_content("Hello World!\n", "text/plain");
  4573. res.status = 524;
  4574. });
  4575. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4576. auto se = detail::scope_exit([&] {
  4577. svr.stop();
  4578. thread.join();
  4579. ASSERT_FALSE(svr.is_running());
  4580. });
  4581. svr.wait_until_ready();
  4582. {
  4583. Client cli(HOST, PORT);
  4584. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4586. EXPECT_EQ(StatusCode::OK_200, res->status);
  4587. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4588. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4589. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4590. }
  4591. }
  4592. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4593. TEST(ExceptionTest, WithoutExceptionHandler) {
  4594. Server svr;
  4595. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4596. throw std::runtime_error("exception...");
  4597. });
  4598. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4599. throw std::runtime_error("exception\r\n...");
  4600. });
  4601. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4602. auto se = detail::scope_exit([&] {
  4603. svr.stop();
  4604. listen_thread.join();
  4605. ASSERT_FALSE(svr.is_running());
  4606. });
  4607. svr.wait_until_ready();
  4608. Client cli("localhost", PORT);
  4609. {
  4610. auto res = cli.Get("/exception");
  4611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4612. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4613. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4614. }
  4615. {
  4616. auto res = cli.Get("/unknown");
  4617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4618. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4619. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4620. }
  4621. }
  4622. TEST(ExceptionTest, WithExceptionHandler) {
  4623. Server svr;
  4624. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4625. std::exception_ptr ep) {
  4626. EXPECT_FALSE(ep == nullptr);
  4627. try {
  4628. std::rethrow_exception(ep);
  4629. } catch (std::exception &e) {
  4630. EXPECT_EQ("abc", std::string(e.what()));
  4631. } catch (...) {}
  4632. res.status = StatusCode::InternalServerError_500;
  4633. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4634. "text/html"); // <= Content-Length still 13 at this point
  4635. });
  4636. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4637. res.set_content("Hello World!\n", "text/plain");
  4638. throw std::runtime_error("abc");
  4639. });
  4640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4641. auto se = detail::scope_exit([&] {
  4642. svr.stop();
  4643. thread.join();
  4644. ASSERT_FALSE(svr.is_running());
  4645. });
  4646. svr.wait_until_ready();
  4647. for (size_t i = 0; i < 10; i++) {
  4648. Client cli(HOST, PORT);
  4649. for (size_t j = 0; j < 100; j++) {
  4650. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4653. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4654. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4655. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4656. }
  4657. cli.set_keep_alive(true);
  4658. for (size_t j = 0; j < 100; j++) {
  4659. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4662. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4663. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4664. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4665. }
  4666. }
  4667. }
  4668. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4669. Server svr;
  4670. svr.set_exception_handler(
  4671. [](const Request &, Response &res, std::exception_ptr) {
  4672. res.set_content("oops", "text/plain");
  4673. });
  4674. svr.Get("/throw", [](const Request &, Response &) {
  4675. throw std::runtime_error("throw");
  4676. });
  4677. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4678. res.status = StatusCode::Created_201;
  4679. throw std::runtime_error("created-then-throw");
  4680. });
  4681. auto port = svr.bind_to_any_port(HOST);
  4682. ASSERT_GT(port, 0);
  4683. thread t = thread([&] { svr.listen_after_bind(); });
  4684. auto se = detail::scope_exit([&] {
  4685. svr.stop();
  4686. t.join();
  4687. ASSERT_FALSE(svr.is_running());
  4688. });
  4689. svr.wait_until_ready();
  4690. Client cli(HOST, port);
  4691. for (auto path : {"/throw", "/created-then-throw"}) {
  4692. auto res = cli.Get(path);
  4693. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4694. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4695. }
  4696. }
  4697. TEST(ExceptionTest, AndErrorHandler) {
  4698. Server svr;
  4699. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4700. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4701. });
  4702. svr.set_exception_handler(
  4703. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4704. EXPECT_FALSE(ep == nullptr);
  4705. try {
  4706. std::rethrow_exception(ep);
  4707. } catch (std::exception &e) {
  4708. res.set_content(e.what(), "text/html");
  4709. } catch (...) {}
  4710. res.status = StatusCode::InternalServerError_500;
  4711. });
  4712. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4713. throw std::runtime_error("EXCEPTION");
  4714. });
  4715. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4716. res.set_content("ERROR", "text/html");
  4717. res.status = StatusCode::InternalServerError_500;
  4718. });
  4719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4720. auto se = detail::scope_exit([&] {
  4721. svr.stop();
  4722. thread.join();
  4723. ASSERT_FALSE(svr.is_running());
  4724. });
  4725. svr.wait_until_ready();
  4726. Client cli(HOST, PORT);
  4727. {
  4728. auto res = cli.Get("/exception");
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4731. EXPECT_EQ("EXCEPTION", res->body);
  4732. }
  4733. {
  4734. auto res = cli.Get("/error");
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4737. EXPECT_EQ("ERROR", res->body);
  4738. }
  4739. {
  4740. auto res = cli.Get("/invalid");
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4743. EXPECT_EQ("NOT_FOUND", res->body);
  4744. }
  4745. }
  4746. #endif
  4747. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4748. // An exception from a user callback outside process_request()'s try/catch
  4749. // used to unwind into the task queue - which does not catch - and terminate
  4750. // the process. Each test below runs the server on a single worker thread: a
  4751. // guard that catches the exception but still loses the thread would otherwise
  4752. // be hidden by a spare worker serving the follow-up request. Note that a
  4753. // regression here aborts the whole test binary rather than failing one test.
  4754. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4755. Server svr;
  4756. svr.new_task_queue = [] { return new ThreadPool(1); };
  4757. std::atomic<int> reported{0};
  4758. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4759. if (err == Error::UserCallbackException) { reported++; }
  4760. });
  4761. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4762. res.set_content_provider(
  4763. 1024, "text/plain",
  4764. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4765. sink.write("hello", 5);
  4766. throw std::runtime_error("from the content provider");
  4767. });
  4768. });
  4769. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4770. res.set_content("ok", "text/plain");
  4771. });
  4772. auto port = svr.bind_to_any_port(HOST);
  4773. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4774. auto se = detail::scope_exit([&] {
  4775. svr.stop();
  4776. listen_thread.join();
  4777. ASSERT_FALSE(svr.is_running());
  4778. });
  4779. svr.wait_until_ready();
  4780. {
  4781. Client cli(HOST, port);
  4782. cli.set_read_timeout(5, 0);
  4783. EXPECT_FALSE(cli.Get("/throw"));
  4784. }
  4785. EXPECT_TRUE(svr.is_running());
  4786. EXPECT_EQ(1, reported.load());
  4787. // A request on a fresh connection is still served.
  4788. {
  4789. Client cli(HOST, port);
  4790. auto res = cli.Get("/ok");
  4791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("ok", res->body);
  4794. }
  4795. }
  4796. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4797. Server svr;
  4798. svr.new_task_queue = [] { return new ThreadPool(1); };
  4799. std::atomic<bool> should_throw{true};
  4800. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4801. res.set_content("hi", "text/plain");
  4802. });
  4803. svr.set_post_routing_handler(
  4804. [&](const Request & /*req*/, Response & /*res*/) {
  4805. if (should_throw) {
  4806. throw std::runtime_error("from the post-routing handler");
  4807. }
  4808. });
  4809. auto port = svr.bind_to_any_port(HOST);
  4810. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4811. auto se = detail::scope_exit([&] {
  4812. svr.stop();
  4813. listen_thread.join();
  4814. ASSERT_FALSE(svr.is_running());
  4815. });
  4816. svr.wait_until_ready();
  4817. {
  4818. Client cli(HOST, port);
  4819. cli.set_read_timeout(5, 0);
  4820. EXPECT_FALSE(cli.Get("/hi"));
  4821. }
  4822. EXPECT_TRUE(svr.is_running());
  4823. should_throw = false;
  4824. {
  4825. Client cli(HOST, port);
  4826. auto res = cli.Get("/hi");
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ("hi", res->body);
  4830. }
  4831. }
  4832. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4833. // The guard reports the caught exception through the error logger, which is
  4834. // a user callback too. A logger that throws has to be contained as well, or
  4835. // the process would terminate from inside the catch.
  4836. Server svr;
  4837. svr.new_task_queue = [] { return new ThreadPool(1); };
  4838. std::atomic<int> reported{0};
  4839. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4840. if (err == Error::UserCallbackException) {
  4841. reported++;
  4842. throw std::runtime_error("from the error logger");
  4843. }
  4844. });
  4845. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4846. res.set_content_provider(
  4847. 1024, "text/plain",
  4848. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4849. sink.write("hello", 5);
  4850. throw std::runtime_error("from the content provider");
  4851. });
  4852. });
  4853. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4854. res.set_content("ok", "text/plain");
  4855. });
  4856. auto port = svr.bind_to_any_port(HOST);
  4857. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4858. auto se = detail::scope_exit([&] {
  4859. svr.stop();
  4860. listen_thread.join();
  4861. ASSERT_FALSE(svr.is_running());
  4862. });
  4863. svr.wait_until_ready();
  4864. {
  4865. Client cli(HOST, port);
  4866. cli.set_read_timeout(5, 0);
  4867. EXPECT_FALSE(cli.Get("/throw"));
  4868. }
  4869. EXPECT_TRUE(svr.is_running());
  4870. EXPECT_EQ(1, reported.load());
  4871. {
  4872. Client cli(HOST, port);
  4873. auto res = cli.Get("/ok");
  4874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4875. EXPECT_EQ(StatusCode::OK_200, res->status);
  4876. EXPECT_EQ("ok", res->body);
  4877. }
  4878. }
  4879. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4880. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4881. // so the exception unwinds through the ws::WebSocket object on its way to
  4882. // the guard. None of the HTTP cases above cross that.
  4883. Server svr;
  4884. svr.new_task_queue = [] { return new ThreadPool(1); };
  4885. std::atomic<int> reported{0};
  4886. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4887. if (err == Error::UserCallbackException) { reported++; }
  4888. });
  4889. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4890. throw std::runtime_error("from the WebSocket handler");
  4891. });
  4892. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4893. res.set_content("ok", "text/plain");
  4894. });
  4895. auto port = svr.bind_to_any_port(HOST);
  4896. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4897. auto se = detail::scope_exit([&] {
  4898. svr.stop();
  4899. listen_thread.join();
  4900. ASSERT_FALSE(svr.is_running());
  4901. });
  4902. svr.wait_until_ready();
  4903. {
  4904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4905. "/ws");
  4906. auto res = client.connect();
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. // The server dropped the connection instead of dying.
  4909. std::string msg;
  4910. EXPECT_FALSE(client.read(msg));
  4911. client.close();
  4912. }
  4913. EXPECT_TRUE(svr.is_running());
  4914. EXPECT_EQ(1, reported.load());
  4915. {
  4916. Client cli(HOST, port);
  4917. auto res = cli.Get("/ok");
  4918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4919. EXPECT_EQ(StatusCode::OK_200, res->status);
  4920. EXPECT_EQ("ok", res->body);
  4921. }
  4922. }
  4923. #ifdef CPPHTTPLIB_SSL_ENABLED
  4924. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4925. // SSLServer::process_and_close_socket() is a separate overload with its own
  4926. // guard, so it is exercised on its own.
  4927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4928. ASSERT_TRUE(svr.is_valid());
  4929. svr.new_task_queue = [] { return new ThreadPool(1); };
  4930. std::atomic<int> reported{0};
  4931. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4932. if (err == Error::UserCallbackException) { reported++; }
  4933. });
  4934. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4935. res.set_content_provider(
  4936. 1024, "text/plain",
  4937. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4938. sink.write("hello", 5);
  4939. throw std::runtime_error("from the content provider");
  4940. });
  4941. });
  4942. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4943. res.set_content("ok", "text/plain");
  4944. });
  4945. auto port = svr.bind_to_any_port(HOST);
  4946. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4947. auto se = detail::scope_exit([&] {
  4948. svr.stop();
  4949. listen_thread.join();
  4950. ASSERT_FALSE(svr.is_running());
  4951. });
  4952. svr.wait_until_ready();
  4953. {
  4954. SSLClient cli(HOST, port);
  4955. cli.enable_server_certificate_verification(false);
  4956. cli.set_read_timeout(5, 0);
  4957. EXPECT_FALSE(cli.Get("/throw"));
  4958. }
  4959. EXPECT_TRUE(svr.is_running());
  4960. EXPECT_EQ(1, reported.load());
  4961. {
  4962. SSLClient cli(HOST, port);
  4963. cli.enable_server_certificate_verification(false);
  4964. auto res = cli.Get("/ok");
  4965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4966. EXPECT_EQ(StatusCode::OK_200, res->status);
  4967. EXPECT_EQ("ok", res->body);
  4968. }
  4969. }
  4970. #endif
  4971. #endif
  4972. TEST(NoContentTest, ContentLength) {
  4973. Server svr;
  4974. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4975. res.status = StatusCode::NoContent_204;
  4976. });
  4977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4978. auto se = detail::scope_exit([&] {
  4979. svr.stop();
  4980. thread.join();
  4981. ASSERT_FALSE(svr.is_running());
  4982. });
  4983. svr.wait_until_ready();
  4984. {
  4985. Client cli(HOST, PORT);
  4986. auto res = cli.Get("/hi");
  4987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4988. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4989. // RFC 9110 8.6: none in a 204 response
  4990. EXPECT_FALSE(res->has_header("Content-Length"));
  4991. }
  4992. }
  4993. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4994. Server svr;
  4995. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4996. res.set_header("Content-Length", "5");
  4997. res.set_content("hello world", "text/plain");
  4998. });
  4999. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5000. // A body that reads as the last chunk, were it taken as chunked
  5001. res.set_header("Transfer-Encoding", "chunked");
  5002. res.set_content("0\r\n\r\n", "text/plain");
  5003. });
  5004. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5005. res.set_header("Content-Length", "2");
  5006. res.set_content_provider(5, "text/plain",
  5007. [](size_t offset, size_t length, DataSink &sink) {
  5008. sink.write(&"hello"[offset], length);
  5009. return true;
  5010. });
  5011. });
  5012. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5013. res.set_header("Content-Length", "1234");
  5014. });
  5015. thread t = thread([&] { svr.listen(HOST, PORT); });
  5016. auto se = detail::scope_exit([&] {
  5017. svr.stop();
  5018. t.join();
  5019. ASSERT_FALSE(svr.is_running());
  5020. });
  5021. svr.wait_until_ready();
  5022. Client cli(HOST, PORT);
  5023. cli.set_read_timeout(1, 0);
  5024. auto expect_body = [&](const Result &res, const std::string &body) {
  5025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5026. EXPECT_EQ(body, res->body);
  5027. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5028. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5029. };
  5030. Headers identity{{"Accept-Encoding", ""}};
  5031. expect_body(cli.Get("/body", identity), "hello world");
  5032. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5033. expect_body(cli.Get("/body",
  5034. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5035. "he");
  5036. expect_body(cli.Get("/provider", identity), "hello");
  5037. expect_body(cli.Get("/empty", identity), "");
  5038. // A HEAD response may give the length of the body a GET would get.
  5039. auto res = cli.Head("/empty");
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5042. }
  5043. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5044. Server svr;
  5045. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5046. res.set_content("short", "text/plain");
  5047. });
  5048. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5049. res.body += " with a footer";
  5050. res.set_header("Transfer-Encoding", "chunked");
  5051. });
  5052. thread t = thread([&] { svr.listen(HOST, PORT); });
  5053. auto se = detail::scope_exit([&] {
  5054. svr.stop();
  5055. t.join();
  5056. ASSERT_FALSE(svr.is_running());
  5057. });
  5058. svr.wait_until_ready();
  5059. Client cli(HOST, PORT);
  5060. cli.set_read_timeout(1, 0);
  5061. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5063. EXPECT_EQ("short with a footer", res->body);
  5064. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5065. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5066. }
  5067. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5068. Server svr;
  5069. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5070. res.set_header("Content-Length", "3");
  5071. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5072. sink.write("abc", 3);
  5073. sink.done();
  5074. return true;
  5075. });
  5076. });
  5077. thread t = thread([&] { svr.listen(HOST, PORT); });
  5078. auto se = detail::scope_exit([&] {
  5079. svr.stop();
  5080. t.join();
  5081. ASSERT_FALSE(svr.is_running());
  5082. });
  5083. svr.wait_until_ready();
  5084. Client cli(HOST, PORT);
  5085. cli.set_keep_alive(true);
  5086. auto res = cli.Get("/");
  5087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5088. EXPECT_EQ("abc", res->body);
  5089. EXPECT_FALSE(res->has_header("Content-Length"));
  5090. EXPECT_EQ("close", res->get_header_value("Connection"));
  5091. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5092. // No body to delimit
  5093. auto head = cli.Head("/");
  5094. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5095. EXPECT_FALSE(head->has_header("Connection"));
  5096. }
  5097. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5098. #ifdef CPPHTTPLIB_SSL_ENABLED
  5099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5100. ASSERT_TRUE(svr.is_valid());
  5101. #else
  5102. Server svr;
  5103. #endif
  5104. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5105. if (req.path == "/routing_handler") {
  5106. res.set_header("PRE_ROUTING", "on");
  5107. res.set_content("Routing Handler", "text/plain");
  5108. return httplib::Server::HandlerResponse::Handled;
  5109. }
  5110. return httplib::Server::HandlerResponse::Unhandled;
  5111. });
  5112. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5113. res.set_content("Error", "text/html");
  5114. });
  5115. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5116. if (req.path == "/routing_handler") {
  5117. res.set_header("POST_ROUTING", "on");
  5118. }
  5119. });
  5120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5121. res.set_content("Hello World!\n", "text/plain");
  5122. });
  5123. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5124. auto se = detail::scope_exit([&] {
  5125. svr.stop();
  5126. thread.join();
  5127. ASSERT_FALSE(svr.is_running());
  5128. });
  5129. svr.wait_until_ready();
  5130. {
  5131. #ifdef CPPHTTPLIB_SSL_ENABLED
  5132. SSLClient cli(HOST, PORT);
  5133. cli.enable_server_certificate_verification(false);
  5134. #else
  5135. Client cli(HOST, PORT);
  5136. #endif
  5137. auto res = cli.Get("/routing_handler");
  5138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5139. EXPECT_EQ(StatusCode::OK_200, res->status);
  5140. EXPECT_EQ("Routing Handler", res->body);
  5141. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5142. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5143. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5144. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5145. }
  5146. {
  5147. #ifdef CPPHTTPLIB_SSL_ENABLED
  5148. SSLClient cli(HOST, PORT);
  5149. cli.enable_server_certificate_verification(false);
  5150. #else
  5151. Client cli(HOST, PORT);
  5152. #endif
  5153. auto res = cli.Get("/hi");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("Hello World!\n", res->body);
  5157. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5158. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5159. }
  5160. {
  5161. #ifdef CPPHTTPLIB_SSL_ENABLED
  5162. SSLClient cli(HOST, PORT);
  5163. cli.enable_server_certificate_verification(false);
  5164. #else
  5165. Client cli(HOST, PORT);
  5166. #endif
  5167. auto res = cli.Get("/aaa");
  5168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5169. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5170. EXPECT_EQ("Error", res->body);
  5171. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5172. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5173. }
  5174. }
  5175. TEST(RequestHandlerTest, PreRequestHandler) {
  5176. auto route_path = "/user/:user";
  5177. Server svr;
  5178. svr.Get("/hi", [](const Request &, Response &res) {
  5179. res.set_content("hi", "text/plain");
  5180. });
  5181. svr.Get(route_path, [](const Request &req, Response &res) {
  5182. res.set_content(req.path_params.at("user"), "text/plain");
  5183. });
  5184. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5185. if (req.matched_route == route_path) {
  5186. auto user = req.path_params.at("user");
  5187. if (user != "john") {
  5188. res.status = StatusCode::Forbidden_403;
  5189. res.set_content("error", "text/html");
  5190. return Server::HandlerResponse::Handled;
  5191. }
  5192. }
  5193. return Server::HandlerResponse::Unhandled;
  5194. });
  5195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5196. auto se = detail::scope_exit([&] {
  5197. svr.stop();
  5198. thread.join();
  5199. ASSERT_FALSE(svr.is_running());
  5200. });
  5201. svr.wait_until_ready();
  5202. Client cli(HOST, PORT);
  5203. {
  5204. auto res = cli.Get("/hi");
  5205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5206. EXPECT_EQ(StatusCode::OK_200, res->status);
  5207. EXPECT_EQ("hi", res->body);
  5208. }
  5209. {
  5210. auto res = cli.Get("/user/john");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::OK_200, res->status);
  5213. EXPECT_EQ("john", res->body);
  5214. }
  5215. {
  5216. auto res = cli.Get("/user/invalid-user");
  5217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5218. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5219. EXPECT_EQ("error", res->body);
  5220. }
  5221. }
  5222. // The pre-request handler must run before the request body is read, so a
  5223. // rejected request never forces the server to buffer a (potentially large)
  5224. // body. Here the posted body is larger than the payload limit: if the body
  5225. // were read first the server would answer 413, but because the pre-request
  5226. // handler runs first it answers 403 and the body is never read.
  5227. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5228. Server svr;
  5229. svr.set_payload_max_length(8);
  5230. auto handler_ran = false;
  5231. svr.Post("/reject", [&](const Request &req, Response &res) {
  5232. handler_ran = true;
  5233. res.set_content(req.body, "text/plain");
  5234. });
  5235. svr.Post("/accept", [](const Request &req, Response &res) {
  5236. res.set_content(req.body, "text/plain");
  5237. });
  5238. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5239. if (req.matched_route == "/reject") {
  5240. res.status = StatusCode::Forbidden_403;
  5241. res.set_content("denied", "text/plain");
  5242. return Server::HandlerResponse::Handled;
  5243. }
  5244. return Server::HandlerResponse::Unhandled;
  5245. });
  5246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5247. auto se = detail::scope_exit([&] {
  5248. svr.stop();
  5249. thread.join();
  5250. ASSERT_FALSE(svr.is_running());
  5251. });
  5252. svr.wait_until_ready();
  5253. Client cli(HOST, PORT);
  5254. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5255. // rejects with 403 before the body is read, so 413 is never reached.
  5256. {
  5257. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5259. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5260. EXPECT_EQ("denied", res->body);
  5261. EXPECT_FALSE(handler_ran);
  5262. }
  5263. // An approved route still reads the body and enforces the payload limit.
  5264. {
  5265. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5267. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5268. }
  5269. }
  5270. TEST(UserDataTest, BasicOperations) {
  5271. httplib::UserData ud;
  5272. // Initially empty
  5273. EXPECT_FALSE(ud.has("key"));
  5274. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5275. // set and get
  5276. ud.set("key", 42);
  5277. EXPECT_TRUE(ud.has("key"));
  5278. auto *p = ud.get<int>("key");
  5279. ASSERT_NE(nullptr, p);
  5280. EXPECT_EQ(42, *p);
  5281. // Type mismatch → nullptr
  5282. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5283. // Overwrite with different type
  5284. ud.set("key", std::string("hello"));
  5285. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5286. auto *s = ud.get<std::string>("key");
  5287. ASSERT_NE(nullptr, s);
  5288. EXPECT_EQ("hello", *s);
  5289. // erase
  5290. ud.erase("key");
  5291. EXPECT_FALSE(ud.has("key"));
  5292. // clear
  5293. ud.set("a", 1);
  5294. ud.set("b", 2);
  5295. ud.clear();
  5296. EXPECT_FALSE(ud.has("a"));
  5297. EXPECT_FALSE(ud.has("b"));
  5298. }
  5299. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5300. struct AuthCtx {
  5301. std::string user_id;
  5302. };
  5303. Server svr;
  5304. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5305. res.user_data.set("auth", AuthCtx{"alice"});
  5306. return Server::HandlerResponse::Unhandled;
  5307. });
  5308. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5309. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5310. ASSERT_NE(nullptr, ctx);
  5311. res.set_content("Hello " + ctx->user_id, "text/plain");
  5312. });
  5313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5314. auto se = detail::scope_exit([&] {
  5315. svr.stop();
  5316. thread.join();
  5317. ASSERT_FALSE(svr.is_running());
  5318. });
  5319. svr.wait_until_ready();
  5320. Client cli(HOST, PORT);
  5321. auto res = cli.Get("/me");
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. EXPECT_EQ(StatusCode::OK_200, res->status);
  5324. EXPECT_EQ("Hello alice", res->body);
  5325. }
  5326. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5327. struct RoleCtx {
  5328. std::string role;
  5329. };
  5330. Server svr;
  5331. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5332. res.user_data.set("role", RoleCtx{"admin"});
  5333. return Server::HandlerResponse::Unhandled;
  5334. });
  5335. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5336. auto *ctx = res.user_data.get<RoleCtx>("role");
  5337. ASSERT_NE(nullptr, ctx);
  5338. res.set_content(ctx->role, "text/plain");
  5339. });
  5340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5341. auto se = detail::scope_exit([&] {
  5342. svr.stop();
  5343. thread.join();
  5344. ASSERT_FALSE(svr.is_running());
  5345. });
  5346. svr.wait_until_ready();
  5347. Client cli(HOST, PORT);
  5348. auto res = cli.Get("/role");
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_EQ("admin", res->body);
  5352. }
  5353. TEST(InvalidFormatTest, StatusCode) {
  5354. Server svr;
  5355. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5356. res.set_content("Hello World!\n", "text/plain");
  5357. res.status = 9999; // Status should be a three-digit code...
  5358. });
  5359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5360. auto se = detail::scope_exit([&] {
  5361. svr.stop();
  5362. thread.join();
  5363. ASSERT_FALSE(svr.is_running());
  5364. });
  5365. svr.wait_until_ready();
  5366. {
  5367. Client cli(HOST, PORT);
  5368. auto res = cli.Get("/hi");
  5369. ASSERT_FALSE(res);
  5370. }
  5371. }
  5372. TEST(URLFragmentTest, WithFragment) {
  5373. Server svr;
  5374. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5375. EXPECT_TRUE(req.target == "/hi");
  5376. });
  5377. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5378. auto se = detail::scope_exit([&] {
  5379. svr.stop();
  5380. thread.join();
  5381. ASSERT_FALSE(svr.is_running());
  5382. });
  5383. svr.wait_until_ready();
  5384. {
  5385. Client cli(HOST, PORT);
  5386. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5387. EXPECT_TRUE(res);
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. res = cli.Get("/hi%23key1=val1=key2=val2");
  5390. EXPECT_TRUE(res);
  5391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5392. }
  5393. }
  5394. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5395. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5396. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5397. Server svr;
  5398. std::vector<std::string> targets;
  5399. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5400. targets.push_back(req.target);
  5401. });
  5402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5403. auto se = detail::scope_exit([&] {
  5404. svr.stop();
  5405. thread.join();
  5406. ASSERT_FALSE(svr.is_running());
  5407. });
  5408. svr.wait_until_ready();
  5409. Client cli(HOST, PORT);
  5410. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5411. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5412. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5413. // A '?' after the '#' belongs to the fragment, not to the query.
  5414. Request req;
  5415. req.method = "GET";
  5416. req.path = "/hi#f?x=1";
  5417. req.params.emplace("a", "1");
  5418. Response res;
  5419. auto error = Error::Success;
  5420. EXPECT_TRUE(cli.send(req, res, error));
  5421. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5422. "/hi?a=1"}),
  5423. targets);
  5424. }
  5425. TEST(HeaderWriter, SetHeaderWriter) {
  5426. Server svr;
  5427. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5428. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5429. return detail::write_headers(strm, hdrs);
  5430. });
  5431. svr.Get("/hi", [](const Request &req, Response &res) {
  5432. auto it = req.headers.find("CustomClientHeader");
  5433. EXPECT_TRUE(it != req.headers.end());
  5434. EXPECT_EQ(it->second, "CustomClientValue");
  5435. res.set_content("Hello World!\n", "text/plain");
  5436. });
  5437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5438. auto se = detail::scope_exit([&] {
  5439. svr.stop();
  5440. thread.join();
  5441. ASSERT_FALSE(svr.is_running());
  5442. });
  5443. svr.wait_until_ready();
  5444. {
  5445. Client cli(HOST, PORT);
  5446. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5447. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5448. return detail::write_headers(strm, hdrs);
  5449. });
  5450. auto res = cli.Get("/hi");
  5451. EXPECT_TRUE(res);
  5452. EXPECT_EQ(StatusCode::OK_200, res->status);
  5453. auto it = res->headers.find("CustomServerHeader");
  5454. EXPECT_TRUE(it != res->headers.end());
  5455. EXPECT_EQ(it->second, "CustomServerValue");
  5456. }
  5457. }
  5458. class ServerTest : public ::testing::Test {
  5459. protected:
  5460. ServerTest()
  5461. : cli_(HOST, PORT)
  5462. #ifdef CPPHTTPLIB_SSL_ENABLED
  5463. ,
  5464. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5465. #endif
  5466. {
  5467. #ifdef CPPHTTPLIB_SSL_ENABLED
  5468. cli_.enable_server_certificate_verification(false);
  5469. #endif
  5470. // Allow LARGE_DATA (100MB) responses
  5471. cli_.set_payload_max_length(200 * 1024 * 1024);
  5472. }
  5473. virtual void SetUp() {
  5474. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5475. svr_.set_payload_max_length(200 * 1024 * 1024);
  5476. svr_.set_mount_point("/", "./www");
  5477. svr_.set_mount_point("/mount", "./www2");
  5478. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5479. svr_.Get("/hi",
  5480. [&](const Request & /*req*/, Response &res) {
  5481. res.set_content("Hello World!", "text/plain");
  5482. })
  5483. .Get("/file_content",
  5484. [&](const Request & /*req*/, Response &res) {
  5485. res.set_file_content("./www/dir/test.html");
  5486. })
  5487. .Get("/file_content_with_content_type",
  5488. [&](const Request & /*req*/, Response &res) {
  5489. res.set_file_content("./www/file", "text/plain");
  5490. })
  5491. .Get("/invalid_file_content",
  5492. [&](const Request & /*req*/, Response &res) {
  5493. res.set_file_content("./www/dir/invalid_file_path");
  5494. })
  5495. .Get("/http_response_splitting",
  5496. [&](const Request & /*req*/, Response &res) {
  5497. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5498. EXPECT_EQ(0U, res.headers.size());
  5499. EXPECT_FALSE(res.has_header("a"));
  5500. res.set_header("a", "1\nSet-Cookie: a=1");
  5501. EXPECT_EQ(0U, res.headers.size());
  5502. EXPECT_FALSE(res.has_header("a"));
  5503. res.set_header("a", "1\rSet-Cookie: a=1");
  5504. EXPECT_EQ(0U, res.headers.size());
  5505. EXPECT_FALSE(res.has_header("a"));
  5506. res.set_header("a\r\nb", "0");
  5507. EXPECT_EQ(0U, res.headers.size());
  5508. EXPECT_FALSE(res.has_header("a"));
  5509. res.set_header("a\rb", "0");
  5510. EXPECT_EQ(0U, res.headers.size());
  5511. EXPECT_FALSE(res.has_header("a"));
  5512. res.set_header("a\nb", "0");
  5513. EXPECT_EQ(0U, res.headers.size());
  5514. EXPECT_FALSE(res.has_header("a"));
  5515. res.set_redirect("1\r\nSet-Cookie: a=1");
  5516. EXPECT_EQ(0U, res.headers.size());
  5517. EXPECT_FALSE(res.has_header("Location"));
  5518. })
  5519. .Get("/slow",
  5520. [&](const Request & /*req*/, Response &res) {
  5521. std::this_thread::sleep_for(std::chrono::seconds(4));
  5522. res.set_content("slow", "text/plain");
  5523. })
  5524. #if 0
  5525. .Post("/slowpost",
  5526. [&](const Request & /*req*/, Response &res) {
  5527. std::this_thread::sleep_for(std::chrono::seconds(2));
  5528. res.set_content("slow", "text/plain");
  5529. })
  5530. #endif
  5531. .Get("/remote_addr",
  5532. [&](const Request &req, Response &res) {
  5533. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5534. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5535. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5536. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5537. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5538. #endif
  5539. res.set_content(req.remote_addr, "text/plain");
  5540. })
  5541. .Get("/local_addr",
  5542. [&](const Request &req, Response &res) {
  5543. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5544. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5545. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5546. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5547. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5548. #endif
  5549. auto local_addr = req.local_addr;
  5550. auto local_port = std::to_string(req.local_port);
  5551. res.set_content(local_addr.append(":").append(local_port),
  5552. "text/plain");
  5553. })
  5554. .Get("/endwith%",
  5555. [&](const Request & /*req*/, Response &res) {
  5556. res.set_content("Hello World!", "text/plain");
  5557. })
  5558. .Get("/a\\+\\+b",
  5559. [&](const Request &req, Response &res) {
  5560. ASSERT_TRUE(req.has_param("a +b"));
  5561. auto val = req.get_param_value("a +b");
  5562. res.set_content(val, "text/plain");
  5563. })
  5564. .Get("/", [&](const Request & /*req*/,
  5565. Response &res) { res.set_redirect("/hi"); })
  5566. .Post("/1",
  5567. [](const Request & /*req*/, Response &res) {
  5568. res.set_redirect("/2", StatusCode::SeeOther_303);
  5569. })
  5570. .Get("/2",
  5571. [](const Request & /*req*/, Response &res) {
  5572. res.set_content("redirected.", "text/plain");
  5573. res.status = StatusCode::OK_200;
  5574. })
  5575. .Post("/person",
  5576. [&](const Request &req, Response &res) {
  5577. if (req.has_param("name") && req.has_param("note")) {
  5578. persons_[req.get_param_value("name")] =
  5579. req.get_param_value("note");
  5580. } else {
  5581. res.status = StatusCode::BadRequest_400;
  5582. }
  5583. })
  5584. .Put("/person",
  5585. [&](const Request &req, Response &res) {
  5586. if (req.has_param("name") && req.has_param("note")) {
  5587. persons_[req.get_param_value("name")] =
  5588. req.get_param_value("note");
  5589. } else {
  5590. res.status = StatusCode::BadRequest_400;
  5591. }
  5592. })
  5593. .Get("/person/(.*)",
  5594. [&](const Request &req, Response &res) {
  5595. string name = req.matches[1];
  5596. if (persons_.find(name) != persons_.end()) {
  5597. auto note = persons_[name];
  5598. res.set_content(note, "text/plain");
  5599. } else {
  5600. res.status = StatusCode::NotFound_404;
  5601. }
  5602. })
  5603. .Delete("/person",
  5604. [&](const Request &req, Response &res) {
  5605. if (req.has_param("name")) {
  5606. string name = req.get_param_value("name");
  5607. if (persons_.find(name) != persons_.end()) {
  5608. persons_.erase(name);
  5609. res.set_content("DELETED", "text/plain");
  5610. } else {
  5611. res.status = StatusCode::NotFound_404;
  5612. }
  5613. } else {
  5614. res.status = StatusCode::BadRequest_400;
  5615. }
  5616. })
  5617. .Post("/x-www-form-urlencoded-json",
  5618. [&](const Request &req, Response &res) {
  5619. auto json = req.get_param_value("json");
  5620. ASSERT_EQ(JSON_DATA, json);
  5621. res.set_content(json, "appliation/json");
  5622. res.status = StatusCode::OK_200;
  5623. })
  5624. .Get("/streamed-chunked",
  5625. [&](const Request & /*req*/, Response &res) {
  5626. res.set_chunked_content_provider(
  5627. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5628. sink.os << "123";
  5629. sink.os << "456";
  5630. sink.os << "789";
  5631. sink.done();
  5632. return true;
  5633. });
  5634. })
  5635. .Get("/streamed-chunked-with-prohibited-trailer",
  5636. [&](const Request & /*req*/, Response &res) {
  5637. auto i = new int(0);
  5638. // Declare both a prohibited trailer (Content-Length) and an
  5639. // allowed one
  5640. res.set_header("Trailer", "Content-Length, X-Allowed");
  5641. res.set_chunked_content_provider(
  5642. "text/plain",
  5643. [i](size_t /*offset*/, DataSink &sink) {
  5644. switch (*i) {
  5645. case 0: sink.os << "123"; break;
  5646. case 1: sink.os << "456"; break;
  5647. case 2: sink.os << "789"; break;
  5648. case 3: {
  5649. sink.done_with_trailer(
  5650. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5651. } break;
  5652. }
  5653. (*i)++;
  5654. return true;
  5655. },
  5656. [i](bool success) {
  5657. EXPECT_TRUE(success);
  5658. delete i;
  5659. });
  5660. })
  5661. .Get("/streamed-chunked2",
  5662. [&](const Request & /*req*/, Response &res) {
  5663. auto i = new int(0);
  5664. res.set_chunked_content_provider(
  5665. "text/plain",
  5666. [i](size_t /*offset*/, DataSink &sink) {
  5667. switch (*i) {
  5668. case 0: sink.os << "123"; break;
  5669. case 1: sink.os << "456"; break;
  5670. case 2: sink.os << "789"; break;
  5671. case 3: sink.done(); break;
  5672. }
  5673. (*i)++;
  5674. return true;
  5675. },
  5676. [i](bool success) {
  5677. EXPECT_TRUE(success);
  5678. delete i;
  5679. });
  5680. })
  5681. .Get("/streamed-chunked-with-trailer",
  5682. [&](const Request & /*req*/, Response &res) {
  5683. auto i = new int(0);
  5684. res.set_header("Trailer", "Dummy1, Dummy2");
  5685. res.set_chunked_content_provider(
  5686. "text/plain",
  5687. [i](size_t /*offset*/, DataSink &sink) {
  5688. switch (*i) {
  5689. case 0: sink.os << "123"; break;
  5690. case 1: sink.os << "456"; break;
  5691. case 2: sink.os << "789"; break;
  5692. case 3: {
  5693. sink.done_with_trailer(
  5694. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5695. } break;
  5696. }
  5697. (*i)++;
  5698. return true;
  5699. },
  5700. [i](bool success) {
  5701. EXPECT_TRUE(success);
  5702. delete i;
  5703. });
  5704. })
  5705. .Get("/streamed",
  5706. [&](const Request & /*req*/, Response &res) {
  5707. res.set_content_provider(
  5708. 6, "text/plain",
  5709. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5710. sink.os << (offset < 3 ? "a" : "b");
  5711. return true;
  5712. });
  5713. })
  5714. .Get("/streamed-without-length",
  5715. [&](const Request & /*req*/, Response &res) {
  5716. auto data = new std::string("abcdefg");
  5717. res.set_content_provider(
  5718. "text/plain",
  5719. [data](size_t offset, DataSink &sink) {
  5720. if (offset < data->size()) {
  5721. sink.os << data->substr(offset);
  5722. }
  5723. sink.done();
  5724. return true;
  5725. },
  5726. [data](bool success) {
  5727. EXPECT_TRUE(success);
  5728. delete data;
  5729. });
  5730. })
  5731. .Get("/streamed-with-range",
  5732. [&](const Request &req, Response &res) {
  5733. auto data = new std::string("abcdefg");
  5734. // An explicit status keeps the server from picking the 206 it
  5735. // would otherwise choose for a ranged request, so the response
  5736. // is not a partial representation.
  5737. auto status = req.get_param_value("status");
  5738. if (status == "200") {
  5739. res.status = StatusCode::OK_200;
  5740. } else if (status == "403") {
  5741. res.status = StatusCode::Forbidden_403;
  5742. }
  5743. res.set_content_provider(
  5744. data->size(), "text/plain",
  5745. [data](size_t offset, size_t length, DataSink &sink) {
  5746. size_t DATA_CHUNK_SIZE = 4;
  5747. const auto &d = *data;
  5748. auto out_len =
  5749. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5750. auto ret =
  5751. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5752. EXPECT_TRUE(ret);
  5753. return true;
  5754. },
  5755. [data, &req](bool success) {
  5756. EXPECT_EQ(success, !req.has_param("error"));
  5757. delete data;
  5758. });
  5759. })
  5760. .Get("/streamed-cancel",
  5761. [&](const Request & /*req*/, Response &res) {
  5762. res.set_content_provider(
  5763. size_t(-1), "text/plain",
  5764. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5765. sink.os << "data_chunk";
  5766. return true;
  5767. });
  5768. })
  5769. .Get("/regex-with-delimiter",
  5770. [&](const Request &req, Response & /*res*/) {
  5771. ASSERT_TRUE(req.has_param("key"));
  5772. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5773. })
  5774. .Get("/with-range",
  5775. [&](const Request & /*req*/, Response &res) {
  5776. res.set_content("abcdefg", "text/plain");
  5777. })
  5778. .Get("/test-start-time",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. EXPECT_NE(req.start_time_,
  5781. std::chrono::steady_clock::time_point::min());
  5782. })
  5783. .Get("/with-range-customized-response",
  5784. [&](const Request & /*req*/, Response &res) {
  5785. res.status = StatusCode::BadRequest_400;
  5786. res.set_content(JSON_DATA, "application/json");
  5787. })
  5788. .Post("/chunked",
  5789. [&](const Request &req, Response & /*res*/) {
  5790. EXPECT_EQ(req.body, "dechunked post body");
  5791. })
  5792. .Post("/large-chunked",
  5793. [&](const Request &req, Response & /*res*/) {
  5794. std::string expected(6 * 30 * 1024u, 'a');
  5795. EXPECT_EQ(req.body, expected);
  5796. })
  5797. .Post("/multipart",
  5798. [&](const Request &req, Response & /*res*/) {
  5799. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5800. req.form.get_field_count("text2") +
  5801. req.form.get_field_count("file3") +
  5802. req.form.get_field_count("file4"));
  5803. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5804. req.form.get_file_count("file2"));
  5805. ASSERT_TRUE(!req.form.has_file("???"));
  5806. ASSERT_TRUE(!req.form.has_field("???"));
  5807. ASSERT_TRUE(req.body.empty());
  5808. {
  5809. const auto &text = req.form.get_field("text1");
  5810. EXPECT_EQ("text default", text);
  5811. }
  5812. {
  5813. const auto &text = req.form.get_field("text2");
  5814. EXPECT_EQ("aωb", text);
  5815. }
  5816. {
  5817. const auto &file = req.form.get_file("file1");
  5818. EXPECT_EQ("hello.txt", file.filename);
  5819. EXPECT_EQ("text/plain", file.content_type);
  5820. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5821. }
  5822. {
  5823. const auto &file = req.form.get_file("file2");
  5824. EXPECT_EQ("world.json", file.filename);
  5825. EXPECT_EQ("application/json", file.content_type);
  5826. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5827. }
  5828. {
  5829. const auto &text = req.form.get_field("file3");
  5830. EXPECT_EQ(0u, text.size());
  5831. }
  5832. {
  5833. const auto &text = req.form.get_field("file4");
  5834. EXPECT_EQ(0u, text.size());
  5835. }
  5836. })
  5837. .Post("/multipart/multi_file_values",
  5838. [&](const Request &req, Response & /*res*/) {
  5839. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5840. req.form.get_field_count("multi_text1"));
  5841. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5842. ASSERT_TRUE(!req.form.has_file("???"));
  5843. ASSERT_TRUE(!req.form.has_field("???"));
  5844. ASSERT_TRUE(req.body.empty());
  5845. {
  5846. const auto &text = req.form.get_field("text");
  5847. EXPECT_EQ("default text", text);
  5848. }
  5849. {
  5850. const auto &text1_values = req.form.get_fields("multi_text1");
  5851. EXPECT_EQ(2u, text1_values.size());
  5852. EXPECT_EQ("aaaaa", text1_values[0]);
  5853. EXPECT_EQ("bbbbb", text1_values[1]);
  5854. }
  5855. {
  5856. const auto &file1_values = req.form.get_files("multi_file1");
  5857. EXPECT_EQ(2u, file1_values.size());
  5858. auto file1 = file1_values[0];
  5859. EXPECT_EQ(file1.filename, "hello.txt");
  5860. EXPECT_EQ(file1.content_type, "text/plain");
  5861. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5862. auto file2 = file1_values[1];
  5863. EXPECT_EQ(file2.filename, "world.json");
  5864. EXPECT_EQ(file2.content_type, "application/json");
  5865. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5866. }
  5867. })
  5868. .Post("/empty",
  5869. [&](const Request &req, Response &res) {
  5870. EXPECT_EQ(req.body, "");
  5871. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5872. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5873. res.set_content("empty", "text/plain");
  5874. })
  5875. .Post("/empty-no-content-type",
  5876. [&](const Request &req, Response &res) {
  5877. EXPECT_EQ(req.body, "");
  5878. EXPECT_FALSE(req.has_header("Content-Type"));
  5879. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5880. res.set_content("empty-no-content-type", "text/plain");
  5881. })
  5882. .Post("/path-only",
  5883. [&](const Request &req, Response &res) {
  5884. EXPECT_EQ(req.body, "");
  5885. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5886. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5887. res.set_content("path-only", "text/plain");
  5888. })
  5889. .Post("/path-headers-only",
  5890. [&](const Request &req, Response &res) {
  5891. EXPECT_EQ(req.body, "");
  5892. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5893. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5894. EXPECT_EQ("world", req.get_header_value("hello"));
  5895. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5896. res.set_content("path-headers-only", "text/plain");
  5897. })
  5898. .Post("/post-large",
  5899. [&](const Request &req, Response &res) {
  5900. EXPECT_EQ(req.body, LARGE_DATA);
  5901. res.set_content(req.body, "text/plain");
  5902. })
  5903. .Post("/post-loopback",
  5904. [&](const Request &, Response &res,
  5905. ContentReader const &content_reader) {
  5906. std::string body;
  5907. content_reader([&](const char *data, size_t data_length) {
  5908. body.append(data, data_length);
  5909. return true;
  5910. });
  5911. res.set_content(body, "text/plain");
  5912. })
  5913. .Put("/put-loopback",
  5914. [&](const Request &, Response &res,
  5915. ContentReader const &content_reader) {
  5916. std::string body;
  5917. content_reader([&](const char *data, size_t data_length) {
  5918. body.append(data, data_length);
  5919. return true;
  5920. });
  5921. res.set_content(body, "text/plain");
  5922. })
  5923. .Patch("/patch-loopback",
  5924. [&](const Request &, Response &res,
  5925. ContentReader const &content_reader) {
  5926. std::string body;
  5927. content_reader([&](const char *data, size_t data_length) {
  5928. body.append(data, data_length);
  5929. return true;
  5930. });
  5931. res.set_content(body, "text/plain");
  5932. })
  5933. .Put("/empty-no-content-type",
  5934. [&](const Request &req, Response &res) {
  5935. EXPECT_EQ(req.body, "");
  5936. EXPECT_FALSE(req.has_header("Content-Type"));
  5937. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5938. res.set_content("empty-no-content-type", "text/plain");
  5939. })
  5940. .Put("/put",
  5941. [&](const Request &req, Response &res) {
  5942. EXPECT_EQ(req.body, "PUT");
  5943. res.set_content(req.body, "text/plain");
  5944. })
  5945. .Put("/put-large",
  5946. [&](const Request &req, Response &res) {
  5947. EXPECT_EQ(req.body, LARGE_DATA);
  5948. res.set_content(req.body, "text/plain");
  5949. })
  5950. .Patch("/patch",
  5951. [&](const Request &req, Response &res) {
  5952. EXPECT_EQ(req.body, "PATCH");
  5953. res.set_content(req.body, "text/plain");
  5954. })
  5955. .Delete("/delete",
  5956. [&](const Request & /*req*/, Response &res) {
  5957. res.set_content("DELETE", "text/plain");
  5958. })
  5959. .Delete("/delete-body",
  5960. [&](const Request &req, Response &res) {
  5961. EXPECT_EQ(req.body, "content");
  5962. res.set_content(req.body, "text/plain");
  5963. })
  5964. .Options(R"(\*)",
  5965. [&](const Request & /*req*/, Response &res) {
  5966. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5967. })
  5968. .CustomRoute("PROPFIND", "/dav/:id",
  5969. [&](const Request &req, Response &res) {
  5970. res.set_header("x-body-size",
  5971. std::to_string(req.body.size()));
  5972. res.set_header("x-matched-route", req.matched_route);
  5973. res.set_header("x-dav-id", req.path_params.at("id"));
  5974. res.status = StatusCode::MultiStatus_207;
  5975. res.set_content(req.body, "application/xml");
  5976. })
  5977. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5978. [&](const Request &req, Response &res) {
  5979. res.set_header("x-dav-match", req.matches[1]);
  5980. res.status = StatusCode::MultiStatus_207;
  5981. })
  5982. .CustomRoute("MKCOL", "/dav-mkcol",
  5983. [&](const Request &req, Response &res) {
  5984. EXPECT_TRUE(req.body.empty());
  5985. res.status = StatusCode::Created_201;
  5986. })
  5987. .CustomRoute(
  5988. "REPORT", "/dav-report",
  5989. [&](const Request & /*req*/, Response &res,
  5990. const ContentReader &content_reader) {
  5991. std::string body;
  5992. content_reader([&](const char *data, size_t data_length) {
  5993. body.append(data, data_length);
  5994. return true;
  5995. });
  5996. res.set_header("x-body-size", std::to_string(body.size()));
  5997. res.status = StatusCode::MultiStatus_207;
  5998. res.set_content(body, "application/xml");
  5999. })
  6000. .Get("/request-target",
  6001. [&](const Request &req, Response & /*res*/) {
  6002. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6003. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6004. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6005. })
  6006. .Get("/long-query-value",
  6007. [&](const Request &req, Response & /*res*/) {
  6008. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6009. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6010. })
  6011. .Get("/too-long-query-value",
  6012. [&](const Request &req, Response & /*res*/) {
  6013. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6014. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6015. })
  6016. .Get("/array-param",
  6017. [&](const Request &req, Response & /*res*/) {
  6018. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6019. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6020. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6021. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6022. })
  6023. .Get("/array-param-values",
  6024. [&](const Request &req, Response & /*res*/) {
  6025. auto values = req.get_param_values("array");
  6026. EXPECT_EQ(3u, values.size());
  6027. EXPECT_EQ("value1", values[0]);
  6028. EXPECT_EQ("value2", values[1]);
  6029. EXPECT_EQ("value3", values[2]);
  6030. auto empty = req.get_param_values("nonexistent");
  6031. EXPECT_TRUE(empty.empty());
  6032. })
  6033. .Post("/validate-no-multiple-headers",
  6034. [&](const Request &req, Response & /*res*/) {
  6035. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6036. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6037. })
  6038. .Post("/content_receiver",
  6039. [&](const Request &req, Response &res,
  6040. const ContentReader &content_reader) {
  6041. if (req.is_multipart_form_data()) {
  6042. std::vector<FormData> items;
  6043. content_reader(
  6044. [&](const FormData &file) {
  6045. items.push_back(file);
  6046. return true;
  6047. },
  6048. [&](const char *data, size_t data_length) {
  6049. items.back().content.append(data, data_length);
  6050. return true;
  6051. });
  6052. EXPECT_EQ(5u, items.size());
  6053. {
  6054. const auto &file = get_file_value(items, "text1");
  6055. EXPECT_TRUE(file.filename.empty());
  6056. EXPECT_EQ("text default", file.content);
  6057. }
  6058. {
  6059. const auto &file = get_file_value(items, "text2");
  6060. EXPECT_TRUE(file.filename.empty());
  6061. EXPECT_EQ("aωb", file.content);
  6062. }
  6063. {
  6064. const auto &file = get_file_value(items, "file1");
  6065. EXPECT_EQ("hello.txt", file.filename);
  6066. EXPECT_EQ("text/plain", file.content_type);
  6067. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6068. }
  6069. {
  6070. const auto &file = get_file_value(items, "file2");
  6071. EXPECT_EQ("world.json", file.filename);
  6072. EXPECT_EQ("application/json", file.content_type);
  6073. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6074. }
  6075. {
  6076. const auto &file = get_file_value(items, "file3");
  6077. EXPECT_TRUE(file.filename.empty());
  6078. EXPECT_EQ("application/octet-stream", file.content_type);
  6079. EXPECT_EQ(0u, file.content.size());
  6080. }
  6081. } else {
  6082. std::string body;
  6083. content_reader([&](const char *data, size_t data_length) {
  6084. EXPECT_EQ(7U, data_length);
  6085. body.append(data, data_length);
  6086. return true;
  6087. });
  6088. EXPECT_EQ(body, "content");
  6089. res.set_content(body, "text/plain");
  6090. }
  6091. })
  6092. .Put("/content_receiver",
  6093. [&](const Request & /*req*/, Response &res,
  6094. const ContentReader &content_reader) {
  6095. std::string body;
  6096. content_reader([&](const char *data, size_t data_length) {
  6097. body.append(data, data_length);
  6098. return true;
  6099. });
  6100. EXPECT_EQ(body, "content");
  6101. res.set_content(body, "text/plain");
  6102. })
  6103. .Patch("/content_receiver",
  6104. [&](const Request & /*req*/, Response &res,
  6105. const ContentReader &content_reader) {
  6106. std::string body;
  6107. content_reader([&](const char *data, size_t data_length) {
  6108. body.append(data, data_length);
  6109. return true;
  6110. });
  6111. EXPECT_EQ(body, "content");
  6112. res.set_content(body, "text/plain");
  6113. })
  6114. .Post("/query-string-and-body",
  6115. [&](const Request &req, Response & /*res*/) {
  6116. ASSERT_TRUE(req.has_param("key"));
  6117. EXPECT_EQ(req.get_param_value("key"), "value");
  6118. EXPECT_EQ(req.body, "content");
  6119. })
  6120. .Get("/last-request",
  6121. [&](const Request &req, Response & /*res*/) {
  6122. EXPECT_EQ("close", req.get_header_value("Connection"));
  6123. })
  6124. .Get(R"(/redirect/(\d+))",
  6125. [&](const Request &req, Response &res) {
  6126. auto num = std::stoi(req.matches[1]) + 1;
  6127. std::string url = "/redirect/" + std::to_string(num);
  6128. res.set_redirect(url);
  6129. })
  6130. .Post("/binary",
  6131. [&](const Request &req, Response &res) {
  6132. EXPECT_EQ(4U, req.body.size());
  6133. EXPECT_EQ("application/octet-stream",
  6134. req.get_header_value("Content-Type"));
  6135. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6136. res.set_content(req.body, "application/octet-stream");
  6137. })
  6138. .Put("/binary",
  6139. [&](const Request &req, Response &res) {
  6140. EXPECT_EQ(4U, req.body.size());
  6141. EXPECT_EQ("application/octet-stream",
  6142. req.get_header_value("Content-Type"));
  6143. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6144. res.set_content(req.body, "application/octet-stream");
  6145. })
  6146. .Patch("/binary",
  6147. [&](const Request &req, Response &res) {
  6148. EXPECT_EQ(4U, req.body.size());
  6149. EXPECT_EQ("application/octet-stream",
  6150. req.get_header_value("Content-Type"));
  6151. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6152. res.set_content(req.body, "application/octet-stream");
  6153. })
  6154. .Delete("/binary",
  6155. [&](const Request &req, Response &res) {
  6156. EXPECT_EQ(4U, req.body.size());
  6157. EXPECT_EQ("application/octet-stream",
  6158. req.get_header_value("Content-Type"));
  6159. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6160. res.set_content(req.body, "application/octet-stream");
  6161. })
  6162. .Get("/issue1772",
  6163. [&](const Request & /*req*/, Response &res) {
  6164. res.status = 401;
  6165. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6166. })
  6167. .Delete("/issue609",
  6168. [](const httplib::Request &, httplib::Response &res,
  6169. const httplib::ContentReader &) {
  6170. res.set_content("ok", "text/plain");
  6171. })
  6172. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6173. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6174. .Get("/compress",
  6175. [&](const Request & /*req*/, Response &res) {
  6176. res.set_content(
  6177. "12345678901234567890123456789012345678901234567890123456789"
  6178. "01234567890123456789012345678901234567890",
  6179. "text/plain");
  6180. })
  6181. .Get("/compress-with-charset",
  6182. [&](const Request & /*req*/, Response &res) {
  6183. res.set_content(
  6184. "12345678901234567890123456789012345678901234567890123456789"
  6185. "01234567890123456789012345678901234567890",
  6186. "application/json; charset=utf-8");
  6187. })
  6188. .Get("/nocompress",
  6189. [&](const Request & /*req*/, Response &res) {
  6190. res.set_content(
  6191. "12345678901234567890123456789012345678901234567890123456789"
  6192. "01234567890123456789012345678901234567890",
  6193. "application/octet-stream");
  6194. })
  6195. .Post("/compress-multipart",
  6196. [&](const Request &req, Response & /*res*/) {
  6197. EXPECT_EQ(2u, req.form.fields.size());
  6198. ASSERT_TRUE(!req.form.has_field("???"));
  6199. {
  6200. const auto &text = req.form.get_field("key1");
  6201. EXPECT_EQ("test", text);
  6202. }
  6203. {
  6204. const auto &text = req.form.get_field("key2");
  6205. EXPECT_EQ("--abcdefg123", text);
  6206. }
  6207. })
  6208. #endif
  6209. ;
  6210. persons_["john"] = "programmer";
  6211. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6212. svr_.wait_until_ready();
  6213. }
  6214. virtual void TearDown() {
  6215. svr_.stop();
  6216. if (!request_threads_.empty()) {
  6217. std::this_thread::sleep_for(std::chrono::seconds(1));
  6218. for (auto &t : request_threads_) {
  6219. t.join();
  6220. }
  6221. }
  6222. t_.join();
  6223. }
  6224. map<string, string> persons_;
  6225. #ifdef CPPHTTPLIB_SSL_ENABLED
  6226. SSLClient cli_;
  6227. SSLServer svr_;
  6228. #else
  6229. Client cli_;
  6230. Server svr_;
  6231. #endif
  6232. thread t_;
  6233. std::vector<thread> request_threads_;
  6234. };
  6235. TEST_F(ServerTest, GetMethod200) {
  6236. auto res = cli_.Get("/hi");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. EXPECT_EQ("HTTP/1.1", res->version);
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. EXPECT_EQ("OK", res->reason);
  6241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6242. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6243. EXPECT_EQ("Hello World!", res->body);
  6244. }
  6245. TEST_F(ServerTest, GetEmptyFile) {
  6246. auto res = cli_.Get("/empty_file");
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. EXPECT_EQ(StatusCode::OK_200, res->status);
  6249. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6250. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6251. EXPECT_EQ("", res->body);
  6252. }
  6253. TEST_F(ServerTest, GetFileContent) {
  6254. auto res = cli_.Get("/file_content");
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::OK_200, res->status);
  6257. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6258. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6259. EXPECT_EQ("test.html", res->body);
  6260. }
  6261. TEST_F(ServerTest, GetFileContentWithRange) {
  6262. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6265. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6266. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6267. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6268. EXPECT_EQ("est", res->body);
  6269. }
  6270. TEST_F(ServerTest, GetFileContentWithContentType) {
  6271. auto res = cli_.Get("/file_content_with_content_type");
  6272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6273. EXPECT_EQ(StatusCode::OK_200, res->status);
  6274. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6275. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6276. EXPECT_EQ("file\n", res->body);
  6277. }
  6278. TEST_F(ServerTest, GetInvalidFileContent) {
  6279. auto res = cli_.Get("/invalid_file_content");
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6282. }
  6283. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6284. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ("HTTP/1.1", res->version);
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6289. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6290. EXPECT_EQ("Hello World!", res->body);
  6291. }
  6292. TEST_F(ServerTest, GetMethod302) {
  6293. auto res = cli_.Get("/");
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::Found_302, res->status);
  6296. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6297. }
  6298. TEST_F(ServerTest, GetMethod302Redirect) {
  6299. cli_.set_follow_location(true);
  6300. auto res = cli_.Get("/");
  6301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6302. EXPECT_EQ(StatusCode::OK_200, res->status);
  6303. EXPECT_EQ("Hello World!", res->body);
  6304. EXPECT_EQ("/hi", res->location);
  6305. }
  6306. TEST_F(ServerTest, GetMethod404) {
  6307. auto res = cli_.Get("/invalid");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6310. }
  6311. TEST_F(ServerTest, HeadMethod200) {
  6312. auto res = cli_.Head("/hi");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::OK_200, res->status);
  6315. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6316. EXPECT_TRUE(res->body.empty());
  6317. }
  6318. TEST_F(ServerTest, HeadMethod200Static) {
  6319. auto res = cli_.Head("/mount/dir/index.html");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::OK_200, res->status);
  6322. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6323. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6324. EXPECT_TRUE(res->body.empty());
  6325. }
  6326. TEST_F(ServerTest, HeadMethod404) {
  6327. auto res = cli_.Head("/invalid");
  6328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6330. EXPECT_TRUE(res->body.empty());
  6331. }
  6332. TEST_F(ServerTest, GetMethodPersonJohn) {
  6333. auto res = cli_.Get("/person/john");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::OK_200, res->status);
  6336. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6337. EXPECT_EQ("programmer", res->body);
  6338. }
  6339. TEST_F(ServerTest, PostMethod1) {
  6340. auto res = cli_.Get("/person/john1");
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6343. res = cli_.Post("/person", "name=john1&note=coder",
  6344. "application/x-www-form-urlencoded");
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. ASSERT_EQ(StatusCode::OK_200, res->status);
  6347. res = cli_.Get("/person/john1");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. ASSERT_EQ(StatusCode::OK_200, res->status);
  6350. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6351. ASSERT_EQ("coder", res->body);
  6352. }
  6353. TEST_F(ServerTest, PostMethod2) {
  6354. auto res = cli_.Get("/person/john2");
  6355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6356. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6357. Params params;
  6358. params.emplace("name", "john2");
  6359. params.emplace("note", "coder");
  6360. res = cli_.Post("/person", params);
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. ASSERT_EQ(StatusCode::OK_200, res->status);
  6363. res = cli_.Get("/person/john2");
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. ASSERT_EQ(StatusCode::OK_200, res->status);
  6366. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6367. ASSERT_EQ("coder", res->body);
  6368. }
  6369. TEST_F(ServerTest, PutMethod3) {
  6370. auto res = cli_.Get("/person/john3");
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6373. Params params;
  6374. params.emplace("name", "john3");
  6375. params.emplace("note", "coder");
  6376. res = cli_.Put("/person", params);
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. ASSERT_EQ(StatusCode::OK_200, res->status);
  6379. res = cli_.Get("/person/john3");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. ASSERT_EQ(StatusCode::OK_200, res->status);
  6382. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6383. ASSERT_EQ("coder", res->body);
  6384. }
  6385. TEST_F(ServerTest, DeleteMethod1) {
  6386. auto res = cli_.Get("/person/john4");
  6387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6388. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6389. Params params;
  6390. params.emplace("name", "john4");
  6391. params.emplace("note", "coder");
  6392. res = cli_.Post("/person", params);
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. ASSERT_EQ(StatusCode::OK_200, res->status);
  6395. res = cli_.Get("/person/john4");
  6396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6397. ASSERT_EQ(StatusCode::OK_200, res->status);
  6398. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6399. ASSERT_EQ("coder", res->body);
  6400. Params delete_params;
  6401. delete_params.emplace("name", "john4");
  6402. res = cli_.Delete("/person", delete_params);
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. ASSERT_EQ(StatusCode::OK_200, res->status);
  6405. ASSERT_EQ("DELETED", res->body);
  6406. res = cli_.Get("/person/john4");
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6409. }
  6410. TEST_F(ServerTest, DeleteMethod2) {
  6411. auto res = cli_.Get("/person/john5");
  6412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6413. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6414. Params params;
  6415. params.emplace("name", "john5");
  6416. params.emplace("note", "developer");
  6417. res = cli_.Post("/person", params);
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. ASSERT_EQ(StatusCode::OK_200, res->status);
  6420. res = cli_.Get("/person/john5");
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. ASSERT_EQ(StatusCode::OK_200, res->status);
  6423. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6424. ASSERT_EQ("developer", res->body);
  6425. Params delete_params;
  6426. delete_params.emplace("name", "john5");
  6427. Headers headers;
  6428. headers.emplace("Custom-Header", "test-value");
  6429. res = cli_.Delete("/person", headers, delete_params);
  6430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6431. ASSERT_EQ(StatusCode::OK_200, res->status);
  6432. ASSERT_EQ("DELETED", res->body);
  6433. res = cli_.Get("/person/john5");
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6436. }
  6437. TEST_F(ServerTest, DeleteMethod3) {
  6438. auto res = cli_.Get("/person/john6");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6441. Params params;
  6442. params.emplace("name", "john6");
  6443. params.emplace("note", "tester");
  6444. res = cli_.Post("/person", params);
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. ASSERT_EQ(StatusCode::OK_200, res->status);
  6447. res = cli_.Get("/person/john6");
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. ASSERT_EQ(StatusCode::OK_200, res->status);
  6450. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6451. ASSERT_EQ("tester", res->body);
  6452. Params delete_params;
  6453. delete_params.emplace("name", "john6");
  6454. Headers headers;
  6455. headers.emplace("Custom-Header", "test-value");
  6456. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. ASSERT_EQ(StatusCode::OK_200, res->status);
  6459. ASSERT_EQ("DELETED", res->body);
  6460. res = cli_.Get("/person/john6");
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6463. }
  6464. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6465. Params params;
  6466. params.emplace("json", JSON_DATA);
  6467. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6469. ASSERT_EQ(StatusCode::OK_200, res->status);
  6470. ASSERT_EQ(JSON_DATA, res->body);
  6471. }
  6472. TEST_F(ServerTest, PostEmptyContent) {
  6473. auto res = cli_.Post("/empty", "", "text/plain");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ("empty", res->body);
  6477. }
  6478. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6479. auto res = cli_.Post("/empty-no-content-type");
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. ASSERT_EQ(StatusCode::OK_200, res->status);
  6482. ASSERT_EQ("empty-no-content-type", res->body);
  6483. }
  6484. TEST_F(ServerTest, PostPathOnly) {
  6485. auto res = cli_.Post("/path-only");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ("path-only", res->body);
  6489. }
  6490. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6491. auto res = cli_.Post("/path-headers-only",
  6492. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. ASSERT_EQ(StatusCode::OK_200, res->status);
  6495. ASSERT_EQ("path-headers-only", res->body);
  6496. }
  6497. TEST_F(ServerTest, PostLarge) {
  6498. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. ASSERT_EQ(StatusCode::OK_200, res->status);
  6501. EXPECT_EQ(LARGE_DATA, res->body);
  6502. }
  6503. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6504. auto res = cli_.Put("/empty-no-content-type");
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. ASSERT_EQ(StatusCode::OK_200, res->status);
  6507. ASSERT_EQ("empty-no-content-type", res->body);
  6508. }
  6509. TEST_F(ServerTest, GetMethodDir) {
  6510. auto res = cli_.Get("/dir/");
  6511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6512. EXPECT_EQ(StatusCode::OK_200, res->status);
  6513. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6514. auto body = R"(<html>
  6515. <head>
  6516. </head>
  6517. <body>
  6518. <a href="/dir/test.html">Test</a>
  6519. <a href="/hi">hi</a>
  6520. </body>
  6521. </html>
  6522. )";
  6523. EXPECT_EQ(body, res->body);
  6524. }
  6525. TEST_F(ServerTest, GetMethodDirTest) {
  6526. auto res = cli_.Get("/dir/test.html");
  6527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6528. EXPECT_EQ(StatusCode::OK_200, res->status);
  6529. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6530. EXPECT_EQ("test.html", res->body);
  6531. }
  6532. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6533. auto res = cli_.Get("/dir/../dir/test.html");
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. }
  6537. TEST_F(ServerTest, GetMethodInvalidPath) {
  6538. auto res = cli_.Get("/dir/../test.html");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6541. }
  6542. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6543. auto res = cli_.Get("/../www/dir/test.html");
  6544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6546. }
  6547. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6548. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6551. }
  6552. TEST_F(ServerTest, GetMethodDirMountTest) {
  6553. auto res = cli_.Get("/mount/dir/test.html");
  6554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6555. EXPECT_EQ(StatusCode::OK_200, res->status);
  6556. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6557. EXPECT_EQ("test.html", res->body);
  6558. }
  6559. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6560. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6563. }
  6564. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6565. auto res = cli_.Get("/mount/dir/../test.html");
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6568. }
  6569. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6570. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6573. }
  6574. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6575. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6578. }
  6579. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6580. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6583. }
  6584. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6585. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6588. }
  6589. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6590. auto res = cli_.Get("/mount/dir");
  6591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6592. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6593. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6594. }
  6595. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6596. auto res = cli_.Get("//dir");
  6597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6598. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6599. EXPECT_FALSE(res->has_header("Location"));
  6600. }
  6601. TEST_F(ServerTest, PostMethod303) {
  6602. auto res = cli_.Post("/1", "body", "text/plain");
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6605. EXPECT_EQ("/2", res->get_header_value("Location"));
  6606. }
  6607. TEST_F(ServerTest, PostMethod303Redirect) {
  6608. cli_.set_follow_location(true);
  6609. auto res = cli_.Post("/1", "body", "text/plain");
  6610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6611. EXPECT_EQ(StatusCode::OK_200, res->status);
  6612. EXPECT_EQ("redirected.", res->body);
  6613. EXPECT_EQ("/2", res->location);
  6614. }
  6615. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6616. auto res = cli_.Get("/dir/test.abcde");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6620. EXPECT_EQ("abcde", res->body);
  6621. }
  6622. TEST_F(ServerTest, StaticFileRange) {
  6623. auto res =
  6624. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6627. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6628. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6629. EXPECT_EQ(true, res->has_header("Content-Range"));
  6630. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6631. EXPECT_EQ(std::string("cd"), res->body);
  6632. }
  6633. TEST_F(ServerTest, StaticFileRanges) {
  6634. auto res = cli_.Get("/dir/test.abcde",
  6635. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6637. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6638. EXPECT_TRUE(
  6639. res->get_header_value("Content-Type")
  6640. .find(
  6641. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6642. 0);
  6643. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6644. }
  6645. TEST_F(ServerTest, StaticFileRangeHead) {
  6646. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6649. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6650. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6651. EXPECT_EQ(true, res->has_header("Content-Range"));
  6652. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6653. }
  6654. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6655. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6657. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6658. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6659. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6660. EXPECT_EQ(true, res->has_header("Content-Range"));
  6661. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6662. res->get_header_value("Content-Range"));
  6663. EXPECT_EQ("LAST\n", res->body);
  6664. }
  6665. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6666. auto res =
  6667. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6670. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6671. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6672. EXPECT_EQ(true, res->has_header("Content-Range"));
  6673. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6674. }
  6675. TEST_F(ServerTest, StaticFileBigFile) {
  6676. auto res = cli_.Get("/dir/1MB.txt");
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::OK_200, res->status);
  6679. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6680. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6681. }
  6682. TEST_F(ServerTest, InvalidBaseDirMount) {
  6683. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6684. }
  6685. TEST_F(ServerTest, Binary) {
  6686. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6687. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6688. "application/octet-stream");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. ASSERT_EQ(StatusCode::OK_200, res->status);
  6691. ASSERT_EQ(4U, res->body.size());
  6692. res = cli_.Put("/binary", binary.data(), binary.size(),
  6693. "application/octet-stream");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. ASSERT_EQ(StatusCode::OK_200, res->status);
  6696. ASSERT_EQ(4U, res->body.size());
  6697. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6698. "application/octet-stream");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. ASSERT_EQ(StatusCode::OK_200, res->status);
  6701. ASSERT_EQ(4U, res->body.size());
  6702. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6703. "application/octet-stream");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. ASSERT_EQ(StatusCode::OK_200, res->status);
  6706. ASSERT_EQ(4U, res->body.size());
  6707. }
  6708. TEST_F(ServerTest, BinaryString) {
  6709. auto binary = std::string("\x00\x01\x02\x03", 4);
  6710. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. ASSERT_EQ(StatusCode::OK_200, res->status);
  6713. ASSERT_EQ(4U, res->body.size());
  6714. res = cli_.Put("/binary", binary, "application/octet-stream");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. ASSERT_EQ(StatusCode::OK_200, res->status);
  6717. ASSERT_EQ(4U, res->body.size());
  6718. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. ASSERT_EQ(StatusCode::OK_200, res->status);
  6721. ASSERT_EQ(4U, res->body.size());
  6722. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. ASSERT_EQ(StatusCode::OK_200, res->status);
  6725. ASSERT_EQ(4U, res->body.size());
  6726. }
  6727. TEST_F(ServerTest, EmptyRequest) {
  6728. auto res = cli_.Get("");
  6729. ASSERT_TRUE(!res);
  6730. EXPECT_EQ(Error::Connection, res.error());
  6731. }
  6732. TEST_F(ServerTest, LongRequest) {
  6733. std::string request;
  6734. for (size_t i = 0; i < 545; i++) {
  6735. request += "/TooLongRequest";
  6736. }
  6737. request += "OK";
  6738. auto res = cli_.Get(request.c_str());
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6741. }
  6742. TEST_F(ServerTest, TooLongRequest) {
  6743. std::string request;
  6744. for (size_t i = 0; i < 546; i++) {
  6745. request += "/TooLongRequest";
  6746. }
  6747. request += "_NG";
  6748. auto start = std::chrono::high_resolution_clock::now();
  6749. cli_.set_keep_alive(true);
  6750. auto res = cli_.Get(request.c_str());
  6751. auto end = std::chrono::high_resolution_clock::now();
  6752. auto elapsed =
  6753. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6754. .count();
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6757. EXPECT_LE(elapsed, 1000);
  6758. EXPECT_EQ("close", res->get_header_value("Connection"));
  6759. EXPECT_FALSE(cli_.is_socket_open());
  6760. }
  6761. TEST_F(ServerTest, AlmostTooLongRequest) {
  6762. // test for #2046 - URI length check shouldn't include other content on req
  6763. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6764. // leading /, space, HTTP/1.1)
  6765. std::string request =
  6766. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6767. auto res = cli_.Get(request.c_str());
  6768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6769. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6770. }
  6771. TEST_F(ServerTest, LongHeader) {
  6772. Request req;
  6773. req.method = "GET";
  6774. req.path = "/hi";
  6775. std::string host_and_port;
  6776. host_and_port += HOST;
  6777. host_and_port += ":";
  6778. host_and_port += std::to_string(PORT);
  6779. req.headers.emplace("Host", host_and_port.c_str());
  6780. req.headers.emplace("Accept", "*/*");
  6781. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6782. req.headers.emplace(
  6783. "Header-Name",
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6812. "@@@@@@@@@@@@@@@@");
  6813. auto res = std::make_shared<Response>();
  6814. auto error = Error::Success;
  6815. auto ret = cli_.send(req, *res, error);
  6816. ASSERT_TRUE(ret);
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. }
  6819. TEST_F(ServerTest, LongQueryValue) {
  6820. auto start = std::chrono::high_resolution_clock::now();
  6821. cli_.set_keep_alive(true);
  6822. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6823. auto end = std::chrono::high_resolution_clock::now();
  6824. auto elapsed =
  6825. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6826. .count();
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6829. EXPECT_LE(elapsed, 1000);
  6830. EXPECT_EQ("close", res->get_header_value("Connection"));
  6831. EXPECT_FALSE(cli_.is_socket_open());
  6832. }
  6833. TEST_F(ServerTest, TooLongQueryValue) {
  6834. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6835. ASSERT_FALSE(res);
  6836. EXPECT_EQ(Error::Read, res.error());
  6837. }
  6838. TEST_F(ServerTest, TooLongHeader) {
  6839. Request req;
  6840. req.method = "GET";
  6841. req.path = "/hi";
  6842. std::string host_and_port;
  6843. host_and_port += HOST;
  6844. host_and_port += ":";
  6845. host_and_port += std::to_string(PORT);
  6846. req.headers.emplace("Host", host_and_port.c_str());
  6847. req.headers.emplace("Accept", "*/*");
  6848. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6849. req.headers.emplace(
  6850. "Header-Name",
  6851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6879. "@@@@@@@@@@@@@@@@@");
  6880. auto res = std::make_shared<Response>();
  6881. auto error = Error::Success;
  6882. auto ret = cli_.send(req, *res, error);
  6883. ASSERT_TRUE(ret);
  6884. EXPECT_EQ(StatusCode::OK_200, res->status);
  6885. }
  6886. TEST_F(ServerTest, HeaderCountAtLimit) {
  6887. // Test with headers just under the 100 limit
  6888. httplib::Headers headers;
  6889. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6890. // This should keep us just under the 100 header limit
  6891. for (int i = 0; i < 95; i++) {
  6892. std::string name = "X-Test-Header-" + std::to_string(i);
  6893. std::string value = "value" + std::to_string(i);
  6894. headers.emplace(name, value);
  6895. }
  6896. // This should work fine as we're under the limit
  6897. auto res = cli_.Get("/hi", headers);
  6898. EXPECT_TRUE(res);
  6899. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6900. }
  6901. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6902. // Test with many headers to exceed the 100 limit
  6903. httplib::Headers headers;
  6904. // Add 150 headers to definitely exceed the 100 limit
  6905. for (int i = 0; i < 150; i++) {
  6906. std::string name = "X-Test-Header-" + std::to_string(i);
  6907. std::string value = "value" + std::to_string(i);
  6908. headers.emplace(name, value);
  6909. }
  6910. // This should fail due to exceeding header count limit
  6911. cli_.set_keep_alive(true);
  6912. auto res = cli_.Get("/hi", headers);
  6913. // The server should respond with 400 Bad Request
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6916. EXPECT_EQ("close", res->get_header_value("Connection"));
  6917. EXPECT_FALSE(cli_.is_socket_open());
  6918. }
  6919. TEST_F(ServerTest, PercentEncoding) {
  6920. auto res = cli_.Get("/e%6edwith%");
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. }
  6924. TEST_F(ServerTest, PercentEncodingUnicode) {
  6925. auto res = cli_.Get("/e%u006edwith%");
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::OK_200, res->status);
  6928. }
  6929. TEST_F(ServerTest, InvalidPercentEncoding) {
  6930. auto res = cli_.Get("/%endwith%");
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6933. }
  6934. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6935. auto res = cli_.Get("/%uendwith%");
  6936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6937. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6938. }
  6939. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6940. auto res = cli_.Get("/hello?aaa=bbb%");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6943. }
  6944. TEST_F(ServerTest, PlusSignEncoding) {
  6945. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. EXPECT_EQ("a +b", res->body);
  6949. }
  6950. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6951. // This test simulates a potential DoS attack using many headers
  6952. // to verify our security fix prevents memory exhaustion
  6953. httplib::Headers attack_headers;
  6954. // Attempt to add many headers like an attacker would (200 headers to far
  6955. // exceed limit)
  6956. for (int i = 0; i < 200; i++) {
  6957. std::string name = "X-Attack-Header-" + std::to_string(i);
  6958. std::string value = "attack_payload_" + std::to_string(i);
  6959. attack_headers.emplace(name, value);
  6960. }
  6961. // Try to POST with excessive headers
  6962. cli_.set_keep_alive(true);
  6963. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6964. // Should either fail or return 400 Bad Request due to security limit
  6965. if (res) {
  6966. // If we get a response, it should be 400 Bad Request
  6967. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6968. EXPECT_EQ("close", res->get_header_value("Connection"));
  6969. }
  6970. EXPECT_FALSE(cli_.is_socket_open());
  6971. }
  6972. TEST_F(ServerTest, MultipartFormData) {
  6973. UploadFormDataItems items = {
  6974. {"text1", "text default", "", ""},
  6975. {"text2", "aωb", "", ""},
  6976. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6977. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6978. {"file3", "", "", "application/octet-stream"},
  6979. {"file4", "", "", " application/json tmp-string "}};
  6980. auto res = cli_.Post("/multipart", items);
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::OK_200, res->status);
  6983. }
  6984. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6985. UploadFormDataItems items = {
  6986. {"text", "default text", "", ""},
  6987. {"multi_text1", "aaaaa", "", ""},
  6988. {"multi_text1", "bbbbb", "", ""},
  6989. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6990. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6991. "application/json"},
  6992. };
  6993. auto res = cli_.Post("/multipart/multi_file_values", items);
  6994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. }
  6997. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6998. auto res = cli_.Get("/hi");
  6999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7000. EXPECT_EQ(StatusCode::OK_200, res->status);
  7001. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7002. EXPECT_EQ("Hello World!", res->body);
  7003. }
  7004. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7005. Request req;
  7006. req.method = "POST";
  7007. req.path = "/chunked";
  7008. std::string host_and_port;
  7009. host_and_port += HOST;
  7010. host_and_port += ":";
  7011. host_and_port += std::to_string(PORT);
  7012. req.headers.emplace("Host", host_and_port.c_str());
  7013. req.headers.emplace("Accept", "*/*");
  7014. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7015. req.headers.emplace("Content-Type", "text/plain");
  7016. req.headers.emplace("Content-Length", "0");
  7017. req.headers.emplace(
  7018. "Transfer-Encoding",
  7019. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7020. // Client does not chunk, so make a chunked body manually.
  7021. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7022. auto res = std::make_shared<Response>();
  7023. auto error = Error::Success;
  7024. auto ret = cli_.send(req, *res, error);
  7025. ASSERT_TRUE(ret);
  7026. EXPECT_EQ(StatusCode::OK_200, res->status);
  7027. }
  7028. template <typename ClientT>
  7029. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7030. int expected_status) {
  7031. Request req;
  7032. req.method = "POST";
  7033. req.path = "/chunked";
  7034. std::string host_and_port;
  7035. host_and_port += HOST;
  7036. host_and_port += ":";
  7037. host_and_port += std::to_string(PORT);
  7038. req.headers.emplace("Host", host_and_port.c_str());
  7039. req.headers.emplace("Content-Length", "0");
  7040. req.headers.emplace("Transfer-Encoding", "chunked");
  7041. req.body = body;
  7042. auto res = std::make_shared<Response>();
  7043. auto error = Error::Success;
  7044. ASSERT_TRUE(cli.send(req, *res, error));
  7045. EXPECT_EQ(expected_status, res->status);
  7046. }
  7047. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7048. // rather than treat them as valid lengths.
  7049. template <typename ClientT>
  7050. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7051. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7052. }
  7053. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7054. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7055. }
  7056. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7057. expect_chunked_body_rejected(
  7058. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7059. }
  7060. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7061. // chunk-size line carries no CR, LF or other control character ahead of its
  7062. // terminator. Such a line must be refused rather than read as extension text.
  7063. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7064. expect_chunked_body_rejected(
  7065. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7066. }
  7067. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7068. expect_chunked_body_rejected(
  7069. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7070. }
  7071. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7072. expect_chunked_body_rejected(
  7073. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7074. }
  7075. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7076. // The literal stays split: a hex escape consumes every hex digit that
  7077. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7078. expect_chunked_body_rejected(
  7079. cli_, "4;a\x01"
  7080. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7081. }
  7082. // The bytes around chunk data are no payload, so they cannot ride on the
  7083. // payload limit
  7084. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7085. // Small enough that the whole request is sent before the server turns it
  7086. // down, yet past the limit by the last chunks
  7087. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7088. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7089. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7090. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7091. SCOPED_TRACE(size_line.substr(0, 2));
  7092. std::string body;
  7093. for (auto c : std::string("dechunked post body")) {
  7094. body += size_line + "\r\n" + c + "\r\n";
  7095. }
  7096. body += "0\r\n\r\n";
  7097. expect_chunked_body_rejected(cli_, body.c_str());
  7098. }
  7099. }
  7100. TEST_F(ServerTest, AcceptsChunkExtension) {
  7101. expect_chunked_body_status(cli_,
  7102. "4;name=value\r\ndech\r\n"
  7103. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7104. "0;last\r\n\r\n",
  7105. StatusCode::OK_200);
  7106. }
  7107. TEST_F(ServerTest, GetStreamed2) {
  7108. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7111. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7112. EXPECT_EQ(true, res->has_header("Content-Range"));
  7113. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7114. EXPECT_EQ(std::string("ab"), res->body);
  7115. }
  7116. TEST_F(ServerTest, GetStreamed) {
  7117. auto res = cli_.Get("/streamed");
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::OK_200, res->status);
  7120. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7121. EXPECT_EQ(std::string("aaabbb"), res->body);
  7122. }
  7123. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7124. auto res = cli_.Get("/streamed-without-length",
  7125. Headers{make_range_header({{0, -1}})});
  7126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7127. EXPECT_EQ(StatusCode::OK_200, res->status);
  7128. EXPECT_EQ(false, res->has_header("Content-Length"));
  7129. EXPECT_EQ(false, res->has_header("Content-Range"));
  7130. EXPECT_EQ(std::string("abcdefg"), res->body);
  7131. }
  7132. TEST_F(ServerTest, GetStreamedWithRange1) {
  7133. auto res =
  7134. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7136. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7137. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7138. EXPECT_EQ(true, res->has_header("Content-Range"));
  7139. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7140. EXPECT_EQ(std::string("def"), res->body);
  7141. }
  7142. TEST_F(ServerTest, GetStreamedWithRange2) {
  7143. auto res =
  7144. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7147. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7148. EXPECT_EQ(true, res->has_header("Content-Range"));
  7149. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7150. EXPECT_EQ(std::string("bcdefg"), res->body);
  7151. }
  7152. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7153. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7156. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7157. EXPECT_EQ(true, res->has_header("Content-Range"));
  7158. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7159. EXPECT_EQ(std::string("efg"), res->body);
  7160. }
  7161. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7162. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7163. // the entire representation.
  7164. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7165. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7168. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7169. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7170. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7171. }
  7172. }
  7173. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7174. auto res =
  7175. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7177. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7178. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7179. EXPECT_EQ(false, res->has_header("Content-Range"));
  7180. EXPECT_EQ(0U, res->body.size());
  7181. }
  7182. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7183. // Only a 206 is served as a partial representation. Under any other status
  7184. // `apply_ranges()` reported the full content length, so the body must match
  7185. // that header, and the content provider must never be asked for an offset
  7186. // outside the representation.
  7187. auto check = [&](int status, const char *range) {
  7188. auto path =
  7189. std::string("/streamed-with-range?status=") + std::to_string(status);
  7190. auto ctx = path + " Range: " + range;
  7191. auto res = cli_.Get(path, Headers{{"Range", range}});
  7192. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7193. EXPECT_EQ(status, res->status) << ctx;
  7194. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7195. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7196. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7197. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7198. };
  7199. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7200. check(403, "bytes=3-5");
  7201. // The offset is far past the representation.
  7202. check(403, "bytes=100000-100200");
  7203. // `first_pos` is still -1 here, and the bounds asserts in
  7204. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7205. check(403, "bytes=-3");
  7206. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7207. // multipart branch would have written one that is empty.
  7208. check(403, "bytes=1-2, 4-5");
  7209. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7210. // covers the whole representation.
  7211. check(200, "bytes=3-5");
  7212. check(200, "bytes=1-2, 4-5");
  7213. }
  7214. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7215. auto res =
  7216. cli_.Get("/streamed-with-range",
  7217. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7218. "92233720368547758079223372036854775807"}});
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7221. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7222. EXPECT_EQ(false, res->has_header("Content-Range"));
  7223. EXPECT_EQ(0U, res->body.size());
  7224. }
  7225. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7226. auto res = cli_.Get(
  7227. "/with-range",
  7228. Headers{{"Range",
  7229. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7230. {"Accept-Encoding", ""}});
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7233. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7234. EXPECT_EQ(true, res->has_header("Content-Range"));
  7235. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7236. EXPECT_EQ(std::string("abcdefg"), res->body);
  7237. }
  7238. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7239. auto res = cli_.Get("/with-range", Headers{
  7240. {"Range", "bytes=0-"},
  7241. {"Accept-Encoding", ""},
  7242. });
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7245. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7246. EXPECT_EQ(true, res->has_header("Content-Range"));
  7247. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7248. EXPECT_EQ(std::string("abcdefg"), res->body);
  7249. }
  7250. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7251. auto res = cli_.Get("/streamed-with-range",
  7252. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7255. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7256. EXPECT_EQ(false, res->has_header("Content-Range"));
  7257. EXPECT_EQ(267U, res->body.size());
  7258. // Check that both range contents are present
  7259. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7260. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7261. // Check that Content-Range headers are present for both ranges
  7262. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7263. std::string::npos);
  7264. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7265. std::string::npos);
  7266. }
  7267. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7268. Ranges ranges;
  7269. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7270. ranges.emplace_back(0, -1);
  7271. }
  7272. auto res = cli_.Get("/streamed-with-range?error",
  7273. Headers{{make_range_header(ranges)}});
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7276. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7277. EXPECT_EQ(false, res->has_header("Content-Range"));
  7278. EXPECT_EQ(0U, res->body.size());
  7279. }
  7280. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7281. auto res = cli_.Get("/streamed-with-range",
  7282. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7285. EXPECT_EQ(5U, res->body.size());
  7286. // Check that overlapping ranges are coalesced into a single range
  7287. EXPECT_EQ("bcdef", res->body);
  7288. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7289. // Should be single range, not multipart
  7290. EXPECT_TRUE(res->has_header("Content-Range"));
  7291. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7292. }
  7293. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7294. auto res = cli_.Get("/streamed-with-range",
  7295. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7298. EXPECT_EQ(268U, res->body.size());
  7299. // Check that both range contents are present
  7300. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7301. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7302. // Check that Content-Range headers are present for both ranges
  7303. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7304. std::string::npos);
  7305. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7306. std::string::npos);
  7307. }
  7308. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7309. auto res = cli_.Get("/streamed-with-range",
  7310. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7313. EXPECT_EQ(269U, res->body.size());
  7314. // Check that both duplicate range contents are present
  7315. size_t first_abc = res->body.find("abc\r\n");
  7316. EXPECT_TRUE(first_abc != std::string::npos);
  7317. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7318. EXPECT_TRUE(second_abc != std::string::npos);
  7319. // Check that Content-Range headers are present for both ranges
  7320. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7321. EXPECT_TRUE(first_range != std::string::npos);
  7322. size_t second_range =
  7323. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7324. EXPECT_TRUE(second_range != std::string::npos);
  7325. }
  7326. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7327. auto res =
  7328. cli_.Get("/streamed-with-range?error",
  7329. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7332. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7333. EXPECT_EQ(false, res->has_header("Content-Range"));
  7334. EXPECT_EQ(0U, res->body.size());
  7335. }
  7336. TEST_F(ServerTest, GetStreamedEndless) {
  7337. uint64_t offset = 0;
  7338. auto res = cli_.Get("/streamed-cancel",
  7339. [&](const char * /*data*/, uint64_t data_length) {
  7340. if (offset < 100) {
  7341. offset += data_length;
  7342. return true;
  7343. }
  7344. return false;
  7345. });
  7346. ASSERT_TRUE(!res);
  7347. EXPECT_EQ(Error::Canceled, res.error());
  7348. }
  7349. TEST_F(ServerTest, ClientStop) {
  7350. std::atomic_size_t count{4};
  7351. std::vector<std::thread> threads;
  7352. for (auto i = count.load(); i != 0; --i) {
  7353. threads.emplace_back([&]() {
  7354. auto res = cli_.Get("/streamed-cancel",
  7355. [&](const char *, uint64_t) { return true; });
  7356. --count;
  7357. ASSERT_TRUE(!res);
  7358. EXPECT_TRUE(res.error() == Error::Canceled ||
  7359. res.error() == Error::Read || res.error() == Error::Write);
  7360. });
  7361. }
  7362. std::this_thread::sleep_for(std::chrono::seconds(2));
  7363. while (count != 0) {
  7364. cli_.stop();
  7365. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7366. }
  7367. for (auto &t : threads) {
  7368. t.join();
  7369. }
  7370. }
  7371. TEST_F(ServerTest, GetWithRange1) {
  7372. auto res = cli_.Get("/with-range", Headers{
  7373. make_range_header({{3, 5}}),
  7374. {"Accept-Encoding", ""},
  7375. });
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7378. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7379. EXPECT_EQ(true, res->has_header("Content-Range"));
  7380. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7381. EXPECT_EQ(std::string("def"), res->body);
  7382. }
  7383. TEST_F(ServerTest, GetWithRange2) {
  7384. auto res = cli_.Get("/with-range", Headers{
  7385. make_range_header({{1, -1}}),
  7386. {"Accept-Encoding", ""},
  7387. });
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7390. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7391. EXPECT_EQ(true, res->has_header("Content-Range"));
  7392. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7393. EXPECT_EQ(std::string("bcdefg"), res->body);
  7394. }
  7395. TEST_F(ServerTest, GetWithRange3) {
  7396. auto res = cli_.Get("/with-range", Headers{
  7397. make_range_header({{0, 0}}),
  7398. {"Accept-Encoding", ""},
  7399. });
  7400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7402. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7403. EXPECT_EQ(true, res->has_header("Content-Range"));
  7404. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7405. EXPECT_EQ(std::string("a"), res->body);
  7406. }
  7407. TEST_F(ServerTest, GetWithRange4) {
  7408. auto res = cli_.Get("/with-range", Headers{
  7409. make_range_header({{-1, 2}}),
  7410. {"Accept-Encoding", ""},
  7411. });
  7412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7413. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7414. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7415. EXPECT_EQ(true, res->has_header("Content-Range"));
  7416. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7417. EXPECT_EQ(std::string("fg"), res->body);
  7418. }
  7419. TEST_F(ServerTest, GetWithRange5) {
  7420. auto res = cli_.Get("/with-range", Headers{
  7421. make_range_header({{0, 5}}),
  7422. {"Accept-Encoding", ""},
  7423. });
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7426. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7427. EXPECT_EQ(true, res->has_header("Content-Range"));
  7428. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7429. EXPECT_EQ(std::string("abcdef"), res->body);
  7430. }
  7431. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7432. auto res =
  7433. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7436. }
  7437. TEST_F(ServerTest, GetWithRangeMultipart) {
  7438. auto res =
  7439. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7442. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7443. EXPECT_EQ(false, res->has_header("Content-Range"));
  7444. EXPECT_EQ(267U, res->body.size());
  7445. }
  7446. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7447. auto res = cli_.Get("/with-range",
  7448. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7451. }
  7452. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7453. auto res = cli_.Get("/with-range-customized-response",
  7454. Headers{{make_range_header({{1, 2}})}});
  7455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7456. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7457. EXPECT_EQ(true, res->has_header("Content-Length"));
  7458. EXPECT_EQ(false, res->has_header("Content-Range"));
  7459. EXPECT_EQ(JSON_DATA, res->body);
  7460. }
  7461. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7462. auto res = cli_.Get("/with-range-customized-response",
  7463. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7466. EXPECT_EQ(true, res->has_header("Content-Length"));
  7467. EXPECT_EQ(false, res->has_header("Content-Range"));
  7468. EXPECT_EQ(JSON_DATA, res->body);
  7469. }
  7470. TEST_F(ServerTest, Issue1772) {
  7471. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7473. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7474. }
  7475. TEST_F(ServerTest, Issue609) {
  7476. auto res = cli_.Delete("/issue609");
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. EXPECT_EQ(std::string("ok"), res->body);
  7480. }
  7481. TEST_F(ServerTest, GetStreamedChunked) {
  7482. auto res = cli_.Get("/streamed-chunked");
  7483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7484. EXPECT_EQ(StatusCode::OK_200, res->status);
  7485. EXPECT_EQ(std::string("123456789"), res->body);
  7486. }
  7487. TEST_F(ServerTest, GetStreamedChunked2) {
  7488. auto res = cli_.Get("/streamed-chunked2");
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. EXPECT_EQ(std::string("123456789"), res->body);
  7492. }
  7493. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7494. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7496. EXPECT_EQ(StatusCode::OK_200, res->status);
  7497. EXPECT_EQ(std::string("123456789"), res->body);
  7498. EXPECT_TRUE(res->has_header("Trailer"));
  7499. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7500. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7501. // Trailers are now stored separately from headers (security fix)
  7502. EXPECT_EQ(2U, res->trailers.size());
  7503. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7504. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7505. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7506. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7507. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7508. // Verify trailers are NOT in headers (security verification)
  7509. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7510. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7511. }
  7512. TEST_F(ServerTest, LargeChunkedPost) {
  7513. Request req;
  7514. req.method = "POST";
  7515. req.path = "/large-chunked";
  7516. std::string host_and_port;
  7517. host_and_port += HOST;
  7518. host_and_port += ":";
  7519. host_and_port += std::to_string(PORT);
  7520. req.headers.emplace("Host", host_and_port.c_str());
  7521. req.headers.emplace("Accept", "*/*");
  7522. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7523. req.headers.emplace("Content-Type", "text/plain");
  7524. req.headers.emplace("Content-Length", "0");
  7525. req.headers.emplace("Transfer-Encoding", "chunked");
  7526. std::string long_string(30 * 1024u, 'a');
  7527. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7528. // Attempt to make a large enough post to exceed OS buffers, to test that
  7529. // the server handles short reads if the full chunk data isn't available.
  7530. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7531. auto res = std::make_shared<Response>();
  7532. auto error = Error::Success;
  7533. auto ret = cli_.send(req, *res, error);
  7534. ASSERT_TRUE(ret);
  7535. EXPECT_EQ(StatusCode::OK_200, res->status);
  7536. }
  7537. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7538. auto res = cli_.Get("/remote_addr");
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. EXPECT_EQ(StatusCode::OK_200, res->status);
  7541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7542. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7543. }
  7544. TEST_F(ServerTest, GetMethodLocalAddr) {
  7545. auto res = cli_.Get("/local_addr");
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(StatusCode::OK_200, res->status);
  7548. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7549. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7550. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7551. }
  7552. TEST_F(ServerTest, HTTPResponseSplitting) {
  7553. auto res = cli_.Get("/http_response_splitting");
  7554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7555. EXPECT_EQ(StatusCode::OK_200, res->status);
  7556. }
  7557. TEST_F(ServerTest, SlowRequest) {
  7558. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7559. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7560. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7561. }
  7562. #if 0
  7563. TEST_F(ServerTest, SlowPost) {
  7564. char buffer[64 * 1024];
  7565. memset(buffer, 0x42, sizeof(buffer));
  7566. auto res = cli_.Post(
  7567. "/slowpost", 64 * 1024 * 1024,
  7568. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7569. auto ret = sink.write(buffer, sizeof(buffer));
  7570. EXPECT_TRUE(ret);
  7571. return true;
  7572. },
  7573. "text/plain");
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. }
  7577. TEST_F(ServerTest, SlowPostFail) {
  7578. char buffer[64 * 1024];
  7579. memset(buffer, 0x42, sizeof(buffer));
  7580. cli_.set_write_timeout(std::chrono::seconds(0));
  7581. auto res = cli_.Post(
  7582. "/slowpost", 64 * 1024 * 1024,
  7583. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7584. sink.write(buffer, sizeof(buffer));
  7585. return true;
  7586. },
  7587. "text/plain");
  7588. ASSERT_TRUE(!res);
  7589. EXPECT_EQ(Error::Write, res.error());
  7590. }
  7591. #endif
  7592. TEST_F(ServerTest, Put) {
  7593. auto res = cli_.Put("/put", "PUT", "text/plain");
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. EXPECT_EQ("PUT", res->body);
  7597. }
  7598. TEST_F(ServerTest, PutWithContentProvider) {
  7599. auto res = cli_.Put(
  7600. "/put", 3,
  7601. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7602. sink.os << "PUT";
  7603. return true;
  7604. },
  7605. "text/plain");
  7606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7607. EXPECT_EQ(StatusCode::OK_200, res->status);
  7608. EXPECT_EQ("PUT", res->body);
  7609. }
  7610. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7611. auto res = cli_.Post(
  7612. "/post", 42,
  7613. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7614. return false;
  7615. },
  7616. "text/plain");
  7617. ASSERT_TRUE(!res);
  7618. EXPECT_EQ(Error::Canceled, res.error());
  7619. }
  7620. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7621. auto res = cli_.Put(
  7622. "/put",
  7623. [](size_t /*offset*/, DataSink &sink) {
  7624. sink.os << "PUT";
  7625. sink.done();
  7626. return true;
  7627. },
  7628. "text/plain");
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_EQ(StatusCode::OK_200, res->status);
  7631. EXPECT_EQ("PUT", res->body);
  7632. }
  7633. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7634. auto res = cli_.Post(
  7635. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7636. "text/plain");
  7637. ASSERT_TRUE(!res);
  7638. EXPECT_EQ(Error::Canceled, res.error());
  7639. }
  7640. TEST_F(ServerTest, PostLoopBack) {
  7641. std::string body;
  7642. auto res = cli_.Post(
  7643. "/post-loopback", 9,
  7644. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7645. EXPECT_EQ(9u, length);
  7646. sink.write("123", 3);
  7647. sink.write("456", 3);
  7648. sink.write("789", 3);
  7649. return true;
  7650. },
  7651. "text/plain",
  7652. [&body](const char *data, size_t data_length) {
  7653. body.append(data, data_length);
  7654. return true;
  7655. });
  7656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7657. EXPECT_EQ(StatusCode::OK_200, res->status);
  7658. EXPECT_EQ("123456789", body);
  7659. }
  7660. TEST_F(ServerTest, PutLoopBack) {
  7661. std::string body;
  7662. auto res = cli_.Put(
  7663. "/put-loopback", 9,
  7664. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7665. EXPECT_EQ(9u, length);
  7666. sink.write("123", 3);
  7667. sink.write("456", 3);
  7668. sink.write("789", 3);
  7669. return true;
  7670. },
  7671. "text/plain",
  7672. [&body](const char *data, size_t data_length) {
  7673. body.append(data, data_length);
  7674. return true;
  7675. });
  7676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7677. EXPECT_EQ(StatusCode::OK_200, res->status);
  7678. EXPECT_EQ("123456789", body);
  7679. }
  7680. TEST_F(ServerTest, PatchLoopBack) {
  7681. std::string body;
  7682. auto res = cli_.Patch(
  7683. "/patch-loopback", 9,
  7684. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7685. EXPECT_EQ(9u, length);
  7686. sink.write("123", 3);
  7687. sink.write("456", 3);
  7688. sink.write("789", 3);
  7689. return true;
  7690. },
  7691. "text/plain",
  7692. [&body](const char *data, size_t data_length) {
  7693. body.append(data, data_length);
  7694. return true;
  7695. });
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ("123456789", body);
  7699. }
  7700. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7701. std::string body;
  7702. auto res = cli_.Post(
  7703. "/post-loopback",
  7704. [](size_t /*offset*/, DataSink &sink) {
  7705. sink.write("123", 3);
  7706. sink.write("456", 3);
  7707. sink.write("789", 3);
  7708. sink.done();
  7709. return true;
  7710. },
  7711. "text/plain",
  7712. [&body](const char *data, size_t data_length) {
  7713. body.append(data, data_length);
  7714. return true;
  7715. });
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::OK_200, res->status);
  7718. EXPECT_EQ("123456789", body);
  7719. }
  7720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7721. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7722. cli_.set_compress(true);
  7723. auto res = cli_.Put(
  7724. "/put", 3,
  7725. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7726. sink.os << "PUT";
  7727. return true;
  7728. },
  7729. "text/plain");
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. EXPECT_EQ("PUT", res->body);
  7733. }
  7734. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7735. cli_.set_compress(true);
  7736. auto res = cli_.Post(
  7737. "/post", 42,
  7738. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7739. return false;
  7740. },
  7741. "text/plain");
  7742. ASSERT_TRUE(!res);
  7743. EXPECT_EQ(Error::Canceled, res.error());
  7744. }
  7745. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7746. cli_.set_compress(true);
  7747. auto res = cli_.Put(
  7748. "/put",
  7749. [](size_t /*offset*/, DataSink &sink) {
  7750. sink.os << "PUT";
  7751. sink.done();
  7752. return true;
  7753. },
  7754. "text/plain");
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::OK_200, res->status);
  7757. EXPECT_EQ("PUT", res->body);
  7758. }
  7759. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7760. cli_.set_compress(true);
  7761. auto res = cli_.Post(
  7762. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7763. "text/plain");
  7764. ASSERT_TRUE(!res);
  7765. EXPECT_EQ(Error::Canceled, res.error());
  7766. }
  7767. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7768. cli_.set_compress(true);
  7769. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. EXPECT_EQ(LARGE_DATA, res->body);
  7773. }
  7774. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7775. #ifdef CPPHTTPLIB_SSL_ENABLED
  7776. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7777. Client cli(s.c_str());
  7778. cli.enable_server_certificate_verification(false);
  7779. #else
  7780. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7781. Client cli(s.c_str());
  7782. #endif
  7783. cli.set_compress(true);
  7784. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::OK_200, res->status);
  7787. EXPECT_EQ(LARGE_DATA, res->body);
  7788. // The compressed size should be less than a 10th of the original. May vary
  7789. // depending on the zlib library.
  7790. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7791. static_cast<uint64_t>(10 * 1024 * 1024));
  7792. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7793. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7794. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7795. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7796. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7797. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7798. #endif
  7799. }
  7800. TEST_F(ServerTest, PutContentWithDeflate) {
  7801. cli_.set_compress(false);
  7802. Headers headers;
  7803. headers.emplace("Content-Encoding", "deflate");
  7804. // PUT in deflate format:
  7805. auto res = cli_.Put("/put", headers,
  7806. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::OK_200, res->status);
  7809. EXPECT_EQ("PUT", res->body);
  7810. }
  7811. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7812. Headers headers;
  7813. headers.emplace("Accept-Encoding", "gzip, deflate");
  7814. auto res = cli_.Get("/streamed-chunked", headers);
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. EXPECT_EQ(std::string("123456789"), res->body);
  7818. }
  7819. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7820. Headers headers;
  7821. headers.emplace("Accept-Encoding", "gzip, deflate");
  7822. auto res = cli_.Get("/streamed-chunked2", headers);
  7823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7824. EXPECT_EQ(StatusCode::OK_200, res->status);
  7825. EXPECT_EQ(std::string("123456789"), res->body);
  7826. }
  7827. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7828. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::OK_200, res->status);
  7831. }
  7832. TEST(GzipDecompressor, ChunkedDecompression) {
  7833. std::string data;
  7834. for (size_t i = 0; i < 32 * 1024; ++i) {
  7835. data.push_back(static_cast<char>('a' + i % 26));
  7836. }
  7837. std::string compressed_data;
  7838. {
  7839. httplib::detail::gzip_compressor compressor;
  7840. bool result = compressor.compress(
  7841. data.data(), data.size(),
  7842. /*last=*/true,
  7843. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7844. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7845. compressed_data_size);
  7846. return true;
  7847. });
  7848. ASSERT_TRUE(result);
  7849. }
  7850. std::string decompressed_data;
  7851. {
  7852. httplib::detail::gzip_decompressor decompressor;
  7853. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7854. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7855. size_t chunk_size = 130;
  7856. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7857. chunk_begin += chunk_size) {
  7858. size_t current_chunk_size =
  7859. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7860. bool result = decompressor.decompress(
  7861. compressed_data.data() + chunk_begin, current_chunk_size,
  7862. [&](const char *decompressed_data_chunk,
  7863. size_t decompressed_data_chunk_size) {
  7864. decompressed_data.insert(decompressed_data.size(),
  7865. decompressed_data_chunk,
  7866. decompressed_data_chunk_size);
  7867. return true;
  7868. });
  7869. ASSERT_TRUE(result);
  7870. }
  7871. }
  7872. ASSERT_EQ(data, decompressed_data);
  7873. }
  7874. TEST(GzipDecompressor, DeflateDecompression) {
  7875. std::string original_text = "Raw deflate without gzip";
  7876. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7877. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7878. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7879. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7880. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7881. std::string decompressed_data;
  7882. {
  7883. httplib::detail::gzip_decompressor decompressor;
  7884. bool result = decompressor.decompress(
  7885. compressed_data.data(), compressed_data.size(),
  7886. [&](const char *decompressed_data_chunk,
  7887. size_t decompressed_data_chunk_size) {
  7888. decompressed_data.insert(decompressed_data.size(),
  7889. decompressed_data_chunk,
  7890. decompressed_data_chunk_size);
  7891. return true;
  7892. });
  7893. ASSERT_TRUE(result);
  7894. }
  7895. ASSERT_EQ(original_text, decompressed_data);
  7896. }
  7897. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7898. std::string original_text = "Raw deflate without gzip";
  7899. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7900. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7901. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7902. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7903. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7904. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7905. std::string decompressed_data;
  7906. {
  7907. httplib::detail::gzip_decompressor decompressor;
  7908. bool result = decompressor.decompress(
  7909. compressed_data.data(), compressed_data.size(),
  7910. [&](const char *decompressed_data_chunk,
  7911. size_t decompressed_data_chunk_size) {
  7912. decompressed_data.insert(decompressed_data.size(),
  7913. decompressed_data_chunk,
  7914. decompressed_data_chunk_size);
  7915. return true;
  7916. });
  7917. ASSERT_TRUE(result);
  7918. }
  7919. ASSERT_EQ(original_text, decompressed_data);
  7920. }
  7921. #endif
  7922. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7923. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7924. Headers headers;
  7925. headers.emplace("Accept-Encoding", "br");
  7926. auto res = cli_.Get("/streamed-chunked", headers);
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. EXPECT_EQ(std::string("123456789"), res->body);
  7930. }
  7931. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7932. Headers headers;
  7933. headers.emplace("Accept-Encoding", "br");
  7934. auto res = cli_.Get("/streamed-chunked2", headers);
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. EXPECT_EQ(std::string("123456789"), res->body);
  7938. }
  7939. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7940. cli_.set_compress(true);
  7941. auto res = cli_.Put(
  7942. "/put", 3,
  7943. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7944. sink.os << "PUT";
  7945. return true;
  7946. },
  7947. "text/plain");
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ(StatusCode::OK_200, res->status);
  7950. EXPECT_EQ("PUT", res->body);
  7951. }
  7952. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7953. cli_.set_compress(true);
  7954. auto res = cli_.Put(
  7955. "/put",
  7956. [](size_t /*offset*/, DataSink &sink) {
  7957. sink.os << "PUT";
  7958. sink.done();
  7959. return true;
  7960. },
  7961. "text/plain");
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. EXPECT_EQ(StatusCode::OK_200, res->status);
  7964. EXPECT_EQ("PUT", res->body);
  7965. }
  7966. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7967. cli_.set_compress(true);
  7968. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7970. EXPECT_EQ(StatusCode::OK_200, res->status);
  7971. EXPECT_EQ(LARGE_DATA, res->body);
  7972. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7973. }
  7974. #endif
  7975. TEST_F(ServerTest, Patch) {
  7976. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_EQ(StatusCode::OK_200, res->status);
  7979. EXPECT_EQ("PATCH", res->body);
  7980. }
  7981. TEST_F(ServerTest, Delete) {
  7982. auto res = cli_.Delete("/delete");
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("DELETE", res->body);
  7986. }
  7987. TEST_F(ServerTest, DeleteContentReceiver) {
  7988. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(StatusCode::OK_200, res->status);
  7991. EXPECT_EQ("content", res->body);
  7992. }
  7993. TEST_F(ServerTest, Options) {
  7994. auto res = cli_.Options("*");
  7995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7998. EXPECT_TRUE(res->body.empty());
  7999. }
  8000. TEST_F(ServerTest, URL) {
  8001. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. }
  8005. TEST_F(ServerTest, ArrayParam) {
  8006. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. }
  8010. TEST_F(ServerTest, ArrayParamValues) {
  8011. auto res =
  8012. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. }
  8016. TEST_F(ServerTest, NoMultipleHeaders) {
  8017. Headers headers = {{"Content-Length", "5"}};
  8018. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8019. "text/plain");
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. }
  8023. TEST_F(ServerTest, PostContentReceiver) {
  8024. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8026. ASSERT_EQ(StatusCode::OK_200, res->status);
  8027. ASSERT_EQ("content", res->body);
  8028. }
  8029. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8030. UploadFormDataItems items = {
  8031. {"text1", "text default", "", ""},
  8032. {"text2", "aωb", "", ""},
  8033. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8034. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8035. {"file3", "", "", "application/octet-stream"},
  8036. };
  8037. auto res = cli_.Post("/content_receiver", items);
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ(StatusCode::OK_200, res->status);
  8040. }
  8041. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8042. UploadFormDataItems items = {
  8043. {"text1", "text default", "", ""},
  8044. {"text2", "aωb", "", ""},
  8045. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8046. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8047. {"file3", "", "", "application/octet-stream"},
  8048. };
  8049. auto boundary = std::string("+++++");
  8050. std::string body;
  8051. for (const auto &item : items) {
  8052. body += "--" + boundary + "\r\n";
  8053. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8054. if (!item.filename.empty()) {
  8055. body += "; filename=\"" + item.filename + "\"";
  8056. }
  8057. body += "\r\n";
  8058. if (!item.content_type.empty()) {
  8059. body += "Content-Type: " + item.content_type + "\r\n";
  8060. }
  8061. body += "\r\n";
  8062. body += item.content + "\r\n";
  8063. }
  8064. body += "--" + boundary + "--\r\n";
  8065. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8066. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8068. EXPECT_EQ(StatusCode::OK_200, res->status);
  8069. }
  8070. TEST(MultipartFormDataTest, FieldEscaping) {
  8071. Server svr;
  8072. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8073. const ContentReader &content_reader) {
  8074. ASSERT_TRUE(req.is_multipart_form_data());
  8075. std::vector<FormData> received;
  8076. content_reader(
  8077. [&](const FormData &file) {
  8078. received.push_back(file);
  8079. return true;
  8080. },
  8081. [&](const char *data, size_t data_length) {
  8082. received.back().content.append(data, data_length);
  8083. return true;
  8084. });
  8085. // '"', CR and LF in names and filenames are escaped following the
  8086. // WHATWG HTML standard, so each part still parses as a single part
  8087. // with no injected headers. Content types get CR/LF escaped too,
  8088. // while '"' (legal there, e.g. quoted charset) is preserved.
  8089. ASSERT_EQ(4U, received.size());
  8090. EXPECT_EQ("na%22me", received[0].name);
  8091. EXPECT_EQ("quoted name", received[0].content);
  8092. EXPECT_EQ("file", received[1].name);
  8093. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8094. received[1].filename);
  8095. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8096. EXPECT_EQ("injected", received[1].content);
  8097. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8098. EXPECT_EQ("my%22file.txt", received[2].filename);
  8099. EXPECT_EQ("cr lf name", received[2].content);
  8100. EXPECT_EQ("typed", received[3].name);
  8101. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8102. received[3].content_type);
  8103. EXPECT_EQ("typed content", received[3].content);
  8104. });
  8105. auto port = svr.bind_to_any_port("localhost");
  8106. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8107. auto se = detail::scope_exit([&] {
  8108. svr.stop();
  8109. t.join();
  8110. ASSERT_FALSE(svr.is_running());
  8111. });
  8112. svr.wait_until_ready();
  8113. Client cli("localhost", port);
  8114. UploadFormDataItems items = {
  8115. {"na\"me", "quoted name", "", ""},
  8116. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8117. "application/octet-stream"},
  8118. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8119. {"typed", "typed content", "",
  8120. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8121. };
  8122. auto res = cli.Post("/post", items);
  8123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8124. EXPECT_EQ(StatusCode::OK_200, res->status);
  8125. }
  8126. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8127. const UploadFormDataItems items = {
  8128. {"name1", "Content 1", "", ""},
  8129. {"name2", "Content 2", "file2.txt", "text/plain"},
  8130. };
  8131. Server svr;
  8132. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8133. const ContentReader &content_reader) {
  8134. ASSERT_TRUE(req.is_multipart_form_data());
  8135. std::vector<FormData> received;
  8136. content_reader(
  8137. [&](const FormData &file) {
  8138. received.push_back(file);
  8139. return true;
  8140. },
  8141. [&](const char *data, size_t data_length) {
  8142. received.back().content.append(data, data_length);
  8143. return true;
  8144. });
  8145. ASSERT_EQ(2U, received.size());
  8146. EXPECT_EQ("name1", received[0].name);
  8147. EXPECT_EQ("Content 1", received[0].content);
  8148. EXPECT_EQ("name2", received[1].name);
  8149. EXPECT_EQ("Content 2", received[1].content);
  8150. EXPECT_EQ("file2.txt", received[1].filename);
  8151. EXPECT_EQ("text/plain", received[1].content_type);
  8152. });
  8153. auto port = svr.bind_to_any_port("localhost");
  8154. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8155. auto se = detail::scope_exit([&] {
  8156. svr.stop();
  8157. t.join();
  8158. ASSERT_FALSE(svr.is_running());
  8159. });
  8160. svr.wait_until_ready();
  8161. Client cli("localhost", port);
  8162. // Whole-body serialization with a generated boundary
  8163. {
  8164. MultipartFormDataWriter writer;
  8165. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8166. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8167. writer.content_type());
  8168. auto body = writer.serialize(items);
  8169. EXPECT_EQ(body.size(), writer.content_length(items));
  8170. auto res = cli.Post("/post", body, writer.content_type());
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(StatusCode::OK_200, res->status);
  8173. }
  8174. // Per-part framing with a custom boundary via a content provider
  8175. {
  8176. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8177. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8178. MultipartFormDataWriter writer("custom-boundary_123");
  8179. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8180. std::string body;
  8181. for (const auto &item : items) {
  8182. body += writer.item_begin(item);
  8183. body += item.content;
  8184. body += MultipartFormDataWriter::item_end();
  8185. }
  8186. body += writer.finish();
  8187. EXPECT_EQ(body.size(), writer.content_length(items));
  8188. auto res = cli.Post(
  8189. "/post", body.size(),
  8190. [&](size_t offset, size_t length, DataSink &sink) {
  8191. sink.write(body.data() + offset, length);
  8192. return true;
  8193. },
  8194. writer.content_type());
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. }
  8198. }
  8199. TEST_F(ServerTest, PostContentReceiverGzip) {
  8200. cli_.set_compress(true);
  8201. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8203. ASSERT_EQ(StatusCode::OK_200, res->status);
  8204. ASSERT_EQ("content", res->body);
  8205. }
  8206. TEST_F(ServerTest, PutContentReceiver) {
  8207. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. ASSERT_EQ(StatusCode::OK_200, res->status);
  8210. ASSERT_EQ("content", res->body);
  8211. }
  8212. TEST_F(ServerTest, PatchContentReceiver) {
  8213. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. ASSERT_EQ(StatusCode::OK_200, res->status);
  8216. ASSERT_EQ("content", res->body);
  8217. }
  8218. template <typename ClientType>
  8219. void TestWithHeadersAndContentReceiver(
  8220. ClientType &cli,
  8221. std::function<Result(ClientType &, const std::string &, const Headers &,
  8222. const std::string &, const std::string &,
  8223. ContentReceiver, DownloadProgress)>
  8224. request_func) {
  8225. Headers headers;
  8226. headers.emplace("X-Custom-Header", "test-value");
  8227. std::string received_body;
  8228. auto res = request_func(
  8229. cli, "/content_receiver", headers, "content", "application/json",
  8230. [&](const char *data, size_t data_length) {
  8231. received_body.append(data, data_length);
  8232. return true;
  8233. },
  8234. nullptr);
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. EXPECT_EQ("content", received_body);
  8238. }
  8239. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8240. #ifdef CPPHTTPLIB_SSL_ENABLED
  8241. using ClientT = SSLClient;
  8242. #else
  8243. using ClientT = Client;
  8244. #endif
  8245. TestWithHeadersAndContentReceiver<ClientT>(
  8246. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8247. const std::string &body, const std::string &content_type,
  8248. ContentReceiver receiver, DownloadProgress progress) {
  8249. return cli.Post(path, headers, body, content_type, receiver, progress);
  8250. });
  8251. }
  8252. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8253. #ifdef CPPHTTPLIB_SSL_ENABLED
  8254. using ClientT = SSLClient;
  8255. #else
  8256. using ClientT = Client;
  8257. #endif
  8258. TestWithHeadersAndContentReceiver<ClientT>(
  8259. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8260. const std::string &body, const std::string &content_type,
  8261. ContentReceiver receiver, DownloadProgress progress) {
  8262. return cli.Put(path, headers, body, content_type, receiver, progress);
  8263. });
  8264. }
  8265. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8266. #ifdef CPPHTTPLIB_SSL_ENABLED
  8267. using ClientT = SSLClient;
  8268. #else
  8269. using ClientT = Client;
  8270. #endif
  8271. TestWithHeadersAndContentReceiver<ClientT>(
  8272. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8273. const std::string &body, const std::string &content_type,
  8274. ContentReceiver receiver, DownloadProgress progress) {
  8275. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8276. });
  8277. }
  8278. template <typename ClientType>
  8279. void TestWithHeadersAndContentReceiverWithProgress(
  8280. ClientType &cli,
  8281. std::function<Result(ClientType &, const std::string &, const Headers &,
  8282. const std::string &, const std::string &,
  8283. ContentReceiver, DownloadProgress)>
  8284. request_func) {
  8285. Headers headers;
  8286. headers.emplace("X-Test-Header", "progress-test");
  8287. std::string received_body;
  8288. auto progress_called = false;
  8289. auto res = request_func(
  8290. cli, "/content_receiver", headers, "content", "text/plain",
  8291. [&](const char *data, size_t data_length) {
  8292. received_body.append(data, data_length);
  8293. return true;
  8294. },
  8295. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8296. progress_called = true;
  8297. return true;
  8298. });
  8299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8300. EXPECT_EQ(StatusCode::OK_200, res->status);
  8301. EXPECT_EQ("content", received_body);
  8302. EXPECT_TRUE(progress_called);
  8303. }
  8304. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8305. #ifdef CPPHTTPLIB_SSL_ENABLED
  8306. using ClientT = SSLClient;
  8307. #else
  8308. using ClientT = Client;
  8309. #endif
  8310. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8311. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8312. const std::string &body, const std::string &content_type,
  8313. ContentReceiver receiver, DownloadProgress progress) {
  8314. return cli.Post(path, headers, body, content_type, receiver, progress);
  8315. });
  8316. }
  8317. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8318. #ifdef CPPHTTPLIB_SSL_ENABLED
  8319. using ClientT = SSLClient;
  8320. #else
  8321. using ClientT = Client;
  8322. #endif
  8323. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8324. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8325. const std::string &body, const std::string &content_type,
  8326. ContentReceiver receiver, DownloadProgress progress) {
  8327. return cli.Put(path, headers, body, content_type, receiver, progress);
  8328. });
  8329. }
  8330. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8331. #ifdef CPPHTTPLIB_SSL_ENABLED
  8332. using ClientT = SSLClient;
  8333. #else
  8334. using ClientT = Client;
  8335. #endif
  8336. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8337. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8338. const std::string &body, const std::string &content_type,
  8339. ContentReceiver receiver, DownloadProgress progress) {
  8340. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8341. });
  8342. }
  8343. template <typename ClientType>
  8344. void TestWithHeadersAndContentReceiverError(
  8345. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8346. const Headers &, const std::string &,
  8347. const std::string &, ContentReceiver)>
  8348. request_func) {
  8349. Headers headers;
  8350. headers.emplace("X-Error-Test", "true");
  8351. std::string received_body;
  8352. auto receiver_failed = false;
  8353. auto res =
  8354. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8355. [&](const char *data, size_t data_length) {
  8356. received_body.append(data, data_length);
  8357. receiver_failed = true;
  8358. return false;
  8359. });
  8360. ASSERT_FALSE(res);
  8361. EXPECT_TRUE(receiver_failed);
  8362. }
  8363. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8364. #ifdef CPPHTTPLIB_SSL_ENABLED
  8365. using ClientT = SSLClient;
  8366. #else
  8367. using ClientT = Client;
  8368. #endif
  8369. TestWithHeadersAndContentReceiverError<ClientT>(
  8370. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8371. const std::string &body, const std::string &content_type,
  8372. ContentReceiver receiver) {
  8373. return cli.Post(path, headers, body, content_type, receiver);
  8374. });
  8375. }
  8376. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8377. #ifdef CPPHTTPLIB_SSL_ENABLED
  8378. using ClientT = SSLClient;
  8379. #else
  8380. using ClientT = Client;
  8381. #endif
  8382. TestWithHeadersAndContentReceiverError<ClientT>(
  8383. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8384. const std::string &body, const std::string &content_type,
  8385. ContentReceiver receiver) {
  8386. return cli.Put(path, headers, body, content_type, receiver);
  8387. });
  8388. }
  8389. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8390. #ifdef CPPHTTPLIB_SSL_ENABLED
  8391. using ClientT = SSLClient;
  8392. #else
  8393. using ClientT = Client;
  8394. #endif
  8395. TestWithHeadersAndContentReceiverError<ClientT>(
  8396. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8397. const std::string &body, const std::string &content_type,
  8398. ContentReceiver receiver) {
  8399. return cli.Patch(path, headers, body, content_type, receiver);
  8400. });
  8401. }
  8402. TEST_F(ServerTest, PostQueryStringAndBody) {
  8403. auto res =
  8404. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8406. ASSERT_EQ(StatusCode::OK_200, res->status);
  8407. }
  8408. TEST_F(ServerTest, HTTP2Magic) {
  8409. Request req;
  8410. req.method = "PRI";
  8411. req.path = "*";
  8412. req.body = "SM";
  8413. auto res = std::make_shared<Response>();
  8414. auto error = Error::Success;
  8415. auto ret = cli_.send(req, *res, error);
  8416. ASSERT_TRUE(ret);
  8417. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8418. }
  8419. TEST_F(ServerTest, KeepAlive) {
  8420. auto res = cli_.Get("/hi");
  8421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8422. EXPECT_EQ(StatusCode::OK_200, res->status);
  8423. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8424. EXPECT_EQ("Hello World!", res->body);
  8425. res = cli_.Get("/hi");
  8426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8427. EXPECT_EQ(StatusCode::OK_200, res->status);
  8428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8429. EXPECT_EQ("Hello World!", res->body);
  8430. res = cli_.Get("/hi");
  8431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8432. EXPECT_EQ(StatusCode::OK_200, res->status);
  8433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8434. EXPECT_EQ("Hello World!", res->body);
  8435. res = cli_.Get("/not-exist");
  8436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8438. res = cli_.Post("/empty", "", "text/plain");
  8439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8440. EXPECT_EQ(StatusCode::OK_200, res->status);
  8441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8442. EXPECT_EQ("empty", res->body);
  8443. EXPECT_EQ("close", res->get_header_value("Connection"));
  8444. res = cli_.Post(
  8445. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8446. "text/plain");
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8450. EXPECT_EQ("empty", res->body);
  8451. cli_.set_keep_alive(false);
  8452. res = cli_.Get("/last-request");
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ(StatusCode::OK_200, res->status);
  8455. EXPECT_EQ("close", res->get_header_value("Connection"));
  8456. }
  8457. TEST_F(ServerTest, TooManyRedirect) {
  8458. cli_.set_follow_location(true);
  8459. auto res = cli_.Get("/redirect/0");
  8460. ASSERT_TRUE(!res);
  8461. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8462. }
  8463. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8464. Request req;
  8465. req.method = "FOOBAR";
  8466. req.path = "/hi";
  8467. cli_.set_keep_alive(true);
  8468. auto res = cli_.send(req);
  8469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8470. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8471. EXPECT_EQ("close", res->get_header_value("Connection"));
  8472. EXPECT_FALSE(cli_.is_socket_open());
  8473. }
  8474. TEST_F(ServerTest, CustomRouteReadsBody) {
  8475. const std::string xml =
  8476. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8477. Request req;
  8478. req.method = "PROPFIND";
  8479. req.path = "/dav/dir";
  8480. req.set_header("Depth", "1");
  8481. req.body = xml;
  8482. auto res = cli_.send(req);
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8485. EXPECT_EQ(xml, res->body);
  8486. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8487. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8488. }
  8489. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8490. Request req;
  8491. req.method = "PROPFIND";
  8492. req.path = "/dav/42";
  8493. auto res = cli_.send(req);
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8496. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8497. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8498. }
  8499. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8500. Request req;
  8501. req.method = "PROPFIND";
  8502. req.path = "/dav-re/123";
  8503. auto res = cli_.send(req);
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8506. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8507. }
  8508. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8509. Request req;
  8510. req.method = "MKCOL";
  8511. req.path = "/dav-mkcol";
  8512. auto res = cli_.send(req);
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::Created_201, res->status);
  8515. }
  8516. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8517. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8518. Request req;
  8519. req.method = "REPORT";
  8520. req.path = "/dav-report";
  8521. req.body = xml;
  8522. auto res = cli_.send(req);
  8523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8524. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8525. EXPECT_EQ(xml, res->body);
  8526. }
  8527. // A content reader route must fire even when the request carries no body,
  8528. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8529. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8530. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8531. Request req;
  8532. req.method = "REPORT";
  8533. req.path = "/dav-report";
  8534. auto res = cli_.send(req);
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8537. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8538. }
  8539. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8540. Request req;
  8541. req.method = "PROPFIND";
  8542. req.path = "/not-dav";
  8543. auto res = cli_.send(req);
  8544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8546. }
  8547. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8548. Request req;
  8549. req.method = "UNLOCK";
  8550. req.path = "/dav/dir";
  8551. cli_.set_keep_alive(true);
  8552. auto res = cli_.send(req);
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8555. EXPECT_EQ("close", res->get_header_value("Connection"));
  8556. EXPECT_FALSE(cli_.is_socket_open());
  8557. }
  8558. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8559. // The mount point serves this path, but only for GET and HEAD.
  8560. auto get_res = cli_.Get("/dir/index.html");
  8561. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8562. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8563. Request req;
  8564. req.method = "PROPFIND";
  8565. req.path = "/dir/index.html";
  8566. auto res = cli_.send(req);
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8569. }
  8570. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8571. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8572. cli_.set_keep_alive(true);
  8573. for (auto i = 0; i < 2; i++) {
  8574. Request req;
  8575. req.method = "PROPFIND";
  8576. req.path = "/dav/dir";
  8577. req.body = xml;
  8578. auto res = cli_.send(req);
  8579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8580. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8581. EXPECT_EQ(xml, res->body);
  8582. EXPECT_TRUE(cli_.is_socket_open());
  8583. }
  8584. // A built-in method must still be served on the same connection.
  8585. cli_.set_keep_alive(false);
  8586. auto res = cli_.Get("/hi");
  8587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8588. EXPECT_EQ(StatusCode::OK_200, res->status);
  8589. EXPECT_EQ("close", res->get_header_value("Connection"));
  8590. }
  8591. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8592. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8593. Request req;
  8594. req.method = "PROPFIND";
  8595. req.path = "/dav/dir";
  8596. req.set_header("Expect", "100-continue");
  8597. req.body = xml;
  8598. auto res = cli_.send(req);
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8601. EXPECT_EQ(xml, res->body);
  8602. }
  8603. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8604. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8605. TEST_F(ServerTest, Gzip) {
  8606. Headers headers;
  8607. headers.emplace("Accept-Encoding", "gzip, deflate");
  8608. auto res = cli_.Get("/compress", headers);
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8611. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8612. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8613. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8614. "7890123456789012345678901234567890",
  8615. res->body);
  8616. EXPECT_EQ(StatusCode::OK_200, res->status);
  8617. }
  8618. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8619. Headers headers;
  8620. headers.emplace("Accept-Encoding", "gzip, deflate");
  8621. auto res = cli_.Get("/compress-with-charset", headers);
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8624. EXPECT_EQ("application/json; charset=utf-8",
  8625. res->get_header_value("Content-Type"));
  8626. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8627. "7890123456789012345678901234567890",
  8628. res->body);
  8629. EXPECT_EQ(StatusCode::OK_200, res->status);
  8630. }
  8631. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8632. Headers headers;
  8633. headers.emplace("Accept-Encoding", "");
  8634. auto res = cli_.Get("/compress", headers);
  8635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8636. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8637. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8638. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8639. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8640. "7890123456789012345678901234567890",
  8641. res->body);
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. }
  8644. TEST_F(ServerTest, GzipWithContentReceiver) {
  8645. Headers headers;
  8646. headers.emplace("Accept-Encoding", "gzip, deflate");
  8647. std::string body;
  8648. auto res =
  8649. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8650. EXPECT_EQ(100U, data_length);
  8651. body.append(data, data_length);
  8652. return true;
  8653. });
  8654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8655. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8657. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8658. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8659. "7890123456789012345678901234567890",
  8660. body);
  8661. EXPECT_EQ(StatusCode::OK_200, res->status);
  8662. }
  8663. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8664. Headers headers;
  8665. headers.emplace("Accept-Encoding", "gzip, deflate");
  8666. cli_.set_decompress(false);
  8667. auto res = cli_.Get("/compress", headers);
  8668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8669. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8670. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8671. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8672. EXPECT_EQ(33U, res->body.size());
  8673. EXPECT_EQ(StatusCode::OK_200, res->status);
  8674. }
  8675. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8676. Headers headers;
  8677. headers.emplace("Accept-Encoding", "");
  8678. std::string body;
  8679. auto res =
  8680. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8681. EXPECT_EQ(100U, data_length);
  8682. body.append(data, data_length);
  8683. return true;
  8684. });
  8685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8686. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8687. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8688. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8689. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8690. "7890123456789012345678901234567890",
  8691. body);
  8692. EXPECT_EQ(StatusCode::OK_200, res->status);
  8693. }
  8694. TEST_F(ServerTest, NoGzip) {
  8695. Headers headers;
  8696. headers.emplace("Accept-Encoding", "gzip, deflate");
  8697. auto res = cli_.Get("/nocompress", headers);
  8698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8699. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8700. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8701. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8702. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8703. "7890123456789012345678901234567890",
  8704. res->body);
  8705. EXPECT_EQ(StatusCode::OK_200, res->status);
  8706. }
  8707. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8708. Headers headers;
  8709. headers.emplace("Accept-Encoding", "gzip, deflate");
  8710. std::string body;
  8711. auto res = cli_.Get("/nocompress", headers,
  8712. [&](const char *data, size_t data_length) {
  8713. EXPECT_EQ(100U, data_length);
  8714. body.append(data, data_length);
  8715. return true;
  8716. });
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8719. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8720. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8721. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8722. "7890123456789012345678901234567890",
  8723. body);
  8724. EXPECT_EQ(StatusCode::OK_200, res->status);
  8725. }
  8726. TEST_F(ServerTest, MultipartFormDataGzip) {
  8727. UploadFormDataItems items = {
  8728. {"key1", "test", "", ""},
  8729. {"key2", "--abcdefg123", "", ""},
  8730. };
  8731. cli_.set_compress(true);
  8732. auto res = cli_.Post("/compress-multipart", items);
  8733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8734. EXPECT_EQ(StatusCode::OK_200, res->status);
  8735. }
  8736. #endif
  8737. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8738. // Static file compression is opt-in, so these run their own server rather than
  8739. // flipping it on for the shared ServerTest fixture, which would silently
  8740. // rewrite what every other static file test is asserting.
  8741. class StaticFileCompressionTest : public ::testing::Test {
  8742. protected:
  8743. void TearDown() override {
  8744. if (t_.joinable()) {
  8745. svr_.stop();
  8746. t_.join();
  8747. }
  8748. }
  8749. int start(const std::function<void(Server &)> &configure = nullptr) {
  8750. // Serves the same tree as a directory of build-time compressed assets
  8751. // would be served: the mount point names the coding the files are already
  8752. // stored in. Registered before "/" so it is the one that matches.
  8753. svr_.set_mount_point("/pre-encoded", "./www",
  8754. {{"Content-Encoding", "gzip"}});
  8755. svr_.set_mount_point("/", "./www");
  8756. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8757. res.set_file_content("./www/dir/index.html", "text/html");
  8758. });
  8759. svr_.Get("/pre-encoded-file-content",
  8760. [](const Request & /*req*/, Response &res) {
  8761. res.set_header("Content-Encoding", "gzip");
  8762. res.set_file_content("./www/dir/index.html", "text/html");
  8763. });
  8764. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8765. res.set_content_provider(
  8766. 6, "text/plain",
  8767. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8768. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8769. return true;
  8770. });
  8771. });
  8772. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8773. res.set_content_provider(
  8774. 1000, "text/plain",
  8775. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8776. if (offset < 100) {
  8777. std::string data(100, 'A');
  8778. sink.write(data.data(), data.size());
  8779. return true;
  8780. }
  8781. std::this_thread::sleep_for(std::chrono::seconds(2));
  8782. std::string data(900, 'B');
  8783. sink.write(data.data(), data.size());
  8784. return true;
  8785. });
  8786. });
  8787. if (configure) { configure(svr_); }
  8788. auto port = svr_.bind_to_any_port(HOST);
  8789. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8790. svr_.wait_until_ready();
  8791. return port;
  8792. }
  8793. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8794. // Every file under ./www except 1MB.txt is smaller than the default
  8795. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8796. // it out of the way.
  8797. static void enable_without_floor(Server &svr) {
  8798. svr.set_static_file_compression(true);
  8799. svr.set_static_file_compression_min_length(0);
  8800. }
  8801. Server svr_;
  8802. std::thread t_;
  8803. };
  8804. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8805. auto port = start();
  8806. Client cli(HOST, port);
  8807. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8809. EXPECT_EQ(StatusCode::OK_200, res->status);
  8810. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8811. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8812. EXPECT_EQ(1048576U, res->body.size());
  8813. }
  8814. TEST_F(StaticFileCompressionTest, MountPoint) {
  8815. auto port = start(enable);
  8816. Client cli(HOST, port);
  8817. cli.set_decompress(false);
  8818. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8820. EXPECT_EQ(StatusCode::OK_200, res->status);
  8821. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8822. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8823. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8824. // The response stays self-delimiting: a length, not a chunked body.
  8825. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8826. EXPECT_EQ(std::to_string(res->body.size()),
  8827. res->get_header_value("Content-Length"));
  8828. EXPECT_LT(res->body.size(), 1048576U);
  8829. EXPECT_FALSE(res->body.empty());
  8830. }
  8831. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8832. auto port = start(enable);
  8833. Client cli(HOST, port);
  8834. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8838. EXPECT_EQ(1048576U, res->body.size());
  8839. }
  8840. TEST_F(StaticFileCompressionTest, FileContent) {
  8841. auto port = start(enable_without_floor);
  8842. Client cli(HOST, port);
  8843. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8845. EXPECT_EQ(StatusCode::OK_200, res->status);
  8846. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8847. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8848. EXPECT_EQ(104U, res->body.size());
  8849. }
  8850. // A handler that serves an already-encoded file names the coding itself. The
  8851. // file-backed path decided its coding from Accept-Encoding and the content
  8852. // type alone, so it compressed the stored bytes a second time and appended a
  8853. // second Content-Encoding field line.
  8854. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8855. auto port = start(enable_without_floor);
  8856. Client cli(HOST, port);
  8857. cli.set_decompress(false);
  8858. auto res = cli.Get("/pre-encoded-file-content",
  8859. Headers{{"Accept-Encoding", "gzip"}});
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ(StatusCode::OK_200, res->status);
  8862. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8863. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8864. // Vary belongs to a coding the server chose, and it chose none here.
  8865. EXPECT_FALSE(res->has_header("Vary"));
  8866. // The file travels exactly as it is stored on disk.
  8867. EXPECT_EQ(104U, res->body.size());
  8868. }
  8869. // The 1MB file clears the default floor, so this one runs the configuration a
  8870. // deployment would actually have.
  8871. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8872. auto port = start(enable);
  8873. Client cli(HOST, port);
  8874. cli.set_decompress(false);
  8875. auto res =
  8876. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8878. EXPECT_EQ(StatusCode::OK_200, res->status);
  8879. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8880. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8881. EXPECT_FALSE(res->has_header("Vary"));
  8882. EXPECT_EQ(1048576U, res->body.size());
  8883. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8884. }
  8885. TEST_F(StaticFileCompressionTest, Head) {
  8886. auto port = start(enable);
  8887. Client cli(HOST, port);
  8888. cli.set_decompress(false);
  8889. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8890. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8891. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_EQ(StatusCode::OK_200, res->status);
  8894. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8895. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8896. // HEAD still reports the size a GET would return.
  8897. EXPECT_EQ(get->get_header_value("Content-Length"),
  8898. res->get_header_value("Content-Length"));
  8899. EXPECT_TRUE(res->body.empty());
  8900. }
  8901. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8902. auto port = start(enable);
  8903. Client cli(HOST, port);
  8904. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8905. {"Accept-Encoding", "gzip"}});
  8906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8908. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8909. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8910. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8911. EXPECT_EQ("cd", res->body);
  8912. }
  8913. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8914. auto port = start(enable);
  8915. Client cli(HOST, port);
  8916. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8918. EXPECT_EQ(StatusCode::OK_200, res->status);
  8919. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8920. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8921. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8922. }
  8923. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8924. auto port = start(enable);
  8925. Client cli(HOST, port);
  8926. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8930. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8931. EXPECT_TRUE(res->body.empty());
  8932. }
  8933. TEST_F(StaticFileCompressionTest, MinLength) {
  8934. auto port = start(enable);
  8935. Client cli(HOST, port);
  8936. // 104 bytes, well under the default floor. Compressing it would add the
  8937. // gzip header and trailer to a body that already fits in one packet.
  8938. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8940. EXPECT_EQ(StatusCode::OK_200, res->status);
  8941. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8942. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8943. }
  8944. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8945. auto port = start([](Server &svr) {
  8946. svr.set_static_file_compression(true);
  8947. svr.set_static_file_compression_min_length(1);
  8948. });
  8949. Client cli(HOST, port);
  8950. cli.set_decompress(false);
  8951. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8954. // A 9-byte file comes back larger than it went in, because gzip's header and
  8955. // trailer outweigh anything deflate can save. That is the end of the range
  8956. // the floor exists to keep out.
  8957. EXPECT_GT(res->body.size(), 9U);
  8958. }
  8959. TEST_F(StaticFileCompressionTest, MaxLength) {
  8960. auto port = start([](Server &svr) {
  8961. svr.set_static_file_compression(true);
  8962. svr.set_static_file_compression_min_length(0);
  8963. svr.set_static_file_compression_max_length(1024);
  8964. });
  8965. Client cli(HOST, port);
  8966. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8967. // defines `small` as a macro on Windows.
  8968. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8969. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8970. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8971. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8972. // Under it: compressed.
  8973. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8974. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8975. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8976. }
  8977. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8978. auto port = start(enable_without_floor);
  8979. Client cli(HOST, port);
  8980. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8981. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8982. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8983. auto identity_etag = identity->get_header_value("ETag");
  8984. ASSERT_FALSE(identity_etag.empty());
  8985. auto gzipped =
  8986. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8987. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8988. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8989. auto gzip_etag = gzipped->get_header_value("ETag");
  8990. ASSERT_FALSE(gzip_etag.empty());
  8991. // Two representations, two validators.
  8992. EXPECT_NE(identity_etag, gzip_etag);
  8993. // Each one revalidates against the request that would produce it...
  8994. auto fresh =
  8995. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8996. {"If-None-Match", gzip_etag}});
  8997. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8998. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8999. auto fresh_identity =
  9000. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9001. {"If-None-Match", identity_etag}});
  9002. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9003. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9004. // ...and not against the other representation.
  9005. auto crossed =
  9006. cli.Get("/dir/index.html",
  9007. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9008. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9009. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9010. }
  9011. // The opt-in covers responses the server reads off disk itself. A caller's own
  9012. // known-length provider keeps its Content-Length and, more importantly, keeps
  9013. // delivering incrementally: routing it through a compressor would hold every
  9014. // write back until zlib's window filled.
  9015. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9016. auto port = start(enable);
  9017. Client cli(HOST, port);
  9018. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9020. EXPECT_EQ(StatusCode::OK_200, res->status);
  9021. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9022. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9023. EXPECT_EQ("aaabbb", res->body);
  9024. }
  9025. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9026. auto port = start(enable);
  9027. Client cli(HOST, port);
  9028. cli.set_read_timeout(1, 0);
  9029. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9030. Headers{{"Accept-Encoding", "gzip"}});
  9031. ASSERT_TRUE(handle.is_valid());
  9032. // The provider writes 100 bytes and then stalls for longer than the read
  9033. // timeout. Those first bytes have to arrive anyway: run the response through
  9034. // a compressor and zlib holds them until its window fills, so the read would
  9035. // come back empty instead.
  9036. char buf[256];
  9037. auto n = handle.read(buf, sizeof(buf));
  9038. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9039. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9040. }
  9041. #endif
  9042. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9043. TEST_F(ServerTest, Brotli) {
  9044. Headers headers;
  9045. headers.emplace("Accept-Encoding", "br");
  9046. auto res = cli_.Get("/compress", headers);
  9047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9048. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9049. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9050. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9051. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9052. "7890123456789012345678901234567890",
  9053. res->body);
  9054. EXPECT_EQ(StatusCode::OK_200, res->status);
  9055. }
  9056. #endif
  9057. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9058. TEST_F(ServerTest, Zstd) {
  9059. Headers headers;
  9060. headers.emplace("Accept-Encoding", "zstd");
  9061. auto res = cli_.Get("/compress", headers);
  9062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9063. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9064. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9065. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9066. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9067. "7890123456789012345678901234567890",
  9068. res->body);
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. }
  9071. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9072. Headers headers;
  9073. headers.emplace("Accept-Encoding", "");
  9074. auto res = cli_.Get("/compress", headers);
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9080. "7890123456789012345678901234567890",
  9081. res->body);
  9082. EXPECT_EQ(StatusCode::OK_200, res->status);
  9083. }
  9084. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9085. Headers headers;
  9086. headers.emplace("Accept-Encoding", "zstd");
  9087. std::string body;
  9088. auto res =
  9089. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9090. EXPECT_EQ(100U, data_length);
  9091. body.append(data, data_length);
  9092. return true;
  9093. });
  9094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9095. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9096. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9097. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9098. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9099. "7890123456789012345678901234567890",
  9100. body);
  9101. EXPECT_EQ(StatusCode::OK_200, res->status);
  9102. }
  9103. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9104. Headers headers;
  9105. headers.emplace("Accept-Encoding", "zstd");
  9106. cli_.set_decompress(false);
  9107. auto res = cli_.Get("/compress", headers);
  9108. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9109. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9110. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9111. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9113. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9115. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9116. EXPECT_EQ(StatusCode::OK_200, res->status);
  9117. ASSERT_EQ(26U, res->body.size());
  9118. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9119. 0);
  9120. }
  9121. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9122. Headers headers;
  9123. headers.emplace("Accept-Encoding", "");
  9124. std::string body;
  9125. auto res =
  9126. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9127. EXPECT_EQ(100U, data_length);
  9128. body.append(data, data_length);
  9129. return true;
  9130. });
  9131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9132. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9134. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9135. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9136. "7890123456789012345678901234567890",
  9137. body);
  9138. EXPECT_EQ(StatusCode::OK_200, res->status);
  9139. }
  9140. TEST_F(ServerTest, NoZstd) {
  9141. Headers headers;
  9142. headers.emplace("Accept-Encoding", "zstd");
  9143. auto res = cli_.Get("/nocompress", headers);
  9144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9145. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9146. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9147. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9148. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9149. "7890123456789012345678901234567890",
  9150. res->body);
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. }
  9153. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9154. Headers headers;
  9155. headers.emplace("Accept-Encoding", "zstd");
  9156. std::string body;
  9157. auto res = cli_.Get("/nocompress", headers,
  9158. [&](const char *data, size_t data_length) {
  9159. EXPECT_EQ(100U, data_length);
  9160. body.append(data, data_length);
  9161. return true;
  9162. });
  9163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9164. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9165. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9166. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9167. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9168. "7890123456789012345678901234567890",
  9169. body);
  9170. EXPECT_EQ(StatusCode::OK_200, res->status);
  9171. }
  9172. // TODO: How to enable zstd ??
  9173. TEST_F(ServerTest, MultipartFormDataZstd) {
  9174. UploadFormDataItems items = {
  9175. {"key1", "test", "", ""},
  9176. {"key2", "--abcdefg123", "", ""},
  9177. };
  9178. Headers headers;
  9179. headers.emplace("Accept-Encoding", "zstd");
  9180. cli_.set_compress(true);
  9181. auto res = cli_.Post("/compress-multipart", headers, items);
  9182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9183. EXPECT_EQ(StatusCode::OK_200, res->status);
  9184. }
  9185. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9186. Headers headers;
  9187. headers.emplace("Accept-Encoding", "zstd");
  9188. cli_.set_compress(true);
  9189. auto res = cli_.Put(
  9190. "/put", headers, 3,
  9191. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9192. sink.os << "PUT";
  9193. return true;
  9194. },
  9195. "text/plain");
  9196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9197. EXPECT_EQ(StatusCode::OK_200, res->status);
  9198. EXPECT_EQ("PUT", res->body);
  9199. }
  9200. // Pre-compression logging tests
  9201. TEST_F(ServerTest, PreCompressionLogging) {
  9202. // Test data for compression (matches the actual /compress endpoint content)
  9203. const std::string test_content =
  9204. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9205. "3456789012345678901234567890";
  9206. // Variables to capture logging data
  9207. std::string pre_compression_body;
  9208. std::string pre_compression_content_type;
  9209. std::string pre_compression_content_encoding;
  9210. std::string post_compression_body;
  9211. std::string post_compression_content_type;
  9212. std::string post_compression_content_encoding;
  9213. // Set up pre-compression logger
  9214. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9215. const Response &res) {
  9216. pre_compression_body = res.body;
  9217. pre_compression_content_type = res.get_header_value("Content-Type");
  9218. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9219. });
  9220. // Set up post-compression logger
  9221. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9222. post_compression_body = res.body;
  9223. post_compression_content_type = res.get_header_value("Content-Type");
  9224. post_compression_content_encoding =
  9225. res.get_header_value("Content-Encoding");
  9226. });
  9227. // Test with gzip compression
  9228. Headers headers;
  9229. headers.emplace("Accept-Encoding", "gzip");
  9230. auto res = cli_.Get("/compress", headers);
  9231. // Verify response was compressed
  9232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9233. EXPECT_EQ(StatusCode::OK_200, res->status);
  9234. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9235. // Verify pre-compression logger captured uncompressed content
  9236. EXPECT_EQ(test_content, pre_compression_body);
  9237. EXPECT_EQ("text/plain", pre_compression_content_type);
  9238. EXPECT_TRUE(pre_compression_content_encoding
  9239. .empty()); // No encoding header before compression
  9240. // Verify post-compression logger captured compressed content
  9241. EXPECT_NE(test_content,
  9242. post_compression_body); // Should be different after compression
  9243. EXPECT_EQ("text/plain", post_compression_content_type);
  9244. EXPECT_EQ("gzip", post_compression_content_encoding);
  9245. // Verify compressed content is smaller
  9246. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9247. }
  9248. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9249. const std::string test_content =
  9250. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9251. "3456789012345678901234567890";
  9252. std::string pre_compression_body;
  9253. std::string post_compression_body;
  9254. svr_.set_pre_compression_logger(
  9255. [&](const Request & /*req*/, const Response &res) {
  9256. pre_compression_body = res.body;
  9257. });
  9258. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9259. post_compression_body = res.body;
  9260. });
  9261. Headers headers;
  9262. headers.emplace("Accept-Encoding", "br");
  9263. auto res = cli_.Get("/compress", headers);
  9264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9265. EXPECT_EQ(StatusCode::OK_200, res->status);
  9266. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9267. // Verify pre-compression content is uncompressed
  9268. EXPECT_EQ(test_content, pre_compression_body);
  9269. // Verify post-compression content is compressed
  9270. EXPECT_NE(test_content, post_compression_body);
  9271. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9272. }
  9273. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9274. const std::string test_content =
  9275. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9276. "3456789012345678901234567890";
  9277. std::string pre_compression_body;
  9278. std::string post_compression_body;
  9279. svr_.set_pre_compression_logger(
  9280. [&](const Request & /*req*/, const Response &res) {
  9281. pre_compression_body = res.body;
  9282. });
  9283. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9284. post_compression_body = res.body;
  9285. });
  9286. // Request without compression (use /nocompress endpoint)
  9287. Headers headers;
  9288. auto res = cli_.Get("/nocompress", headers);
  9289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9290. EXPECT_EQ(StatusCode::OK_200, res->status);
  9291. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9292. // Pre-compression logger should not be called when no compression is applied
  9293. EXPECT_TRUE(
  9294. pre_compression_body.empty()); // Pre-compression logger not called
  9295. EXPECT_EQ(
  9296. test_content,
  9297. post_compression_body); // Post-compression logger captures final content
  9298. }
  9299. TEST_F(ServerTest, LoggerSeesContentLength) {
  9300. size_t logged_content_length = 0;
  9301. std::string logged_content_length_header;
  9302. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9303. logged_content_length = res.content_length_;
  9304. logged_content_length_header = res.get_header_value("Content-Length");
  9305. });
  9306. auto res = cli_.Get("/nocompress");
  9307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9308. EXPECT_EQ(StatusCode::OK_200, res->status);
  9309. EXPECT_EQ(res->body.size(), logged_content_length);
  9310. EXPECT_EQ(std::to_string(logged_content_length),
  9311. logged_content_length_header);
  9312. }
  9313. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9314. const std::string test_content =
  9315. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9316. "3456789012345678901234567890";
  9317. std::string pre_compression_body;
  9318. bool pre_logger_called = false;
  9319. // Set only pre-compression logger
  9320. svr_.set_pre_compression_logger(
  9321. [&](const Request & /*req*/, const Response &res) {
  9322. pre_compression_body = res.body;
  9323. pre_logger_called = true;
  9324. });
  9325. Headers headers;
  9326. headers.emplace("Accept-Encoding", "gzip");
  9327. auto res = cli_.Get("/compress", headers);
  9328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9331. // Verify pre-compression logger was called
  9332. EXPECT_TRUE(pre_logger_called);
  9333. EXPECT_EQ(test_content, pre_compression_body);
  9334. }
  9335. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9336. {
  9337. // Test with Expect: 100-continue header - success case
  9338. // Server returns 100 Continue, client sends body, server returns 200 OK
  9339. Request req;
  9340. req.method = "POST";
  9341. req.path = "/post-large";
  9342. req.set_header("Expect", "100-continue");
  9343. req.body = LARGE_DATA;
  9344. Response res;
  9345. auto error = Error::Success;
  9346. cli_.set_keep_alive(true);
  9347. auto ret = cli_.send(req, res, error);
  9348. EXPECT_TRUE(ret);
  9349. EXPECT_EQ(StatusCode::OK_200, res.status);
  9350. EXPECT_EQ(LARGE_DATA, res.body);
  9351. }
  9352. {
  9353. // Test with Expect: 100-continue header - error case
  9354. // Client should not send the body when server returns an error
  9355. Request req;
  9356. req.method = "POST";
  9357. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9358. req.set_header("Expect", "100-continue");
  9359. req.body = LARGE_DATA;
  9360. Response res;
  9361. auto error = Error::Success;
  9362. auto start = std::chrono::high_resolution_clock::now();
  9363. cli_.set_keep_alive(true);
  9364. auto ret = cli_.send(req, res, error);
  9365. auto end = std::chrono::high_resolution_clock::now();
  9366. auto elapsed =
  9367. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9368. .count();
  9369. // With Expect: 100-continue, request completes successfully but with error
  9370. EXPECT_TRUE(ret);
  9371. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9372. EXPECT_EQ("close", res.get_header_value("Connection"));
  9373. EXPECT_FALSE(cli_.is_socket_open());
  9374. EXPECT_LE(elapsed, 2000);
  9375. }
  9376. {
  9377. // Send an extra GET request to ensure error recovery without hanging
  9378. Request req;
  9379. req.method = "GET";
  9380. req.path = "/hi";
  9381. auto start = std::chrono::high_resolution_clock::now();
  9382. auto res = cli_.send(req);
  9383. auto end = std::chrono::high_resolution_clock::now();
  9384. auto elapsed =
  9385. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9386. .count();
  9387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9388. EXPECT_EQ(StatusCode::OK_200, res->status);
  9389. EXPECT_EQ("Hello World!", res->body);
  9390. EXPECT_LE(elapsed, 500);
  9391. }
  9392. }
  9393. TEST(ZstdDecompressor, ChunkedDecompression) {
  9394. std::string data;
  9395. for (size_t i = 0; i < 32 * 1024; ++i) {
  9396. data.push_back(static_cast<char>('a' + i % 26));
  9397. }
  9398. std::string compressed_data;
  9399. {
  9400. httplib::detail::zstd_compressor compressor;
  9401. bool result = compressor.compress(
  9402. data.data(), data.size(),
  9403. /*last=*/true,
  9404. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9405. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9406. compressed_data_size);
  9407. return true;
  9408. });
  9409. ASSERT_TRUE(result);
  9410. }
  9411. std::string decompressed_data;
  9412. {
  9413. httplib::detail::zstd_decompressor decompressor;
  9414. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9415. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9416. size_t chunk_size = 130;
  9417. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9418. chunk_begin += chunk_size) {
  9419. size_t current_chunk_size =
  9420. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9421. bool result = decompressor.decompress(
  9422. compressed_data.data() + chunk_begin, current_chunk_size,
  9423. [&](const char *decompressed_data_chunk,
  9424. size_t decompressed_data_chunk_size) {
  9425. decompressed_data.insert(decompressed_data.size(),
  9426. decompressed_data_chunk,
  9427. decompressed_data_chunk_size);
  9428. return true;
  9429. });
  9430. ASSERT_TRUE(result);
  9431. }
  9432. }
  9433. ASSERT_EQ(data, decompressed_data);
  9434. }
  9435. TEST(ZstdDecompressor, Decompress) {
  9436. std::string original_text = "Compressed with ZSTD";
  9437. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9438. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9439. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9440. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9441. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9442. std::string decompressed_data;
  9443. {
  9444. httplib::detail::zstd_decompressor decompressor;
  9445. bool result = decompressor.decompress(
  9446. compressed_data.data(), compressed_data.size(),
  9447. [&](const char *decompressed_data_chunk,
  9448. size_t decompressed_data_chunk_size) {
  9449. decompressed_data.insert(decompressed_data.size(),
  9450. decompressed_data_chunk,
  9451. decompressed_data_chunk_size);
  9452. return true;
  9453. });
  9454. ASSERT_TRUE(result);
  9455. }
  9456. ASSERT_EQ(original_text, decompressed_data);
  9457. }
  9458. #endif
  9459. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9460. // separate chunks so that the server sees each part in its own read(). Used to
  9461. // place a read boundary at a specific offset of a request body.
  9462. static bool send_request_in_parts(time_t read_timeout_sec,
  9463. const std::vector<std::string> &parts,
  9464. std::string *resp = nullptr,
  9465. int port = PORT) {
  9466. auto error = Error::Success;
  9467. auto client_sock = detail::create_client_socket(
  9468. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9469. /*connection_timeout_sec=*/5, 0,
  9470. /*read_timeout_sec=*/5, 0,
  9471. /*write_timeout_sec=*/5, 0, std::string(), error);
  9472. if (client_sock == INVALID_SOCKET) { return false; }
  9473. auto ret = detail::process_client_socket(
  9474. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9475. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9476. for (size_t i = 0; i < parts.size(); i++) {
  9477. const auto &part = parts[i];
  9478. if (part.size() !=
  9479. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9480. return false;
  9481. }
  9482. if (i + 1 < parts.size()) {
  9483. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9484. }
  9485. }
  9486. char buf[512];
  9487. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9488. while (line_reader.getline()) {
  9489. if (resp) { *resp += line_reader.ptr(); }
  9490. }
  9491. return true;
  9492. });
  9493. detail::close_socket(client_sock);
  9494. return ret;
  9495. }
  9496. // Sends a raw request to a server listening at HOST:PORT.
  9497. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9498. std::string *resp = nullptr, int port = PORT) {
  9499. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9500. }
  9501. #ifdef CPPHTTPLIB_SSL_ENABLED
  9502. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9504. ASSERT_TRUE(svr.is_valid());
  9505. svr.set_read_timeout(1, 0);
  9506. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9507. auto se = detail::scope_exit([&] {
  9508. svr.stop();
  9509. t.join();
  9510. ASSERT_FALSE(svr.is_running());
  9511. });
  9512. svr.wait_until_ready();
  9513. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9514. // keeps each wait well within the read timeout. The server gives up a
  9515. // second in, so the bytes sent after that fail.
  9516. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9517. parts.resize(26, std::string(1, '\0'));
  9518. EXPECT_FALSE(send_request_in_parts(5, parts));
  9519. }
  9520. #endif
  9521. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9522. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9523. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9524. const std::vector<std::string> &parts,
  9525. std::string *resp = nullptr,
  9526. int port = PORT) {
  9527. auto error = Error::Success;
  9528. auto sock = detail::create_client_socket(
  9529. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9530. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9531. /*write_timeout_sec=*/5, 0, std::string(), error);
  9532. if (sock == INVALID_SOCKET) { return false; }
  9533. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9534. auto ctx = SSL_CTX_new(TLS_client_method());
  9535. auto ssl = SSL_new(ctx);
  9536. auto ssl_se = detail::scope_exit([&] {
  9537. SSL_free(ssl);
  9538. SSL_CTX_free(ctx);
  9539. });
  9540. SSL_set_fd(ssl, static_cast<int>(sock));
  9541. if (SSL_connect(ssl) != 1) { return false; }
  9542. for (size_t i = 0; i < parts.size(); i++) {
  9543. const auto &part = parts[i];
  9544. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9545. static_cast<int>(part.size())) {
  9546. return false;
  9547. }
  9548. if (i + 1 < parts.size()) {
  9549. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9550. }
  9551. }
  9552. char buf[512];
  9553. int n;
  9554. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9555. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9556. }
  9557. return true;
  9558. }
  9559. #endif
  9560. // The request line, then a header value a byte at a time.
  9561. static std::vector<std::string> slow_request_head_parts() {
  9562. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9563. parts.resize(26, "a");
  9564. parts.emplace_back("\r\n\r\n");
  9565. return parts;
  9566. }
  9567. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9568. // within the one-second read timeout. The server gives up a second in, before
  9569. // the head is complete.
  9570. static void
  9571. expect_slow_request_head_dropped(Server &svr,
  9572. const std::function<std::string()> &send) {
  9573. std::atomic<bool> handled(false);
  9574. svr.Get("/", [&](const Request &, Response &res) {
  9575. handled = true;
  9576. res.set_content("ok", "text/plain");
  9577. });
  9578. svr.set_read_timeout(1, 0);
  9579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9580. auto se = detail::scope_exit([&] {
  9581. svr.stop();
  9582. t.join();
  9583. ASSERT_FALSE(svr.is_running());
  9584. });
  9585. svr.wait_until_ready();
  9586. auto resp = send();
  9587. EXPECT_FALSE(handled);
  9588. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9589. }
  9590. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9591. Server svr;
  9592. expect_slow_request_head_dropped(svr, [] {
  9593. std::string resp;
  9594. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9595. return resp;
  9596. });
  9597. }
  9598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9599. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9601. ASSERT_TRUE(svr.is_valid());
  9602. expect_slow_request_head_dropped(svr, [] {
  9603. std::string resp;
  9604. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9605. return resp;
  9606. });
  9607. }
  9608. #endif
  9609. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9610. Server svr;
  9611. std::string header_value;
  9612. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9613. header_value = req.get_header_value("foo");
  9614. res.set_content("ok", "text/plain");
  9615. });
  9616. thread t = thread([&] { svr.listen(HOST, PORT); });
  9617. auto se = detail::scope_exit([&] {
  9618. svr.stop();
  9619. t.join();
  9620. ASSERT_FALSE(svr.is_running());
  9621. });
  9622. svr.wait_until_ready();
  9623. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9624. // like characters are not treated the same - use vertical tab and escape.
  9625. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9626. "foo: \t \v bar \x1B\t \r\n"
  9627. "Connection: close\r\n"
  9628. "\r\n";
  9629. std::string res;
  9630. ASSERT_TRUE(send_request(5, req, &res));
  9631. EXPECT_EQ(header_value, "");
  9632. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9633. }
  9634. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9635. Server svr;
  9636. std::string received;
  9637. svr.Get("/order", [&](const Request &req, Response &res) {
  9638. received = entries_to_string(req.headers);
  9639. res.set_content("ok", "text/plain");
  9640. });
  9641. auto port = svr.bind_to_any_port(HOST);
  9642. thread t = thread([&] { svr.listen_after_bind(); });
  9643. auto se = detail::scope_exit([&] {
  9644. svr.stop();
  9645. t.join();
  9646. ASSERT_FALSE(svr.is_running());
  9647. });
  9648. svr.wait_until_ready();
  9649. const std::string req = "GET /order HTTP/1.1\r\n"
  9650. "Host: localhost\r\n"
  9651. "X-First: 1\r\n"
  9652. "X-Dup: a\r\n"
  9653. "X-Second: 2\r\n"
  9654. "X-Dup: b\r\n"
  9655. "Connection: close\r\n"
  9656. "\r\n";
  9657. std::string res;
  9658. ASSERT_TRUE(send_request(5, req, &res, port));
  9659. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9660. EXPECT_EQ(
  9661. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9662. received);
  9663. }
  9664. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9665. Server svr;
  9666. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9667. res.set_header("Set-Cookie", "first=1");
  9668. res.set_header("X-Between", "y");
  9669. res.set_header("Set-Cookie", "second=2");
  9670. res.set_content("ok", "text/plain");
  9671. });
  9672. auto port = svr.bind_to_any_port(HOST);
  9673. thread t = thread([&] { svr.listen_after_bind(); });
  9674. auto se = detail::scope_exit([&] {
  9675. svr.stop();
  9676. t.join();
  9677. ASSERT_FALSE(svr.is_running());
  9678. });
  9679. svr.wait_until_ready();
  9680. Client cli(HOST, port);
  9681. auto res = cli.Get("/cookies");
  9682. ASSERT_TRUE(res);
  9683. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9684. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9685. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9686. }
  9687. // A stream may send a byte at a time with a small extension on each chunk,
  9688. // however long it runs
  9689. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9690. Server svr;
  9691. svr.Post("/count", [](const Request &req, Response &res) {
  9692. res.set_content(std::to_string(req.body.size()), "text/plain");
  9693. });
  9694. auto port = svr.bind_to_any_port(HOST);
  9695. ASSERT_LT(0, port);
  9696. thread t = thread([&] { svr.listen_after_bind(); });
  9697. auto se = detail::scope_exit([&] {
  9698. svr.stop();
  9699. t.join();
  9700. ASSERT_FALSE(svr.is_running());
  9701. });
  9702. svr.wait_until_ready();
  9703. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9704. "\r\nTransfer-Encoding: chunked\r\n"
  9705. "Connection: close\r\n\r\n";
  9706. for (auto i = 0; i < 4096; i++) {
  9707. req += "1;a=b\r\nx\r\n";
  9708. }
  9709. req += "0\r\n\r\n";
  9710. std::string res;
  9711. ASSERT_TRUE(send_request(5, req, &res, port));
  9712. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9713. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9714. }
  9715. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9716. Server svr;
  9717. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9718. auto i = new int(0);
  9719. res.set_header("Trailer", "X-Safe, X-Reflected");
  9720. res.set_chunked_content_provider(
  9721. "text/plain",
  9722. [i](size_t /*offset*/, DataSink &sink) {
  9723. if (*i == 0) {
  9724. sink.os << "body";
  9725. } else {
  9726. Headers trailer;
  9727. // A valid trailer that must survive.
  9728. trailer.emplace("X-Safe", "safe");
  9729. // Attacker-controlled value carrying CR/LF (response splitting).
  9730. trailer.emplace("X-Reflected",
  9731. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9732. // Attacker-controlled name carrying CR/LF.
  9733. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9734. sink.done_with_trailer(trailer);
  9735. }
  9736. (*i)++;
  9737. return true;
  9738. },
  9739. [i](bool /*success*/) { delete i; });
  9740. });
  9741. thread t = thread([&] { svr.listen(HOST, PORT); });
  9742. auto se = detail::scope_exit([&] {
  9743. svr.stop();
  9744. t.join();
  9745. ASSERT_FALSE(svr.is_running());
  9746. });
  9747. svr.wait_until_ready();
  9748. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9749. "Host: " + HOST +
  9750. "\r\n"
  9751. "Connection: close\r\n"
  9752. "\r\n";
  9753. std::string res;
  9754. ASSERT_TRUE(send_request(5, req, &res));
  9755. // The injected fields must not appear anywhere in the raw response.
  9756. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9757. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9758. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9759. // Invalid trailers are dropped entirely, matching set_header().
  9760. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9761. // The valid trailer still passes through.
  9762. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9763. }
  9764. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9765. // A custom header writer gets only the fields the default one writes
  9766. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9767. std::string s;
  9768. for (const auto &h : hdrs) {
  9769. s += h.first + ": " + h.second + "\r\n";
  9770. }
  9771. s += "\r\n";
  9772. return strm.write(s.data(), s.size());
  9773. };
  9774. for (auto custom_writer : {false, true}) {
  9775. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9776. Server svr;
  9777. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9778. svr.set_post_routing_handler([](const Request &, Response &res) {
  9779. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9780. });
  9781. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9782. // res.headers is a public field an application can populate directly,
  9783. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9784. // A valid header that must survive.
  9785. res.headers.emplace("X-Safe", "safe");
  9786. // Attacker-controlled value carrying CR/LF (response splitting).
  9787. res.headers.emplace("X-Reflected",
  9788. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9789. // Attacker-controlled name carrying CR/LF.
  9790. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9791. res.set_content("body", "text/plain");
  9792. });
  9793. thread t = thread([&] { svr.listen(HOST, PORT); });
  9794. auto se = detail::scope_exit([&] {
  9795. svr.stop();
  9796. t.join();
  9797. ASSERT_FALSE(svr.is_running());
  9798. });
  9799. svr.wait_until_ready();
  9800. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9801. "Host: " + HOST +
  9802. "\r\n"
  9803. "Connection: close\r\n"
  9804. "\r\n";
  9805. std::string res;
  9806. ASSERT_TRUE(send_request(5, req, &res));
  9807. // The injected fields must not appear anywhere in the raw response.
  9808. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9809. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9810. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9811. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9812. // Invalid headers are dropped entirely, matching set_header().
  9813. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9814. // The valid header still passes through.
  9815. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9816. }
  9817. }
  9818. // Forward declaration: in split builds split.py strips `inline` and moves the
  9819. // definition into httplib.cc, so detail::write_request_line is not visible from
  9820. // the public httplib.h. Re-declaring it here lets the tests link against the
  9821. // symbol in both header-only and split builds.
  9822. namespace httplib {
  9823. namespace detail {
  9824. ssize_t write_request_line(Stream &strm, const std::string &method,
  9825. const std::string &path);
  9826. } // namespace detail
  9827. } // namespace httplib
  9828. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9829. // A well-formed target is written verbatim.
  9830. {
  9831. detail::BufferStream strm;
  9832. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9833. EXPECT_GT(n, 0);
  9834. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9835. }
  9836. // A target carrying CR/LF, SP or other control octets must be rejected
  9837. // before anything reaches the wire, otherwise it splits the request line and
  9838. // injects a header or a whole request.
  9839. const std::string evil_targets[] = {
  9840. "/a\r\nInjected: pwned",
  9841. "/a\rInjected",
  9842. "/a\nInjected",
  9843. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9844. "/a b",
  9845. "/a\tb",
  9846. "/a\x7f",
  9847. };
  9848. for (const auto &evil : evil_targets) {
  9849. detail::BufferStream strm;
  9850. auto n = detail::write_request_line(strm, "GET", evil);
  9851. EXPECT_LT(n, 0);
  9852. EXPECT_TRUE(strm.get_buffer().empty());
  9853. }
  9854. }
  9855. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9856. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9857. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9858. // target reaches write_request. The client must fail cleanly with
  9859. // Error::Write instead of putting a request-line-less, header-injecting
  9860. // request on the wire.
  9861. Server svr;
  9862. svr.Get("/a", [](const Request &, Response &res) {
  9863. res.set_content("ok", "text/plain");
  9864. });
  9865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9866. auto se = detail::scope_exit([&] {
  9867. svr.stop();
  9868. thread.join();
  9869. ASSERT_FALSE(svr.is_running());
  9870. });
  9871. svr.wait_until_ready();
  9872. {
  9873. Client cli(HOST, PORT);
  9874. cli.set_path_encode(false);
  9875. // The request is rejected before anything is written, so the connection
  9876. // stays silent and the subsequent response read would otherwise block for
  9877. // the full default read timeout. Shorten it -- the assertion is on the
  9878. // error, not the timeout.
  9879. cli.set_read_timeout(1, 0);
  9880. auto res = cli.Get("/a\r\nInjected: pwned");
  9881. EXPECT_FALSE(res);
  9882. EXPECT_EQ(Error::Write, res.error());
  9883. }
  9884. }
  9885. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9886. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9887. // including extension methods.
  9888. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9889. for (const auto &method : good_methods) {
  9890. detail::BufferStream strm;
  9891. auto n = detail::write_request_line(strm, method, "/");
  9892. EXPECT_GT(n, 0);
  9893. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9894. }
  9895. // A method carrying CR/LF would split the request line and smuggle a whole
  9896. // request ahead of the real one. A space or an empty method corrupts the
  9897. // request line. All must be rejected before anything reaches the wire.
  9898. const std::string evil_methods[] = {
  9899. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9900. "GET\r\nInjected: pwned",
  9901. "GET\r",
  9902. "GET\n",
  9903. "GE T",
  9904. "",
  9905. };
  9906. for (const auto &evil : evil_methods) {
  9907. detail::BufferStream strm;
  9908. auto n = detail::write_request_line(strm, evil, "/");
  9909. EXPECT_LT(n, 0);
  9910. EXPECT_TRUE(strm.get_buffer().empty());
  9911. }
  9912. }
  9913. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9914. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9915. // through Client::send must fail with Error::Write and no request, neither
  9916. // the smuggled one nor the real one, may reach the server.
  9917. Server svr;
  9918. std::atomic<int> request_count(0);
  9919. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9920. request_count++;
  9921. res.status = StatusCode::OK_200;
  9922. return Server::HandlerResponse::Handled;
  9923. });
  9924. auto port = svr.bind_to_any_port(HOST);
  9925. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9926. auto se = detail::scope_exit([&] {
  9927. svr.stop();
  9928. thread.join();
  9929. ASSERT_FALSE(svr.is_running());
  9930. });
  9931. svr.wait_until_ready();
  9932. {
  9933. Client cli(HOST, port);
  9934. const std::string evil_methods[] = {
  9935. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9936. "GE T",
  9937. "",
  9938. };
  9939. for (const auto &evil : evil_methods) {
  9940. Request req;
  9941. req.method = evil;
  9942. req.path = "/";
  9943. auto res = cli.send(req);
  9944. EXPECT_FALSE(res);
  9945. EXPECT_EQ(Error::Write, res.error());
  9946. }
  9947. auto handle =
  9948. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9949. EXPECT_FALSE(handle.is_valid());
  9950. EXPECT_EQ(Error::Write, handle.error);
  9951. // A valid request on the same client still goes through.
  9952. auto res = cli.Get("/");
  9953. ASSERT_TRUE(res);
  9954. EXPECT_EQ(StatusCode::OK_200, res->status);
  9955. }
  9956. EXPECT_EQ(1, request_count.load());
  9957. }
  9958. // Sends a raw request and verifies that there isn't a crash or exception.
  9959. static void test_raw_request(const std::string &req,
  9960. std::string *out = nullptr) {
  9961. Server svr;
  9962. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9963. res.set_content("ok", "text/plain");
  9964. });
  9965. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9966. res.set_content("ok", "text/plain");
  9967. });
  9968. svr.Get("/header_field_value_check",
  9969. [&](const Request & /*req*/, Response &res) {
  9970. res.set_content("ok", "text/plain");
  9971. });
  9972. svr.CustomRoute("PROPFIND", "/dav",
  9973. [&](const Request & /*req*/, Response &res) {
  9974. res.status = StatusCode::MultiStatus_207;
  9975. });
  9976. // Server read timeout must be longer than the client read timeout for the
  9977. // bug to reproduce, probably to force the server to process a request
  9978. // without a trailing blank line.
  9979. const time_t client_read_timeout_sec = 1;
  9980. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9981. bool listen_thread_ok = false;
  9982. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9983. auto se = detail::scope_exit([&] {
  9984. svr.stop();
  9985. t.join();
  9986. ASSERT_FALSE(svr.is_running());
  9987. EXPECT_TRUE(listen_thread_ok);
  9988. });
  9989. svr.wait_until_ready();
  9990. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9991. }
  9992. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9993. // A certain header line causes an exception if the header property is parsed
  9994. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9995. test_raw_request(
  9996. "GET /hi HTTP/1.1\r\n"
  9997. " : "
  9998. " "
  9999. " ");
  10000. }
  10001. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10002. // A certain header line causes an exception if the header property *name* is
  10003. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10004. // greedy matcher and requires backtracking when there are a lot of ":"
  10005. // characters.
  10006. // This occurs with libc++ but not libstdc++.
  10007. test_raw_request(
  10008. "GET /hi HTTP/1.1\r\n"
  10009. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10010. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10011. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10012. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10013. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10014. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10015. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10016. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10017. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10018. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10019. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10020. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10021. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10022. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10023. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10024. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10025. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10026. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10027. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10028. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10029. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10030. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10031. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10032. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10033. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10034. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10035. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10036. "&&&%%%");
  10037. }
  10038. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10039. // Make sure this doesn't crash the server.
  10040. // In a previous version of the header line regex, the "\r" rendered the line
  10041. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10042. // a new position where the leading white space ended and the field value
  10043. // began.
  10044. // The crash occurs with libc++ but not libstdc++.
  10045. test_raw_request("GET /hi HTTP/1.1\r\n"
  10046. "a:" +
  10047. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10048. "\r\n"
  10049. "\r\n");
  10050. }
  10051. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10052. const char *rejected[] = {
  10053. // RFC 9112 §3: one SP between the parts, and nothing else
  10054. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10055. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10056. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10057. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10058. // A request-target has no fragment
  10059. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10060. // An HTTP/1.1 request needs a Host
  10061. "GET /hi HTTP/1.1\r\n\r\n",
  10062. };
  10063. for (auto request : rejected) {
  10064. std::string out;
  10065. test_raw_request(request, &out);
  10066. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10067. }
  10068. std::string out;
  10069. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10070. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10071. }
  10072. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10073. // RFC 9112 §6.1
  10074. const char *requests[] = {
  10075. "PUT /put_hi HTTP/1.1\r\n"
  10076. "Host: localhost\r\n"
  10077. "Content-Length: 0\r\n"
  10078. "Transfer-Encoding: chunked\r\n"
  10079. "\r\n"
  10080. "0\r\n\r\n",
  10081. "PUT /put_hi HTTP/1.0\r\n"
  10082. "Connection: keep-alive\r\n"
  10083. "Transfer-Encoding: chunked\r\n"
  10084. "\r\n"
  10085. "0\r\n\r\n",
  10086. };
  10087. for (auto request : requests) {
  10088. std::string out;
  10089. test_raw_request(request, &out);
  10090. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10091. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10092. }
  10093. }
  10094. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10095. std::string out;
  10096. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10097. "Content-Type: text/plain\r\n"
  10098. "Transfer-Encoding: chunked\r\n"
  10099. "\r\n"
  10100. "nothex\r\n",
  10101. &out);
  10102. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10103. }
  10104. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10105. std::string out;
  10106. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10107. "Content-Type: text/plain\r\n"
  10108. "Transfer-Encoding: chunked\r\n"
  10109. "\r\n"
  10110. "3\r\n"
  10111. "xyz\r\n"
  10112. "NaN\r\n",
  10113. &out);
  10114. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10115. }
  10116. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10117. std::string out;
  10118. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10119. "Content-Type: text/plain\r\n"
  10120. "Transfer-Encoding: chunked\r\n"
  10121. "\r\n"
  10122. // Length is too large for 64 bits.
  10123. "1ffffffffffffffff\r\n"
  10124. "xyz\r\n",
  10125. &out);
  10126. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10127. }
  10128. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10129. test_raw_request("GET /hi HTTP/1.1\r\n"
  10130. "Content-Type: text/plain\r\n\r");
  10131. }
  10132. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10133. std::string out;
  10134. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10135. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10136. }
  10137. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10138. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10139. std::string out;
  10140. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10141. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10142. }
  10143. }
  10144. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10145. std::string out;
  10146. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10147. "Host: localhost\r\n"
  10148. "Connection: close\r\n\r\n",
  10149. &out);
  10150. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10151. }
  10152. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10153. Server svr;
  10154. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10155. EXPECT_TRUE(!req.remote_addr.empty());
  10156. });
  10157. thread t = thread([&] { svr.listen(HOST, PORT); });
  10158. auto se = detail::scope_exit([&] {
  10159. svr.stop();
  10160. t.join();
  10161. ASSERT_FALSE(svr.is_running());
  10162. });
  10163. svr.wait_until_ready();
  10164. // Send an invalid request line to trigger Bad Request
  10165. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10166. std::string out;
  10167. ASSERT_TRUE(send_request(5, bad_req, &out));
  10168. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10169. }
  10170. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10171. // answered right away rather than blocking on a read that waits for EOF.
  10172. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10173. std::string out;
  10174. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10175. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10176. }
  10177. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10178. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10179. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10180. for (const auto *method : methods) {
  10181. Server svr;
  10182. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10183. EXPECT_FALSE(svr.is_valid()) << method;
  10184. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10185. }
  10186. }
  10187. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10188. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10189. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10190. for (const auto *method : methods) {
  10191. Server svr;
  10192. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10193. EXPECT_FALSE(svr.is_valid()) << method;
  10194. }
  10195. }
  10196. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10197. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10198. "COPY", "MOVE", "LOCK",
  10199. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10200. Server svr;
  10201. for (const auto *method : methods) {
  10202. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10203. }
  10204. EXPECT_TRUE(svr.is_valid());
  10205. }
  10206. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10207. Server svr;
  10208. svr.CustomRoute("POST", "/x",
  10209. [](const Request &, Response &, const ContentReader &) {});
  10210. EXPECT_FALSE(svr.is_valid());
  10211. }
  10212. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10213. Server svr;
  10214. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10215. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10216. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10217. EXPECT_FALSE(svr.is_valid());
  10218. }
  10219. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10220. Server svr;
  10221. auto captured = Error::Success;
  10222. svr.set_error_logger(
  10223. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10224. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10225. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10226. }
  10227. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10228. std::string out;
  10229. std::string request(
  10230. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10231. test_raw_request(request, &out);
  10232. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10233. }
  10234. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10235. std::string out;
  10236. std::string request(
  10237. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10238. test_raw_request(request, &out);
  10239. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10240. }
  10241. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10242. std::string out;
  10243. std::string request(
  10244. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10245. test_raw_request(request, &out);
  10246. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10247. }
  10248. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10249. std::string out;
  10250. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10251. "Host: localhost\r\n"
  10252. "Test: \r\n\r\n",
  10253. &out);
  10254. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10255. }
  10256. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10257. Server svr;
  10258. std::string x_custom;
  10259. std::string cookie;
  10260. std::string xff;
  10261. std::string x_unicode;
  10262. std::string x_iis;
  10263. svr.Get("/check", [&](const Request &req, Response &res) {
  10264. x_custom = req.get_header_value("X-Custom");
  10265. cookie = req.get_header_value("Cookie");
  10266. xff = req.get_header_value("X-Forwarded-For");
  10267. x_unicode = req.get_header_value("X-Unicode");
  10268. x_iis = req.get_header_value("X-IIS");
  10269. res.set_content("ok", "text/plain");
  10270. });
  10271. thread t = thread([&] { svr.listen(HOST, PORT); });
  10272. auto se = detail::scope_exit([&] {
  10273. svr.stop();
  10274. t.join();
  10275. ASSERT_FALSE(svr.is_running());
  10276. });
  10277. svr.wait_until_ready();
  10278. const std::string req = "GET /check HTTP/1.1\r\n"
  10279. "Host: localhost\r\n"
  10280. "X-Custom: a%0D%0AInjected: b\r\n"
  10281. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10282. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10283. "X-Unicode: %E3%81%82\r\n"
  10284. "X-IIS: %u00E9\r\n"
  10285. "Connection: close\r\n"
  10286. "\r\n";
  10287. std::string res;
  10288. ASSERT_TRUE(send_request(5, req, &res));
  10289. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10290. // Every value must be returned verbatim (wire form), with no decoding.
  10291. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10292. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10293. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10294. EXPECT_EQ("%E3%81%82", x_unicode);
  10295. EXPECT_EQ("%u00E9", x_iis);
  10296. }
  10297. // Applications that previously relied on automatic percent-decoding can
  10298. // reproduce the old behavior by explicitly calling decode_path_component()
  10299. // or, for RFC 3986 conformance, decode_uri_component().
  10300. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10301. Server svr;
  10302. std::string decoded;
  10303. svr.Get("/check", [&](const Request &req, Response &res) {
  10304. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10305. res.set_content("ok", "text/plain");
  10306. });
  10307. thread t = thread([&] { svr.listen(HOST, PORT); });
  10308. auto se = detail::scope_exit([&] {
  10309. svr.stop();
  10310. t.join();
  10311. ASSERT_FALSE(svr.is_running());
  10312. });
  10313. svr.wait_until_ready();
  10314. const std::string req = "GET /check HTTP/1.1\r\n"
  10315. "Host: localhost\r\n"
  10316. "X-Custom: hello%20world\r\n"
  10317. "Connection: close\r\n"
  10318. "\r\n";
  10319. std::string res;
  10320. ASSERT_TRUE(send_request(5, req, &res));
  10321. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10322. EXPECT_EQ("hello world", decoded);
  10323. }
  10324. // Regression test for #2033. Browsers send Referer values that include
  10325. // percent-encoded characters such as %0A inside the URL. Decoding the
  10326. // header value would either trip the post-decode CR/LF/NUL guard (the
  10327. // original bug, returning 400) or, after that guard was relaxed, silently
  10328. // store a literal LF — both unacceptable. The wire form must round-trip.
  10329. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10330. Server svr;
  10331. std::string referer;
  10332. svr.Get("/check", [&](const Request &req, Response &res) {
  10333. referer = req.get_header_value("Referer");
  10334. res.set_content("ok", "text/plain");
  10335. });
  10336. thread t = thread([&] { svr.listen(HOST, PORT); });
  10337. auto se = detail::scope_exit([&] {
  10338. svr.stop();
  10339. t.join();
  10340. ASSERT_FALSE(svr.is_running());
  10341. });
  10342. svr.wait_until_ready();
  10343. const std::string req = "GET /check HTTP/1.1\r\n"
  10344. "Host: localhost\r\n"
  10345. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10346. "Connection: close\r\n"
  10347. "\r\n";
  10348. std::string res;
  10349. ASSERT_TRUE(send_request(5, req, &res));
  10350. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10351. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10352. }
  10353. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10354. Server svr;
  10355. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10356. res.set_header("Cache-Control", "no-cache");
  10357. res.set_chunked_content_provider(
  10358. "text/event-stream", [](size_t offset, DataSink &sink) {
  10359. std::string s = "data:";
  10360. s += std::to_string(offset);
  10361. s += "\n\n";
  10362. auto ret = sink.write(s.data(), s.size());
  10363. EXPECT_TRUE(ret);
  10364. std::this_thread::sleep_for(std::chrono::seconds(1));
  10365. return true;
  10366. });
  10367. });
  10368. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10369. svr.wait_until_ready();
  10370. Client client(HOST, PORT);
  10371. const Headers headers = {{"Accept", "text/event-stream"}};
  10372. auto get_thread = std::thread([&client, &headers]() {
  10373. auto res = client.Get(
  10374. "/events", headers,
  10375. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10376. });
  10377. auto se = detail::scope_exit([&] {
  10378. svr.stop();
  10379. get_thread.join();
  10380. listen_thread.join();
  10381. ASSERT_FALSE(svr.is_running());
  10382. });
  10383. // Give GET time to get a few messages.
  10384. std::this_thread::sleep_for(std::chrono::seconds(2));
  10385. }
  10386. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10387. httplib::Server svr;
  10388. svr.Post("/hi",
  10389. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10390. res.status = StatusCode::OK_200;
  10391. });
  10392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10393. svr.wait_until_ready();
  10394. Client cli(HOST, PORT);
  10395. auto res = cli.Post("/hi", "data", "text/plain");
  10396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10397. EXPECT_EQ(StatusCode::OK_200, res->status);
  10398. svr.stop();
  10399. thread.join();
  10400. ASSERT_FALSE(svr.is_running());
  10401. res = cli.Post("/hi", "data", "text/plain");
  10402. ASSERT_FALSE(res);
  10403. }
  10404. TEST(ServerStopTest, ListenFailure) {
  10405. Server svr;
  10406. auto t = thread([&]() {
  10407. auto ret = svr.listen("????", PORT);
  10408. EXPECT_FALSE(ret);
  10409. });
  10410. svr.wait_until_ready();
  10411. svr.stop();
  10412. t.join();
  10413. }
  10414. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10415. TEST(ServerStopTest, Decommision) {
  10416. Server svr;
  10417. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10418. for (int i = 0; i < 4; i++) {
  10419. auto is_even = !(i % 2);
  10420. std::thread t{[&] {
  10421. try {
  10422. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10423. if (is_even) {
  10424. throw std::runtime_error("Some thing that happens to go wrong.");
  10425. }
  10426. svr.listen(HOST, PORT);
  10427. } catch (...) { svr.decommission(); }
  10428. }};
  10429. svr.wait_until_ready();
  10430. // Server is up
  10431. {
  10432. Client cli(HOST, PORT);
  10433. auto res = cli.Get("/hi");
  10434. if (is_even) {
  10435. EXPECT_FALSE(res);
  10436. } else {
  10437. EXPECT_TRUE(res);
  10438. EXPECT_EQ("hi...", res->body);
  10439. }
  10440. }
  10441. svr.stop();
  10442. t.join();
  10443. // Server is down...
  10444. {
  10445. Client cli(HOST, PORT);
  10446. auto res = cli.Get("/hi");
  10447. EXPECT_FALSE(res);
  10448. }
  10449. }
  10450. }
  10451. #endif
  10452. // Helper function for string body upload progress tests
  10453. template <typename SetupHandler, typename ClientCall>
  10454. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10455. ClientCall &&client_call,
  10456. const string &body) {
  10457. Server svr;
  10458. setup_handler(svr);
  10459. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10460. auto se = detail::scope_exit([&] {
  10461. svr.stop();
  10462. t.join();
  10463. });
  10464. svr.wait_until_ready();
  10465. Client cli(HOST, PORT);
  10466. vector<uint64_t> progress_values;
  10467. bool progress_called = false;
  10468. auto res =
  10469. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10470. progress_values.push_back(current);
  10471. progress_called = true;
  10472. return true;
  10473. });
  10474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10475. EXPECT_EQ(200, res->status);
  10476. EXPECT_TRUE(progress_called);
  10477. }
  10478. TEST(UploadProgressTest, PostStringBodyBasic) {
  10479. TestStringBodyUploadProgress(
  10480. [](Server &svr) {
  10481. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10482. res.set_content("received", "text/plain");
  10483. });
  10484. },
  10485. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10486. return cli.Post("/test", body, "text/plain", progress_callback);
  10487. },
  10488. "test data for upload progress");
  10489. }
  10490. TEST(UploadProgressTest, PutStringBodyBasic) {
  10491. TestStringBodyUploadProgress(
  10492. [](Server &svr) {
  10493. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10494. res.set_content("put received", "text/plain");
  10495. });
  10496. },
  10497. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10498. return cli.Put("/test", body, "text/plain", progress_callback);
  10499. },
  10500. "put test data for upload progress");
  10501. }
  10502. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10503. TestStringBodyUploadProgress(
  10504. [](Server &svr) {
  10505. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10506. res.set_content("patch received", "text/plain");
  10507. });
  10508. },
  10509. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10510. return cli.Patch("/test", body, "text/plain", progress_callback);
  10511. },
  10512. "patch test data for upload progress");
  10513. }
  10514. // Helper function for content provider upload progress tests
  10515. template <typename SetupHandler, typename ClientCall>
  10516. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10517. ClientCall &&client_call) {
  10518. Server svr;
  10519. setup_handler(svr);
  10520. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10521. auto se = detail::scope_exit([&] {
  10522. svr.stop();
  10523. t.join();
  10524. });
  10525. svr.wait_until_ready();
  10526. Client cli(HOST, PORT);
  10527. vector<uint64_t> progress_values;
  10528. auto res =
  10529. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10530. progress_values.push_back(current);
  10531. return true;
  10532. });
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. EXPECT_EQ(200, res->status);
  10535. EXPECT_FALSE(progress_values.empty());
  10536. }
  10537. TEST(UploadProgressTest, PostContentProviderProgress) {
  10538. TestContentProviderUploadProgress(
  10539. [](Server &svr) {
  10540. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10541. res.set_content("provider received", "text/plain");
  10542. });
  10543. },
  10544. [](Client &cli, UploadProgress progress_callback) {
  10545. return cli.Post(
  10546. "/test", 9,
  10547. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10548. sink.os << "test data";
  10549. return true;
  10550. },
  10551. "text/plain", progress_callback);
  10552. });
  10553. }
  10554. // Helper function for multipart upload progress tests
  10555. template <typename SetupHandler, typename ClientCall>
  10556. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10557. ClientCall &&client_call,
  10558. const string &endpoint) {
  10559. Server svr;
  10560. setup_handler(svr);
  10561. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10562. auto se = detail::scope_exit([&] {
  10563. svr.stop();
  10564. t.join();
  10565. });
  10566. svr.wait_until_ready();
  10567. Client cli(HOST, PORT);
  10568. vector<uint64_t> progress_values;
  10569. UploadFormDataItems items = {
  10570. {"field1", "value1", "", ""},
  10571. {"field2", "longer value for progress tracking test", "", ""},
  10572. {"file1", "file content data for upload progress", "test.txt",
  10573. "text/plain"}};
  10574. auto res = client_call(cli, endpoint, items,
  10575. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10576. progress_values.push_back(current);
  10577. return true;
  10578. });
  10579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10580. EXPECT_EQ(200, res->status);
  10581. EXPECT_FALSE(progress_values.empty());
  10582. }
  10583. TEST(UploadProgressTest, PostMultipartProgress) {
  10584. TestMultipartUploadProgress(
  10585. [](Server &svr) {
  10586. svr.Post("/multipart", [](const Request &req, Response &res) {
  10587. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10588. res.set_content("multipart received", "text/plain");
  10589. });
  10590. },
  10591. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10592. UploadProgress progress_callback) {
  10593. return cli.Post(endpoint, items, progress_callback);
  10594. },
  10595. "/multipart");
  10596. }
  10597. // Helper function for basic download progress tests
  10598. template <typename SetupHandler, typename ClientCall>
  10599. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10600. ClientCall &&client_call, const string &endpoint,
  10601. size_t expected_content_size) {
  10602. Server svr;
  10603. setup_handler(svr);
  10604. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10605. auto se = detail::scope_exit([&] {
  10606. svr.stop();
  10607. t.join();
  10608. });
  10609. svr.wait_until_ready();
  10610. Client cli(HOST, PORT);
  10611. vector<uint64_t> progress_values;
  10612. auto res = client_call(cli, endpoint,
  10613. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10614. progress_values.push_back(current);
  10615. return true;
  10616. });
  10617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10618. EXPECT_EQ(200, res->status);
  10619. EXPECT_FALSE(progress_values.empty());
  10620. EXPECT_EQ(expected_content_size, res->body.size());
  10621. }
  10622. TEST(DownloadProgressTest, GetBasic) {
  10623. TestBasicDownloadProgress(
  10624. [](Server &svr) {
  10625. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10626. string content(1000, 'D');
  10627. res.set_content(content, "text/plain");
  10628. });
  10629. },
  10630. [](Client &cli, const string &endpoint,
  10631. DownloadProgress progress_callback) {
  10632. return cli.Get(endpoint, progress_callback);
  10633. },
  10634. "/download", 1000u);
  10635. }
  10636. // Helper function for content receiver download progress tests
  10637. template <typename SetupHandler, typename ClientCall>
  10638. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10639. ClientCall &&client_call,
  10640. const string &endpoint,
  10641. size_t expected_content_size) {
  10642. Server svr;
  10643. setup_handler(svr);
  10644. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10645. auto se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. t.join();
  10648. });
  10649. svr.wait_until_ready();
  10650. Client cli(HOST, PORT);
  10651. vector<uint64_t> progress_values;
  10652. string received_body;
  10653. auto res = client_call(
  10654. cli, endpoint,
  10655. [&](const char *data, size_t data_length) -> bool {
  10656. received_body.append(data, data_length);
  10657. return true;
  10658. },
  10659. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10660. progress_values.push_back(current);
  10661. return true;
  10662. });
  10663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10664. EXPECT_EQ(200, res->status);
  10665. EXPECT_FALSE(progress_values.empty());
  10666. EXPECT_EQ(expected_content_size, received_body.size());
  10667. EXPECT_TRUE(res->body.empty());
  10668. }
  10669. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10670. TestContentReceiverDownloadProgress(
  10671. [](Server &svr) {
  10672. svr.Get("/download-receiver",
  10673. [](const Request & /*req*/, Response &res) {
  10674. string content(2000, 'R');
  10675. res.set_content(content, "text/plain");
  10676. });
  10677. },
  10678. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10679. DownloadProgress progress_callback) {
  10680. return cli.Get(endpoint, content_receiver, progress_callback);
  10681. },
  10682. "/download-receiver", 2000u);
  10683. }
  10684. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10685. // A provider reaching a pass with nothing to hand over - an empty buffer
  10686. // popped off a queue, say - must not be taken to mean the body is finished.
  10687. // It used to end the loop with the terminating chunk unwritten while the
  10688. // server still considered the response complete, so the peer waited for an
  10689. // end that never arrived.
  10690. Server svr;
  10691. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10692. auto step = std::make_shared<int>(0);
  10693. res.set_chunked_content_provider("text/plain",
  10694. [step](size_t /*offset*/, DataSink &sink) {
  10695. switch ((*step)++) {
  10696. case 0: sink.write("", 0); break;
  10697. case 1: sink.write("hello", 5); break;
  10698. default: sink.done(); break;
  10699. }
  10700. return true;
  10701. });
  10702. });
  10703. auto port = svr.bind_to_any_port(HOST);
  10704. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10705. auto listen_se = detail::scope_exit([&] {
  10706. svr.stop();
  10707. listen_thread.join();
  10708. ASSERT_FALSE(svr.is_running());
  10709. });
  10710. svr.wait_until_ready();
  10711. Client cli(HOST, port);
  10712. // Without the fix the body is never terminated, so bound the wait rather
  10713. // than letting the test hang on the default read timeout.
  10714. cli.set_read_timeout(5, 0);
  10715. auto res = cli.Get("/stream");
  10716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10717. EXPECT_EQ(StatusCode::OK_200, res->status);
  10718. EXPECT_EQ("hello", res->body);
  10719. }
  10720. TEST(StreamingTest, NoContentLengthStreaming) {
  10721. Server svr;
  10722. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10723. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10724. if (offset < 6) {
  10725. sink.os << (offset < 3 ? "a" : "b");
  10726. } else {
  10727. sink.done();
  10728. }
  10729. return true;
  10730. });
  10731. });
  10732. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10733. auto listen_se = detail::scope_exit([&] {
  10734. svr.stop();
  10735. listen_thread.join();
  10736. ASSERT_FALSE(svr.is_running());
  10737. });
  10738. svr.wait_until_ready();
  10739. Client client(HOST, PORT);
  10740. auto get_thread = std::thread([&client]() {
  10741. std::string s;
  10742. auto res =
  10743. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10744. s += std::string(data, len);
  10745. return true;
  10746. });
  10747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10748. EXPECT_EQ(StatusCode::OK_200, res->status);
  10749. EXPECT_EQ("aaabbb", s);
  10750. });
  10751. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10752. // Give GET time to get a few messages.
  10753. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10754. }
  10755. TEST(MountTest, Unmount) {
  10756. Server svr;
  10757. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10758. auto se = detail::scope_exit([&] {
  10759. svr.stop();
  10760. listen_thread.join();
  10761. ASSERT_FALSE(svr.is_running());
  10762. });
  10763. svr.wait_until_ready();
  10764. Client cli("localhost", PORT);
  10765. svr.set_mount_point("/mount2", "./www2");
  10766. auto res = cli.Get("/");
  10767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10769. res = cli.Get("/mount2/dir/test.html");
  10770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10771. EXPECT_EQ(StatusCode::OK_200, res->status);
  10772. svr.set_mount_point("/", "./www");
  10773. res = cli.Get("/dir/");
  10774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10775. EXPECT_EQ(StatusCode::OK_200, res->status);
  10776. svr.remove_mount_point("/");
  10777. res = cli.Get("/dir/");
  10778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10779. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10780. svr.remove_mount_point("/mount2");
  10781. res = cli.Get("/mount2/dir/test.html");
  10782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10783. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10784. }
  10785. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10786. Server svr;
  10787. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10788. svr.Get("/api/hello", [](const Request &, Response &res) {
  10789. res.set_content("api", "text/plain");
  10790. });
  10791. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10792. auto se = detail::scope_exit([&] {
  10793. svr.stop();
  10794. listen_thread.join();
  10795. ASSERT_FALSE(svr.is_running());
  10796. });
  10797. svr.wait_until_ready();
  10798. Client cli(HOST, PORT);
  10799. auto res = cli.Get("/dir/test.html");
  10800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10801. EXPECT_EQ(StatusCode::OK_200, res->status);
  10802. res = cli.Get("/api/hello");
  10803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10804. EXPECT_EQ(StatusCode::OK_200, res->status);
  10805. EXPECT_EQ("api", res->body);
  10806. }
  10807. TEST(MountTest, PathSegmentBoundary) {
  10808. Server svr;
  10809. svr.set_mount_point("/mount2", "./www2");
  10810. svr.set_mount_point("/", "./www");
  10811. auto port = svr.bind_to_any_port(HOST);
  10812. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10813. auto se = detail::scope_exit([&] {
  10814. svr.stop();
  10815. listen_thread.join();
  10816. ASSERT_FALSE(svr.is_running());
  10817. });
  10818. svr.wait_until_ready();
  10819. Client cli(HOST, port);
  10820. auto res = cli.Get("/mount2/dir/test.html");
  10821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10822. EXPECT_EQ(StatusCode::OK_200, res->status);
  10823. // "/mount2" must not match part-way through a path segment.
  10824. res = cli.Get("/mount2dir/test.html");
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10827. // A mount point ending in '/' keeps matching every path below it.
  10828. res = cli.Get("/dir/test.html");
  10829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10830. EXPECT_EQ(StatusCode::OK_200, res->status);
  10831. }
  10832. TEST(MountTest, Redicect) {
  10833. Server svr;
  10834. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10835. auto se = detail::scope_exit([&] {
  10836. svr.stop();
  10837. listen_thread.join();
  10838. ASSERT_FALSE(svr.is_running());
  10839. });
  10840. svr.set_mount_point("/", "./www");
  10841. svr.wait_until_ready();
  10842. Client cli("localhost", PORT);
  10843. auto res = cli.Get("/dir/");
  10844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10845. EXPECT_EQ(StatusCode::OK_200, res->status);
  10846. res = cli.Get("/dir");
  10847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10848. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10849. res = cli.Get("/file");
  10850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10851. EXPECT_EQ(StatusCode::OK_200, res->status);
  10852. res = cli.Get("/file/");
  10853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10855. cli.set_follow_location(true);
  10856. res = cli.Get("/dir");
  10857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10858. EXPECT_EQ(StatusCode::OK_200, res->status);
  10859. }
  10860. TEST(MountTest, MultibytesPathName) {
  10861. Server svr;
  10862. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10863. auto se = detail::scope_exit([&] {
  10864. svr.stop();
  10865. listen_thread.join();
  10866. ASSERT_FALSE(svr.is_running());
  10867. });
  10868. svr.set_mount_point("/", "./www");
  10869. svr.wait_until_ready();
  10870. Client cli("localhost", PORT);
  10871. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10873. EXPECT_EQ(StatusCode::OK_200, res->status);
  10874. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10875. }
  10876. // A mount point serves no path with an empty segment or one ending in '.' or
  10877. // a space, so a guard in the pre-routing handler sees the path of every file
  10878. // that is served
  10879. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10880. Server svr;
  10881. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10882. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10883. if (req.path == "/dir/test.html") {
  10884. res.status = StatusCode::Unauthorized_401;
  10885. return Server::HandlerResponse::Handled;
  10886. }
  10887. return Server::HandlerResponse::Unhandled;
  10888. });
  10889. auto port = svr.bind_to_any_port(HOST);
  10890. ASSERT_LT(0, port);
  10891. thread t = thread([&] { svr.listen_after_bind(); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. t.join();
  10895. ASSERT_FALSE(svr.is_running());
  10896. });
  10897. svr.wait_until_ready();
  10898. Client cli(HOST, port);
  10899. for (auto path :
  10900. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10901. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10902. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  10903. "/dir/test.html%3A%3A$DATA"}) {
  10904. SCOPED_TRACE(path);
  10905. auto res = cli.Get(path);
  10906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10907. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10908. }
  10909. }
  10910. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10911. Server svr;
  10912. svr.set_mount_point("/", "./www");
  10913. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10914. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10915. auto port = svr.bind_to_any_port(HOST);
  10916. ASSERT_GT(port, 0);
  10917. thread t = thread([&] { svr.listen_after_bind(); });
  10918. auto se = detail::scope_exit([&] {
  10919. svr.stop();
  10920. t.join();
  10921. ASSERT_FALSE(svr.is_running());
  10922. });
  10923. svr.wait_until_ready();
  10924. Client cli(HOST, port);
  10925. auto res = cli.Get("/dir/test.abcde");
  10926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10927. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10928. res = cli.Get("/dir/test.html");
  10929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10930. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10931. }
  10932. #ifdef _WIN32
  10933. // Issue #2435: mmap::open() must succeed even when another handle holds
  10934. // the file open for writing (e.g. an active log file).
  10935. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10936. const char *path = "mmap_concurrent_writer_test.txt";
  10937. const char *content = "hello";
  10938. {
  10939. std::ofstream f(path, std::ios::binary);
  10940. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10941. }
  10942. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10943. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10944. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10945. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10946. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10947. detail::mmap m(path);
  10948. ASSERT_TRUE(m.is_open());
  10949. EXPECT_EQ(strlen(content), m.size());
  10950. char buf[8];
  10951. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10952. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10953. }
  10954. #endif
  10955. #ifndef _WIN32
  10956. // A directory or a device has no size to serve.
  10957. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10958. const char *path = "./mmap_not_regular_test_dir";
  10959. ASSERT_EQ(0, ::mkdir(path, 0755));
  10960. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10961. for (auto p : {path, "/dev/null"}) {
  10962. detail::mmap m(p);
  10963. EXPECT_FALSE(m.is_open()) << p;
  10964. EXPECT_EQ(0U, m.size()) << p;
  10965. }
  10966. Server svr;
  10967. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10968. res.set_file_content("/dev/null");
  10969. });
  10970. auto port = svr.bind_to_any_port(HOST);
  10971. thread t = thread([&] { svr.listen_after_bind(); });
  10972. auto se = detail::scope_exit([&] {
  10973. svr.stop();
  10974. t.join();
  10975. });
  10976. svr.wait_until_ready();
  10977. auto res = Client(HOST, port).Get("/null");
  10978. ASSERT_TRUE(res);
  10979. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10980. }
  10981. #endif
  10982. #ifdef __linux__
  10983. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10984. TEST(MmapTest, FileIsNotMapped) {
  10985. const char *path = "mmap_not_mapped_test.txt";
  10986. {
  10987. std::ofstream f(path, std::ios::binary);
  10988. f << "hello";
  10989. }
  10990. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10991. detail::mmap m(path);
  10992. ASSERT_TRUE(m.is_open());
  10993. std::ifstream maps("/proc/self/maps");
  10994. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10995. std::istreambuf_iterator<char>());
  10996. EXPECT_EQ(std::string::npos, mappings.find(path));
  10997. }
  10998. #endif
  10999. TEST(KeepAliveTest, ReadTimeout) {
  11000. Server svr;
  11001. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11002. std::this_thread::sleep_for(std::chrono::seconds(2));
  11003. res.set_content("a", "text/plain");
  11004. });
  11005. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11006. res.set_content("b", "text/plain");
  11007. });
  11008. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11009. auto se = detail::scope_exit([&] {
  11010. svr.stop();
  11011. listen_thread.join();
  11012. ASSERT_FALSE(svr.is_running());
  11013. });
  11014. svr.wait_until_ready();
  11015. Client cli("localhost", PORT);
  11016. cli.set_keep_alive(true);
  11017. cli.set_read_timeout(std::chrono::seconds(1));
  11018. auto resa = cli.Get("/a");
  11019. ASSERT_FALSE(resa);
  11020. EXPECT_EQ(Error::Read, resa.error());
  11021. auto resb = cli.Get("/b");
  11022. ASSERT_TRUE(resb);
  11023. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11024. EXPECT_EQ("b", resb->body);
  11025. }
  11026. TEST(KeepAliveTest, MaxCount) {
  11027. size_t keep_alive_max_count = 3;
  11028. Server svr;
  11029. svr.set_keep_alive_max_count(keep_alive_max_count);
  11030. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11031. res.set_content("Hello World!", "text/plain");
  11032. });
  11033. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11034. auto se = detail::scope_exit([&] {
  11035. svr.stop();
  11036. listen_thread.join();
  11037. ASSERT_FALSE(svr.is_running());
  11038. });
  11039. svr.wait_until_ready();
  11040. Client cli(HOST, PORT);
  11041. cli.set_keep_alive(true);
  11042. for (size_t i = 0; i < 5; i++) {
  11043. auto result = cli.Get("/hi");
  11044. ASSERT_TRUE(result);
  11045. EXPECT_EQ(StatusCode::OK_200, result->status);
  11046. if (i == keep_alive_max_count - 1) {
  11047. EXPECT_EQ("close", result->get_header_value("Connection"));
  11048. } else {
  11049. EXPECT_FALSE(result->has_header("Connection"));
  11050. }
  11051. }
  11052. }
  11053. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11054. // can pull the next one into the server's buffer. The server must serve it
  11055. // without waiting for the socket to become readable again. The keep-alive
  11056. // timeout outlasts the client's read timeout, so a request left waiting for it
  11057. // shows up as a missing response.
  11058. static void serve_pipelining_routes(Server &svr,
  11059. const std::function<void(int)> &client) {
  11060. svr.set_keep_alive_timeout(5);
  11061. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11062. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11063. });
  11064. svr.Post("/echo", [](const Request &req, Response &res) {
  11065. res.set_content("echo " + req.body, "text/plain");
  11066. });
  11067. auto port = svr.bind_to_any_port(HOST);
  11068. thread t = thread([&] { svr.listen_after_bind(); });
  11069. auto se = detail::scope_exit([&] {
  11070. svr.stop();
  11071. t.join();
  11072. });
  11073. svr.wait_until_ready();
  11074. client(port);
  11075. }
  11076. static std::string
  11077. send_pipelined_requests(const std::vector<std::string> &parts) {
  11078. Server svr;
  11079. std::string res;
  11080. serve_pipelining_routes(svr, [&](int port) {
  11081. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11082. });
  11083. return res;
  11084. }
  11085. static void expect_in_order(const std::string &res,
  11086. const std::vector<std::string> &bodies) {
  11087. size_t pos = 0;
  11088. for (const auto &body : bodies) {
  11089. pos = res.find(body, pos);
  11090. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11091. pos += body.size();
  11092. }
  11093. }
  11094. TEST(KeepAliveTest, PipelinedRequests) {
  11095. auto res = send_pipelined_requests(
  11096. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11097. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11098. "Content-Length: 4\r\n\r\nbody"
  11099. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11100. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11101. }
  11102. // The second request starts in the server's buffer and ends on the socket.
  11103. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11104. auto res =
  11105. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11106. "GET /hi/2 HTTP/1.1\r\nHo",
  11107. "st: localhost\r\nConnection: close\r\n\r\n"});
  11108. expect_in_order(res, {"hi 1", "hi 2"});
  11109. }
  11110. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11111. // CRLF after a body does not turn into a 400 for the next request.
  11112. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11113. auto res = send_pipelined_requests(
  11114. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11115. "Content-Length: 4\r\n\r\nbody\r\n"
  11116. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11117. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11118. expect_in_order(res, {"echo body", "hi 2"});
  11119. }
  11120. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11121. // must not be served as the next request.
  11122. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11123. auto res = send_pipelined_requests(
  11124. {"INVALID REQUEST LINE\r\n\r\n"
  11125. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11126. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11127. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11128. }
  11129. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11130. // Over TLS, the next request is held by the TLS library as already decrypted
  11131. // data rather than on the socket.
  11132. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11134. std::string res;
  11135. serve_pipelining_routes(svr, [&](int port) {
  11136. // One part, so all three requests arrive in one TLS record
  11137. EXPECT_TRUE(send_ssl_request_in_parts(
  11138. 2,
  11139. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11140. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11141. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11142. &res, port));
  11143. });
  11144. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11145. }
  11146. #endif
  11147. TEST(KeepAliveTest, Issue1041) {
  11148. Server svr;
  11149. svr.set_keep_alive_timeout(3);
  11150. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11151. res.set_content("Hello World!", "text/plain");
  11152. });
  11153. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11154. auto se = detail::scope_exit([&] {
  11155. svr.stop();
  11156. listen_thread.join();
  11157. ASSERT_FALSE(svr.is_running());
  11158. });
  11159. svr.wait_until_ready();
  11160. Client cli(HOST, PORT);
  11161. cli.set_keep_alive(true);
  11162. auto result = cli.Get("/hi");
  11163. ASSERT_TRUE(result);
  11164. EXPECT_EQ(StatusCode::OK_200, result->status);
  11165. std::this_thread::sleep_for(std::chrono::seconds(5));
  11166. result = cli.Get("/hi");
  11167. ASSERT_TRUE(result);
  11168. EXPECT_EQ(StatusCode::OK_200, result->status);
  11169. }
  11170. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11171. Server svr;
  11172. svr.set_keep_alive_max_count(0);
  11173. std::set<int> remote_ports;
  11174. svr.Get("/hi", [&](const Request &req, Response &res) {
  11175. remote_ports.insert(req.remote_port);
  11176. res.set_content("hi", "text/plain");
  11177. });
  11178. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. listen_thread.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. Client cli(HOST, PORT);
  11186. cli.set_keep_alive(true);
  11187. for (int i = 0; i < 3; i++) {
  11188. auto res = cli.Get("/hi");
  11189. ASSERT_TRUE(res);
  11190. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11191. }
  11192. // All three over one connection
  11193. EXPECT_EQ(1u, remote_ports.size());
  11194. }
  11195. TEST(KeepAliveTest, Issue1959) {
  11196. Server svr;
  11197. svr.set_keep_alive_timeout(5);
  11198. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11199. res.set_content("a", "text/plain");
  11200. });
  11201. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11202. auto se = detail::scope_exit([&] {
  11203. if (!svr.is_running()) return;
  11204. svr.stop();
  11205. listen_thread.join();
  11206. ASSERT_FALSE(svr.is_running());
  11207. });
  11208. svr.wait_until_ready();
  11209. Client cli("localhost", PORT);
  11210. cli.set_keep_alive(true);
  11211. using namespace std::chrono;
  11212. auto start = steady_clock::now();
  11213. cli.Get("/a");
  11214. svr.stop();
  11215. listen_thread.join();
  11216. auto end = steady_clock::now();
  11217. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11218. EXPECT_LT(elapsed, 5000);
  11219. }
  11220. #ifdef CPPHTTPLIB_SSL_ENABLED
  11221. TEST(KeepAliveTest, SSLClientReconnection) {
  11222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11223. ASSERT_TRUE(svr.is_valid());
  11224. svr.set_keep_alive_timeout(1);
  11225. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11226. res.set_content("Hello World!", "text/plain");
  11227. });
  11228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11229. auto se = detail::scope_exit([&] {
  11230. svr.stop();
  11231. listen_thread.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. SSLClient cli(HOST, PORT);
  11236. cli.enable_server_certificate_verification(false);
  11237. cli.set_keep_alive(true);
  11238. auto result = cli.Get("/hi");
  11239. ASSERT_TRUE(result);
  11240. EXPECT_EQ(StatusCode::OK_200, result->status);
  11241. result = cli.Get("/hi");
  11242. ASSERT_TRUE(result);
  11243. EXPECT_EQ(StatusCode::OK_200, result->status);
  11244. std::this_thread::sleep_for(std::chrono::seconds(2));
  11245. // Recoonect
  11246. result = cli.Get("/hi");
  11247. ASSERT_TRUE(result);
  11248. EXPECT_EQ(StatusCode::OK_200, result->status);
  11249. result = cli.Get("/hi");
  11250. ASSERT_TRUE(result);
  11251. EXPECT_EQ(StatusCode::OK_200, result->status);
  11252. }
  11253. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11254. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11255. ASSERT_TRUE(svr.is_valid());
  11256. svr.set_keep_alive_timeout(1);
  11257. std::string content = "reconnect";
  11258. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11259. res.set_content("Hello World!", "text/plain");
  11260. });
  11261. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11262. auto se = detail::scope_exit([&] {
  11263. svr.stop();
  11264. listen_thread.join();
  11265. ASSERT_FALSE(svr.is_running());
  11266. });
  11267. svr.wait_until_ready();
  11268. SSLClient cli(HOST, PORT);
  11269. cli.enable_server_certificate_verification(false);
  11270. cli.set_keep_alive(true);
  11271. auto result = cli.Post(
  11272. "/hi", content.size(),
  11273. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11274. sink.write(content.c_str(), content.size());
  11275. return true;
  11276. },
  11277. "text/plain");
  11278. ASSERT_TRUE(result);
  11279. EXPECT_EQ(200, result->status);
  11280. std::this_thread::sleep_for(std::chrono::seconds(2));
  11281. // Recoonect
  11282. result = cli.Post(
  11283. "/hi", content.size(),
  11284. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11285. sink.write(content.c_str(), content.size());
  11286. return true;
  11287. },
  11288. "text/plain");
  11289. ASSERT_TRUE(result);
  11290. EXPECT_EQ(200, result->status);
  11291. result = cli.Post(
  11292. "/hi", content.size(),
  11293. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11294. sink.write(content.c_str(), content.size());
  11295. return true;
  11296. },
  11297. "text/plain");
  11298. ASSERT_TRUE(result);
  11299. EXPECT_EQ(200, result->status);
  11300. }
  11301. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11302. using namespace httplib::tls;
  11303. {
  11304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11305. ASSERT_TRUE(svr.is_valid());
  11306. svr.Get("/sni", [&](const Request &req, Response &res) {
  11307. std::string expected = req.sni();
  11308. EXPECT_EQ(expected, req.get_param_value("expected"));
  11309. res.set_content("ok", "text/plain");
  11310. });
  11311. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11312. auto se = detail::scope_exit([&] {
  11313. svr.stop();
  11314. listen_thread.join();
  11315. ASSERT_FALSE(svr.is_running());
  11316. });
  11317. svr.wait_until_ready();
  11318. {
  11319. SSLClient cli("localhost", PORT);
  11320. cli.enable_server_certificate_verification(false);
  11321. auto res = cli.Get("/sni?expected=localhost");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. }
  11324. {
  11325. SSLClient cli("::1", PORT);
  11326. cli.enable_server_certificate_verification(false);
  11327. auto res = cli.Get("/sni?expected=");
  11328. // NOTE: This may fail if the server is listening on IPv4 only
  11329. // (e.g., when localhost resolves to 127.0.0.1 only)
  11330. if (res) {
  11331. EXPECT_EQ(StatusCode::OK_200, res->status);
  11332. } else {
  11333. EXPECT_EQ(Error::Connection, res.error());
  11334. }
  11335. }
  11336. }
  11337. }
  11338. // The SNI of a failed handshake does not reach the next connection that the
  11339. // same worker thread serves
  11340. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11342. ASSERT_TRUE(svr.is_valid());
  11343. svr.new_task_queue = [] { return new ThreadPool(1); };
  11344. svr.Get("/sni", [](const Request &req, Response &res) {
  11345. res.set_content(req.sni(), "text/plain");
  11346. });
  11347. auto port = svr.bind_to_any_port("127.0.0.1");
  11348. ASSERT_LT(0, port);
  11349. thread t = thread([&] { svr.listen_after_bind(); });
  11350. auto se = detail::scope_exit([&] {
  11351. svr.stop();
  11352. t.join();
  11353. ASSERT_FALSE(svr.is_running());
  11354. });
  11355. svr.wait_until_ready();
  11356. {
  11357. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11358. SSLClient cli("localhost", port);
  11359. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11360. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11361. auto res = cli.Get("/sni");
  11362. ASSERT_FALSE(res);
  11363. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11364. }
  11365. // An IP host sends no SNI (RFC 6066)
  11366. SSLClient cli("127.0.0.1", port);
  11367. cli.enable_server_certificate_verification(false);
  11368. auto res = cli.Get("/sni");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ("", res->body);
  11371. }
  11372. #endif
  11373. TEST(ClientProblemDetectionTest, ContentProvider) {
  11374. Server svr;
  11375. size_t content_length = 1024 * 1024;
  11376. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11377. res.set_content_provider(
  11378. content_length, "text/plain",
  11379. [&](size_t offset, size_t length, DataSink &sink) {
  11380. auto out_len = std::min(length, static_cast<size_t>(1024));
  11381. std::string out(out_len, '@');
  11382. sink.write(out.data(), out_len);
  11383. return offset < 4096;
  11384. },
  11385. [](bool success) { ASSERT_FALSE(success); });
  11386. });
  11387. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11388. res.set_content_provider(
  11389. 0, "text/plain",
  11390. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11391. EXPECT_TRUE(false);
  11392. return true;
  11393. },
  11394. [](bool success) { ASSERT_FALSE(success); });
  11395. });
  11396. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11397. auto se = detail::scope_exit([&] {
  11398. svr.stop();
  11399. listen_thread.join();
  11400. ASSERT_FALSE(svr.is_running());
  11401. });
  11402. svr.wait_until_ready();
  11403. Client cli("localhost", PORT);
  11404. {
  11405. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11406. size_t /*data_length*/) { return false; });
  11407. ASSERT_FALSE(res);
  11408. }
  11409. {
  11410. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11411. size_t /*data_length*/) { return false; });
  11412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11413. }
  11414. }
  11415. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11416. // A provider that reports success without writing anything and without
  11417. // calling done() used to be handed the same offset and length again on every
  11418. // pass, so it spun for as long as the peer stayed connected.
  11419. Server svr;
  11420. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11421. res.set_content("ok", "text/plain");
  11422. });
  11423. auto port = svr.bind_to_any_port(HOST);
  11424. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11425. auto se = detail::scope_exit([&] {
  11426. svr.stop();
  11427. listen_thread.join();
  11428. ASSERT_FALSE(svr.is_running());
  11429. });
  11430. svr.wait_until_ready();
  11431. std::atomic<int> call_count{0};
  11432. Client cli(HOST, port);
  11433. auto res = cli.Post(
  11434. "/", 1024,
  11435. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11436. // Give up after enough passes to show the spin, so that losing the
  11437. // check below fails this test instead of hanging it.
  11438. return ++call_count < 100;
  11439. },
  11440. "text/plain");
  11441. ASSERT_FALSE(res);
  11442. EXPECT_EQ(Error::Write, res.error());
  11443. EXPECT_EQ(1, call_count.load());
  11444. }
  11445. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11446. // A writer only has to assign `write`. The other three used to be left as
  11447. // empty std::functions, so a provider calling one threw
  11448. // std::bad_function_call out of the thread running it and took the whole
  11449. // process down.
  11450. DataSink sink;
  11451. std::string written;
  11452. sink.write = [&](const char *data, size_t data_len) {
  11453. written.append(data, data_len);
  11454. return true;
  11455. };
  11456. EXPECT_TRUE(sink.is_writable());
  11457. sink.done();
  11458. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11459. EXPECT_TRUE(written.empty());
  11460. }
  11461. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11462. // A sink that cannot carry trailers still has to finish.
  11463. DataSink sink;
  11464. auto done_count = 0;
  11465. sink.done = [&]() { done_count++; };
  11466. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11467. EXPECT_EQ(1, done_count);
  11468. }
  11469. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11470. Server svr;
  11471. const std::string body(4096, 'x');
  11472. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11473. res.set_content_provider(body.size(), "text/plain",
  11474. [&](size_t offset, size_t length, DataSink &sink) {
  11475. sink.write(body.data() + offset, length);
  11476. sink.done();
  11477. return true;
  11478. });
  11479. });
  11480. auto port = svr.bind_to_any_port(HOST);
  11481. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11482. auto se = detail::scope_exit([&] {
  11483. svr.stop();
  11484. listen_thread.join();
  11485. ASSERT_FALSE(svr.is_running());
  11486. });
  11487. svr.wait_until_ready();
  11488. Client cli(HOST, port);
  11489. auto res = cli.Get("/");
  11490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11491. EXPECT_EQ(StatusCode::OK_200, res->status);
  11492. EXPECT_EQ(body, res->body);
  11493. }
  11494. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11495. Server svr;
  11496. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11497. res.set_content_provider(
  11498. 1024, "text/plain",
  11499. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11500. sink.write("hello", 5);
  11501. sink.done(); // short of the 1024 bytes the response promised
  11502. return true;
  11503. });
  11504. });
  11505. auto port = svr.bind_to_any_port(HOST);
  11506. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11507. auto se = detail::scope_exit([&] {
  11508. svr.stop();
  11509. listen_thread.join();
  11510. ASSERT_FALSE(svr.is_running());
  11511. });
  11512. svr.wait_until_ready();
  11513. Client cli(HOST, port);
  11514. cli.set_read_timeout(5, 0);
  11515. // The response is short of its Content-Length, so the client cannot read a
  11516. // complete body. What matters is that this returns at all: a no-op done()
  11517. // would leave the writer looping over a provider that never makes progress.
  11518. auto res = cli.Get("/");
  11519. EXPECT_FALSE(res);
  11520. }
  11521. // Read as the next response by a peer that sees it after a framed body.
  11522. static const std::string smuggled_response =
  11523. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11524. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11525. Server svr;
  11526. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11527. res.set_content_provider(
  11528. 5, "text/plain",
  11529. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11530. auto data = "AAAAA" + smuggled_response;
  11531. sink.write(data.data(), data.size());
  11532. return true;
  11533. });
  11534. });
  11535. thread t = thread([&] { svr.listen(HOST, PORT); });
  11536. auto se = detail::scope_exit([&] {
  11537. svr.stop();
  11538. t.join();
  11539. ASSERT_FALSE(svr.is_running());
  11540. });
  11541. svr.wait_until_ready();
  11542. std::string resp;
  11543. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11544. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11545. resp.clear();
  11546. ASSERT_TRUE(send_request(
  11547. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11548. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11549. }
  11550. TEST(NoContentTest, BodyIsNotSent) {
  11551. Server svr;
  11552. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11553. res.status = StatusCode::NoContent_204;
  11554. res.set_content(smuggled_response, "text/plain");
  11555. });
  11556. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11557. res.status = StatusCode::NotModified_304;
  11558. res.set_chunked_content_provider(
  11559. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11560. sink.write(smuggled_response.data(), smuggled_response.size());
  11561. sink.done();
  11562. return true;
  11563. });
  11564. });
  11565. thread t = thread([&] { svr.listen(HOST, PORT); });
  11566. auto se = detail::scope_exit([&] {
  11567. svr.stop();
  11568. t.join();
  11569. ASSERT_FALSE(svr.is_running());
  11570. });
  11571. svr.wait_until_ready();
  11572. for (auto path : {"/204", "/304"}) {
  11573. std::string resp;
  11574. ASSERT_TRUE(send_request(
  11575. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11576. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11577. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11578. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11579. }
  11580. }
  11581. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11582. Server svr;
  11583. std::atomic<bool> smuggled(false);
  11584. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11585. res.set_content("ok", "text/plain");
  11586. });
  11587. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11588. smuggled = true;
  11589. });
  11590. auto port = svr.bind_to_any_port(HOST);
  11591. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11592. auto se = detail::scope_exit([&] {
  11593. svr.stop();
  11594. listen_thread.join();
  11595. ASSERT_FALSE(svr.is_running());
  11596. });
  11597. svr.wait_until_ready();
  11598. // What follows the body would be read as the next request.
  11599. Client cli(HOST, port);
  11600. auto res = cli.Post(
  11601. "/", 5,
  11602. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11603. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11604. sink.write(data.data(), data.size());
  11605. return true;
  11606. },
  11607. "text/plain");
  11608. ASSERT_FALSE(res);
  11609. EXPECT_EQ(Error::Write, res.error());
  11610. EXPECT_FALSE(smuggled);
  11611. }
  11612. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11613. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11614. // The compressed path builds the whole body before connecting, so this
  11615. // fails client-side and never reaches a server.
  11616. Client cli(HOST, PORT);
  11617. cli.set_compress(true);
  11618. auto res = cli.Post(
  11619. "/", 1024,
  11620. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11621. sink.write("hello", 5);
  11622. sink.done(); // short of the 1024 bytes the request announced
  11623. return true;
  11624. },
  11625. "text/plain");
  11626. ASSERT_FALSE(res);
  11627. EXPECT_EQ(Error::Write, res.error());
  11628. }
  11629. #endif
  11630. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11631. Server svr;
  11632. svr.set_error_handler([](Request const &, Response &res) -> void {
  11633. res.set_chunked_content_provider(
  11634. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11635. sink.os << "hello";
  11636. sink.os << "world";
  11637. sink.done();
  11638. return true;
  11639. });
  11640. });
  11641. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11642. auto se = detail::scope_exit([&] {
  11643. svr.stop();
  11644. listen_thread.join();
  11645. ASSERT_FALSE(svr.is_running());
  11646. });
  11647. svr.wait_until_ready();
  11648. Client cli("localhost", PORT);
  11649. auto res = cli.Get("/");
  11650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11651. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11652. EXPECT_EQ("helloworld", res->body);
  11653. }
  11654. // A body set after a content provider must replace it, not be sent through it.
  11655. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11656. Server svr;
  11657. svr.set_mount_point("/", "./www");
  11658. svr.set_file_request_handler([](const Request &req, Response &res) {
  11659. if (req.path == "/dir/test.html") {
  11660. res.status = StatusCode::Forbidden_403;
  11661. res.set_content(std::string(5000, 'D'), "text/plain");
  11662. } else if (req.path == "/file") {
  11663. res.status = StatusCode::Forbidden_403;
  11664. res.body = "Denied";
  11665. }
  11666. });
  11667. auto port = svr.bind_to_any_port(HOST);
  11668. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11669. auto se = detail::scope_exit([&] {
  11670. svr.stop();
  11671. t.join();
  11672. ASSERT_FALSE(svr.is_running());
  11673. });
  11674. svr.wait_until_ready();
  11675. Client cli(HOST, port);
  11676. {
  11677. auto res = cli.Get("/dir/test.html");
  11678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11679. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11680. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11681. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11682. }
  11683. {
  11684. auto res = cli.Get("/file");
  11685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11686. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11687. EXPECT_EQ("Denied", res->body);
  11688. }
  11689. {
  11690. auto res = cli.Get("/dir/index.html");
  11691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11692. EXPECT_EQ(StatusCode::OK_200, res->status);
  11693. EXPECT_EQ(0U, res->body.find("<html>"));
  11694. }
  11695. }
  11696. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11697. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11698. Server svr;
  11699. std::vector<bool> released;
  11700. std::mutex released_mutex;
  11701. auto releaser = [&](bool success) {
  11702. std::lock_guard<std::mutex> guard(released_mutex);
  11703. released.push_back(success);
  11704. };
  11705. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11706. return sink.write(&"hello"[offset], length);
  11707. };
  11708. svr.Get("/sized", [&](const Request &, Response &res) {
  11709. res.status = StatusCode::NotFound_404;
  11710. res.set_content_provider(5, "text/plain", provider, releaser);
  11711. });
  11712. svr.Get("/chunked", [&](const Request &, Response &res) {
  11713. res.status = StatusCode::ServiceUnavailable_503;
  11714. res.set_chunked_content_provider(
  11715. "text/plain",
  11716. [](size_t, DataSink &sink) {
  11717. sink.os << "chunk";
  11718. sink.done();
  11719. return true;
  11720. },
  11721. releaser);
  11722. });
  11723. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11724. res.set_content_provider(5, "text/plain", provider, releaser);
  11725. throw std::runtime_error("after the provider");
  11726. });
  11727. svr.set_error_handler([](const Request &req, Response &res) {
  11728. // Leave the exception handler's content to it.
  11729. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11730. res.set_content(std::string(1000, 'E'), "text/html");
  11731. return Server::HandlerResponse::Handled;
  11732. });
  11733. svr.set_exception_handler(
  11734. [](const Request &, Response &res, std::exception_ptr) {
  11735. res.status = StatusCode::InternalServerError_500;
  11736. res.set_content(std::string(1000, 'X'), "text/html");
  11737. });
  11738. auto port = svr.bind_to_any_port(HOST);
  11739. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11740. auto se = detail::scope_exit([&] {
  11741. svr.stop();
  11742. t.join();
  11743. ASSERT_FALSE(svr.is_running());
  11744. });
  11745. svr.wait_until_ready();
  11746. Client cli(HOST, port);
  11747. {
  11748. auto res = cli.Get("/sized");
  11749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11751. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11752. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11753. }
  11754. {
  11755. auto res = cli.Get("/chunked");
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11758. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11759. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11760. }
  11761. {
  11762. auto res = cli.Get("/throw");
  11763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11764. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11765. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11766. }
  11767. std::lock_guard<std::mutex> guard(released_mutex);
  11768. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11769. }
  11770. #endif
  11771. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11772. Server svr;
  11773. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11774. return sink.write(&"abc"[offset], length);
  11775. };
  11776. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11777. res.set_file_content("./www/dir/test.html");
  11778. res.set_content("body", "text/plain");
  11779. });
  11780. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11781. res.set_content(std::string(100, 'B'), "text/plain");
  11782. res.set_file_content("./www/dir/test.html");
  11783. });
  11784. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11785. res.set_content(std::string(100, 'B'), "text/plain");
  11786. res.set_content_provider(3, "text/x-provider", abc);
  11787. });
  11788. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11789. res.set_content_provider(3, "text/x-provider", abc);
  11790. res.set_content(std::string(100, 'B'), "text/plain");
  11791. });
  11792. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11793. res.set_content_provider(3, "text/x-provider", abc);
  11794. res.set_file_content("./www/dir/test.html", "text/x-file");
  11795. });
  11796. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11797. res.set_file_content("./www/dir/test.html");
  11798. res.set_header("Content-Type", "text/x-handler");
  11799. });
  11800. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11801. res.set_content_provider(3, "text/plain", abc);
  11802. res.body = "direct";
  11803. });
  11804. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11805. res.set_file_content("./www/dir/test.html");
  11806. res.body = "direct";
  11807. });
  11808. auto port = svr.bind_to_any_port(HOST);
  11809. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11810. auto se = detail::scope_exit([&] {
  11811. svr.stop();
  11812. t.join();
  11813. ASSERT_FALSE(svr.is_running());
  11814. });
  11815. svr.wait_until_ready();
  11816. Client cli(HOST, port);
  11817. auto expect_body = [&](const char *path, const std::string &body,
  11818. const std::string &type) {
  11819. // Uncompressed, so Content-Length can be compared with the body.
  11820. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11821. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11822. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11823. EXPECT_EQ(body, res->body) << path;
  11824. EXPECT_EQ(std::to_string(body.size()),
  11825. res->get_header_value("Content-Length"))
  11826. << path;
  11827. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11828. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11829. };
  11830. expect_body("/file-then-body", "body", "text/plain");
  11831. expect_body("/body-then-file", "test.html", "text/html");
  11832. expect_body("/body-then-provider", "abc", "text/x-provider");
  11833. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11834. expect_body("/provider-then-file", "test.html", "text/x-file");
  11835. expect_body("/file-then-header", "test.html", "text/x-handler");
  11836. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11837. expect_body("/file-then-direct-body", "direct", "text/plain");
  11838. // Ranges are checked against the body, not the dropped provider.
  11839. {
  11840. auto res = cli.Get("/provider-then-direct-body",
  11841. Headers{{make_range_header({{1, 2}})}});
  11842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11844. EXPECT_EQ("ir", res->body);
  11845. }
  11846. {
  11847. auto res = cli.Get("/file-then-direct-body",
  11848. Headers{{make_range_header({{7, 8}})}});
  11849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11850. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11851. }
  11852. }
  11853. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11854. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11855. const char *path = "./truncated_while_served.txt";
  11856. const size_t size = 32 * 1024 * 1024;
  11857. {
  11858. std::ofstream f(path, std::ios::binary);
  11859. f << std::string(size, 'x');
  11860. }
  11861. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11862. // Over TLS, where the bytes are encrypted in this process rather than
  11863. // copied by send().
  11864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11865. svr.Get("/file", [&](const Request &, Response &res) {
  11866. res.set_file_content(path, "text/plain");
  11867. });
  11868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11869. auto se = detail::scope_exit([&] {
  11870. svr.stop();
  11871. thread.join();
  11872. ASSERT_FALSE(svr.is_running());
  11873. });
  11874. svr.wait_until_ready();
  11875. // The file shrinks once the first bytes are in, as a rewrite in place
  11876. // would, and reading the mapping past its new end used to raise SIGBUS.
  11877. SSLClient cli(HOST, PORT);
  11878. cli.enable_server_certificate_verification(false);
  11879. size_t received = 0;
  11880. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11881. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11882. received += len;
  11883. return true;
  11884. });
  11885. EXPECT_FALSE(res);
  11886. EXPECT_LT(received, size);
  11887. }
  11888. #endif
  11889. // Forward declaration (see the base64_encode note).
  11890. namespace httplib {
  11891. namespace detail {
  11892. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11893. const std::string &content_type,
  11894. EncodingType encoding);
  11895. } // namespace detail
  11896. } // namespace httplib
  11897. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11898. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11899. ASSERT_TRUE(mm->is_open());
  11900. Response res;
  11901. detail::set_file_content_provider(res, mm, "text/html",
  11902. detail::EncodingType::None);
  11903. std::string out;
  11904. DataSink sink;
  11905. sink.write = [&](const char *d, size_t l) {
  11906. out.append(d, l);
  11907. return true;
  11908. };
  11909. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11910. EXPECT_EQ("test.html", out);
  11911. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11912. EXPECT_EQ("test.html", out);
  11913. }
  11914. TEST(LongPollingTest, ClientCloseDetection) {
  11915. Server svr;
  11916. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11917. res.set_chunked_content_provider(
  11918. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11919. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11920. sink.os << "hello";
  11921. auto count = 10;
  11922. while (count > 0 && sink.is_writable()) {
  11923. this_thread::sleep_for(chrono::milliseconds(10));
  11924. count--;
  11925. }
  11926. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11927. return true;
  11928. });
  11929. });
  11930. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11931. auto se = detail::scope_exit([&] {
  11932. svr.stop();
  11933. listen_thread.join();
  11934. ASSERT_FALSE(svr.is_running());
  11935. });
  11936. svr.wait_until_ready();
  11937. Client cli("localhost", PORT);
  11938. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11939. EXPECT_EQ("hello", string(data, data_length));
  11940. return false; // close the socket immediately.
  11941. });
  11942. ASSERT_FALSE(res);
  11943. }
  11944. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11945. Server svr;
  11946. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11947. res.set_chunked_content_provider(
  11948. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11949. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11950. sink.os << "hello";
  11951. EXPECT_TRUE(sink.os.good());
  11952. // Wait for the client to close the connection
  11953. auto count = 10;
  11954. while (count > 0 && sink.is_writable()) {
  11955. this_thread::sleep_for(chrono::milliseconds(10));
  11956. count--;
  11957. }
  11958. // After client disconnect, write repeatedly until the socket
  11959. // write actually fails (small writes may be absorbed by the
  11960. // kernel buffer)
  11961. std::string chunk(1024, 'x');
  11962. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11963. sink.os << chunk;
  11964. }
  11965. EXPECT_TRUE(sink.os.fail());
  11966. return true;
  11967. });
  11968. });
  11969. auto port = svr.bind_to_any_port("localhost");
  11970. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11971. auto se = detail::scope_exit([&] {
  11972. svr.stop();
  11973. listen_thread.join();
  11974. ASSERT_FALSE(svr.is_running());
  11975. });
  11976. svr.wait_until_ready();
  11977. Client cli("localhost", port);
  11978. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11979. EXPECT_EQ("hello", string(data, data_length));
  11980. return false; // close the socket immediately.
  11981. });
  11982. ASSERT_FALSE(res);
  11983. }
  11984. TEST(GetWithParametersTest, GetWithParameters) {
  11985. Server svr;
  11986. svr.Get("/", [&](const Request &req, Response &) {
  11987. EXPECT_EQ("world", req.get_param_value("hello"));
  11988. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11989. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11990. });
  11991. svr.Get("/params", [&](const Request &req, Response &) {
  11992. EXPECT_EQ("world", req.get_param_value("hello"));
  11993. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11994. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11995. });
  11996. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11997. EXPECT_EQ("resource-id", req.matches[1]);
  11998. EXPECT_EQ("foo", req.get_param_value("param1"));
  11999. EXPECT_EQ("bar", req.get_param_value("param2"));
  12000. });
  12001. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12002. EXPECT_EQ("user-id", req.path_params.at("id"));
  12003. EXPECT_EQ("foo", req.get_param_value("param1"));
  12004. EXPECT_EQ("bar", req.get_param_value("param2"));
  12005. });
  12006. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12007. auto se = detail::scope_exit([&] {
  12008. svr.stop();
  12009. listen_thread.join();
  12010. ASSERT_FALSE(svr.is_running());
  12011. });
  12012. svr.wait_until_ready();
  12013. {
  12014. Client cli(HOST, PORT);
  12015. Params params;
  12016. params.emplace("hello", "world");
  12017. params.emplace("hello2", "world2");
  12018. params.emplace("hello3", "world3");
  12019. auto res = cli.Get("/", params, Headers{});
  12020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12021. EXPECT_EQ(StatusCode::OK_200, res->status);
  12022. }
  12023. {
  12024. Client cli(HOST, PORT);
  12025. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12027. EXPECT_EQ(StatusCode::OK_200, res->status);
  12028. }
  12029. {
  12030. Client cli(HOST, PORT);
  12031. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12033. EXPECT_EQ(StatusCode::OK_200, res->status);
  12034. }
  12035. {
  12036. Client cli(HOST, PORT);
  12037. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12039. EXPECT_EQ(StatusCode::OK_200, res->status);
  12040. }
  12041. }
  12042. TEST(GetWithParametersTest, GetWithParameters2) {
  12043. Server svr;
  12044. svr.Get("/", [&](const Request &req, Response &res) {
  12045. auto text = req.get_param_value("hello");
  12046. res.set_content(text, "text/plain");
  12047. });
  12048. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12049. auto se = detail::scope_exit([&] {
  12050. svr.stop();
  12051. listen_thread.join();
  12052. ASSERT_FALSE(svr.is_running());
  12053. });
  12054. svr.wait_until_ready();
  12055. Client cli("localhost", PORT);
  12056. Params params;
  12057. params.emplace("hello", "world");
  12058. std::string body;
  12059. auto res = cli.Get("/", params, Headers{},
  12060. [&](const char *data, size_t data_length) {
  12061. body.append(data, data_length);
  12062. return true;
  12063. });
  12064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12065. EXPECT_EQ(StatusCode::OK_200, res->status);
  12066. EXPECT_EQ("world", body);
  12067. }
  12068. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12069. Server svr;
  12070. svr.Get("/search", [&](const Request &req, Response &res) {
  12071. auto q = req.get_param_value("q");
  12072. res.set_content(q, "text/plain");
  12073. });
  12074. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12075. auto se = detail::scope_exit([&] {
  12076. svr.stop();
  12077. listen_thread.join();
  12078. ASSERT_FALSE(svr.is_running());
  12079. });
  12080. svr.wait_until_ready();
  12081. Client cli("localhost", PORT);
  12082. // Verify that Get(path, params) works without requiring Headers argument
  12083. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12085. EXPECT_EQ(StatusCode::OK_200, res->status);
  12086. EXPECT_EQ("cpp-httplib", res->body);
  12087. }
  12088. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12089. auto host = "httpbingo.org";
  12090. auto path = std::string{"/range/32"};
  12091. #ifdef CPPHTTPLIB_SSL_ENABLED
  12092. SSLClient cli(host);
  12093. #else
  12094. Client cli(host);
  12095. #endif
  12096. cli.set_default_headers({make_range_header({{1, 10}})});
  12097. cli.set_connection_timeout(5);
  12098. {
  12099. auto res = cli.Get(path);
  12100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12101. EXPECT_EQ("bcdefghijk", res->body);
  12102. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12103. }
  12104. {
  12105. auto res = cli.Get(path);
  12106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12107. EXPECT_EQ("bcdefghijk", res->body);
  12108. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12109. }
  12110. }
  12111. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12112. Server svr;
  12113. svr.set_default_headers({{"Hello", "World"}});
  12114. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12115. res.set_content("ok", "text/plain");
  12116. });
  12117. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12118. auto se = detail::scope_exit([&] {
  12119. svr.stop();
  12120. listen_thread.join();
  12121. ASSERT_FALSE(svr.is_running());
  12122. });
  12123. svr.wait_until_ready();
  12124. Client cli("localhost", PORT);
  12125. auto res = cli.Get("/");
  12126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12127. EXPECT_EQ(StatusCode::OK_200, res->status);
  12128. EXPECT_EQ("ok", res->body);
  12129. EXPECT_EQ("World", res->get_header_value("Hello"));
  12130. }
  12131. #ifdef CPPHTTPLIB_SSL_ENABLED
  12132. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12134. ASSERT_TRUE(svr.is_valid());
  12135. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12136. std::this_thread::sleep_for(std::chrono::seconds(2));
  12137. res.set_content("a", "text/plain");
  12138. });
  12139. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12140. res.set_content("b", "text/plain");
  12141. });
  12142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12143. auto se = detail::scope_exit([&] {
  12144. svr.stop();
  12145. listen_thread.join();
  12146. ASSERT_FALSE(svr.is_running());
  12147. });
  12148. svr.wait_until_ready();
  12149. SSLClient cli("localhost", PORT);
  12150. cli.enable_server_certificate_verification(false);
  12151. cli.set_keep_alive(true);
  12152. cli.set_read_timeout(std::chrono::seconds(1));
  12153. auto resa = cli.Get("/a");
  12154. ASSERT_TRUE(!resa);
  12155. EXPECT_EQ(Error::Read, resa.error());
  12156. auto resb = cli.Get("/b");
  12157. ASSERT_TRUE(resb);
  12158. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12159. EXPECT_EQ("b", resb->body);
  12160. }
  12161. // Closing an idle keep-alive connection sends close_notify and returns. The
  12162. // server must not wait for the client's close_notify: an idle client never
  12163. // sends one, so the worker would be held until the read timeout expires, and
  12164. // stop() would wait for it.
  12165. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12167. ASSERT_TRUE(svr.is_valid());
  12168. svr.set_keep_alive_timeout(1);
  12169. svr.set_read_timeout(10, 0);
  12170. svr.Get("/", [](const Request &, Response &res) {
  12171. res.set_content("ok", "text/plain");
  12172. });
  12173. auto port = svr.bind_to_any_port(HOST);
  12174. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12175. auto se = detail::scope_exit([&] {
  12176. if (listen_thread.joinable()) {
  12177. svr.stop();
  12178. listen_thread.join();
  12179. }
  12180. });
  12181. svr.wait_until_ready();
  12182. SSLClient cli(HOST, port);
  12183. cli.enable_server_certificate_verification(false);
  12184. cli.set_keep_alive(true);
  12185. auto res = cli.Get("/");
  12186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12187. EXPECT_EQ(StatusCode::OK_200, res->status);
  12188. // Stay idle past the keep-alive timeout so the server closes the connection.
  12189. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12190. auto start = std::chrono::steady_clock::now();
  12191. svr.stop();
  12192. listen_thread.join();
  12193. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12194. std::chrono::steady_clock::now() - start)
  12195. .count();
  12196. EXPECT_LT(elapsed, 3000);
  12197. }
  12198. #endif
  12199. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12200. protected:
  12201. ServerTestWithAI_PASSIVE()
  12202. : cli_(HOST, PORT)
  12203. #ifdef CPPHTTPLIB_SSL_ENABLED
  12204. ,
  12205. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12206. #endif
  12207. {
  12208. #ifdef CPPHTTPLIB_SSL_ENABLED
  12209. cli_.enable_server_certificate_verification(false);
  12210. #endif
  12211. }
  12212. virtual void SetUp() {
  12213. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12214. res.set_content("Hello World!", "text/plain");
  12215. });
  12216. t_ = thread(
  12217. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12218. svr_.wait_until_ready();
  12219. }
  12220. virtual void TearDown() {
  12221. svr_.stop();
  12222. t_.join();
  12223. }
  12224. #ifdef CPPHTTPLIB_SSL_ENABLED
  12225. SSLClient cli_;
  12226. SSLServer svr_;
  12227. #else
  12228. Client cli_;
  12229. Server svr_;
  12230. #endif
  12231. thread t_;
  12232. };
  12233. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12234. auto res = cli_.Get("/hi");
  12235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12236. EXPECT_EQ(StatusCode::OK_200, res->status);
  12237. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12238. EXPECT_EQ("Hello World!", res->body);
  12239. }
  12240. class ServerUpDownTest : public ::testing::Test {
  12241. protected:
  12242. ServerUpDownTest() : cli_(HOST, PORT) {}
  12243. virtual void SetUp() {
  12244. t_ = thread([&]() {
  12245. svr_.bind_to_any_port(HOST);
  12246. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12247. ASSERT_TRUE(svr_.listen_after_bind());
  12248. });
  12249. svr_.wait_until_ready();
  12250. }
  12251. virtual void TearDown() {
  12252. svr_.stop();
  12253. t_.join();
  12254. }
  12255. Client cli_;
  12256. Server svr_;
  12257. thread t_;
  12258. };
  12259. TEST_F(ServerUpDownTest, QuickStartStop) {
  12260. // Should not crash, especially when run with
  12261. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12262. }
  12263. class PayloadMaxLengthTest : public ::testing::Test {
  12264. protected:
  12265. PayloadMaxLengthTest()
  12266. : cli_(HOST, PORT)
  12267. #ifdef CPPHTTPLIB_SSL_ENABLED
  12268. ,
  12269. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12270. #endif
  12271. {
  12272. #ifdef CPPHTTPLIB_SSL_ENABLED
  12273. cli_.enable_server_certificate_verification(false);
  12274. #endif
  12275. }
  12276. virtual void SetUp() {
  12277. svr_.set_payload_max_length(8);
  12278. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12279. res.set_content("test", "text/plain");
  12280. });
  12281. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12282. svr_.wait_until_ready();
  12283. }
  12284. virtual void TearDown() {
  12285. svr_.stop();
  12286. t_.join();
  12287. }
  12288. #ifdef CPPHTTPLIB_SSL_ENABLED
  12289. SSLClient cli_;
  12290. SSLServer svr_;
  12291. #else
  12292. Client cli_;
  12293. Server svr_;
  12294. #endif
  12295. thread t_;
  12296. };
  12297. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12298. auto res = cli_.Post("/test", "123456789", "text/plain");
  12299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12300. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12301. res = cli_.Post("/test", "12345678", "text/plain");
  12302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12303. EXPECT_EQ(StatusCode::OK_200, res->status);
  12304. }
  12305. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12306. // Test chunked encoding with payload exceeding the 8-byte limit
  12307. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12308. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12310. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12311. }
  12312. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12313. // Test chunked encoding with payload within the 8-byte limit
  12314. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12315. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12317. EXPECT_EQ(StatusCode::OK_200, res->status);
  12318. }
  12319. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12320. // Test using send_request to send chunked data exceeding payload limit
  12321. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12322. "Host: " +
  12323. std::string(HOST) + ":" + std::to_string(PORT) +
  12324. "\r\n"
  12325. "Transfer-Encoding: chunked\r\n"
  12326. "Connection: close\r\n"
  12327. "\r\n"
  12328. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12329. "0123456789\r\n"
  12330. "0\r\n" // End chunk
  12331. "\r\n";
  12332. std::string response;
  12333. bool result = send_request(1, chunked_request, &response);
  12334. if (!result) {
  12335. // If send_request fails, it might be because the server closed the
  12336. // connection due to payload limit enforcement, which is acceptable
  12337. SUCCEED()
  12338. << "Server rejected oversized chunked request (connection closed)";
  12339. } else {
  12340. // If we got a response, check if it's an error response or connection was
  12341. // closed early Short response length indicates connection was closed due to
  12342. // payload limit
  12343. if (response.length() <= 10) {
  12344. SUCCEED() << "Server closed connection for oversized chunked request";
  12345. } else {
  12346. // Check for error status codes
  12347. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12348. response.find("Payload Too Large") != std::string::npos ||
  12349. response.find("400") != std::string::npos);
  12350. }
  12351. }
  12352. }
  12353. class LargePayloadMaxLengthTest : public ::testing::Test {
  12354. protected:
  12355. LargePayloadMaxLengthTest()
  12356. : cli_(HOST, PORT)
  12357. #ifdef CPPHTTPLIB_SSL_ENABLED
  12358. ,
  12359. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12360. #endif
  12361. {
  12362. #ifdef CPPHTTPLIB_SSL_ENABLED
  12363. cli_.enable_server_certificate_verification(false);
  12364. #endif
  12365. }
  12366. virtual void SetUp() {
  12367. // Set 10MB payload limit
  12368. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12369. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12370. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12371. res.set_content("Large payload test", "text/plain");
  12372. });
  12373. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12374. svr_.wait_until_ready();
  12375. }
  12376. virtual void TearDown() {
  12377. svr_.stop();
  12378. t_.join();
  12379. }
  12380. #ifdef CPPHTTPLIB_SSL_ENABLED
  12381. SSLClient cli_;
  12382. SSLServer svr_;
  12383. #else
  12384. Client cli_;
  12385. Server svr_;
  12386. #endif
  12387. thread t_;
  12388. };
  12389. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12390. // Test chunked encoding with payload within 10MB limit
  12391. std::string medium_payload(5 * 1024 * 1024,
  12392. 'A'); // 5MB payload, within 10MB limit
  12393. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12395. EXPECT_EQ(StatusCode::OK_200, res->status);
  12396. }
  12397. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12398. // Test chunked encoding with payload exceeding 10MB limit
  12399. std::string large_payload(12 * 1024 * 1024,
  12400. 'B'); // 12MB payload, exceeds 10MB limit
  12401. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12402. // Server may either return 413 or close the connection
  12403. if (res) {
  12404. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12405. } else {
  12406. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12407. }
  12408. }
  12409. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12410. Server svr;
  12411. svr.Get("/", [](const Request &, Response &res) {
  12412. // Claims the most the client accepts, far more than it sends, then drops
  12413. // the connection.
  12414. res.set_content_provider(std::string().max_size(), "text/plain",
  12415. [](size_t, size_t, DataSink &sink) {
  12416. sink.write("abc", 3);
  12417. return false;
  12418. });
  12419. });
  12420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12421. auto se = detail::scope_exit([&] {
  12422. svr.stop();
  12423. thread.join();
  12424. ASSERT_FALSE(svr.is_running());
  12425. });
  12426. svr.wait_until_ready();
  12427. Client cli(HOST, PORT);
  12428. cli.set_payload_max_length(0);
  12429. EXPECT_FALSE(cli.Get("/"));
  12430. }
  12431. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12432. // Stream API does, not as a plain read failure
  12433. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12434. Server svr;
  12435. svr.Get("/big", [](const Request &, Response &res) {
  12436. res.set_content(std::string(100000, 'b'), "text/plain");
  12437. });
  12438. auto port = svr.bind_to_any_port(HOST);
  12439. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12440. auto se = detail::scope_exit([&] {
  12441. svr.stop();
  12442. thread.join();
  12443. });
  12444. svr.wait_until_ready();
  12445. Client cli(HOST, port);
  12446. cli.set_payload_max_length(1000);
  12447. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12448. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12449. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12450. [](const char *, size_t) { return true; });
  12451. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12452. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12453. // Small on the wire, over the limit once decompressed
  12454. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12455. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12456. #endif
  12457. }
  12458. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12459. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12460. // path.
  12461. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12462. Server svr;
  12463. const size_t LIMIT = 64 * 1024; // 64KB
  12464. svr.set_payload_max_length(LIMIT);
  12465. size_t total = 0;
  12466. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12467. const ContentReader &content_reader) {
  12468. content_reader([&](const char * /*data*/, size_t len) {
  12469. total += len;
  12470. return true;
  12471. });
  12472. res.status = 200;
  12473. res.set_content("stream_ok", "text/plain");
  12474. });
  12475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12476. auto se = detail::scope_exit([&] {
  12477. svr.stop();
  12478. thread.join();
  12479. ASSERT_FALSE(svr.is_running());
  12480. });
  12481. svr.wait_until_ready();
  12482. // Prepare 256KB raw data and gzip-compress it
  12483. std::string raw(256 * 1024, 'A');
  12484. std::string gz;
  12485. {
  12486. z_stream zs{};
  12487. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12488. Z_DEFAULT_STRATEGY);
  12489. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12490. zs.avail_in = static_cast<uInt>(raw.size());
  12491. char outbuf[4096];
  12492. int ret;
  12493. do {
  12494. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12495. zs.avail_out = sizeof(outbuf);
  12496. ret = deflate(&zs, Z_FINISH);
  12497. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12498. } while (ret != Z_STREAM_END);
  12499. deflateEnd(&zs);
  12500. }
  12501. Client cli(HOST, PORT);
  12502. cli.set_connection_timeout(std::chrono::seconds(5));
  12503. Headers headers = {{"Content-Encoding", "gzip"}};
  12504. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12505. "application/octet-stream");
  12506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12507. // Server must reject oversized decompressed payloads with 413.
  12508. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12509. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12510. EXPECT_LE(total, LIMIT);
  12511. }
  12512. #endif
  12513. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12514. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12515. // the payload must be passed through untouched instead of being rejected.
  12516. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12517. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12518. Server svr;
  12519. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12520. res.set_content(body, "image/jpeg");
  12521. res.set_header("Content-Encoding", "UTF-8");
  12522. });
  12523. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12524. res.set_content(body, "image/jpeg");
  12525. res.set_header("Content-Encoding", "identity");
  12526. });
  12527. svr.Post("/echo", [](const Request &req, Response &res) {
  12528. res.set_content(req.body, "image/jpeg");
  12529. });
  12530. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12531. auto se = detail::scope_exit([&] {
  12532. svr.stop();
  12533. t.join();
  12534. ASSERT_FALSE(svr.is_running());
  12535. });
  12536. svr.wait_until_ready();
  12537. Client cli(HOST, PORT);
  12538. {
  12539. auto res = cli.Get("/image");
  12540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12541. EXPECT_EQ(StatusCode::OK_200, res->status);
  12542. EXPECT_EQ(body, res->body);
  12543. }
  12544. {
  12545. auto res = cli.Get("/identity");
  12546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12547. EXPECT_EQ(StatusCode::OK_200, res->status);
  12548. EXPECT_EQ(body, res->body);
  12549. }
  12550. {
  12551. // The same applies to a request body reaching the server.
  12552. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12553. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12555. EXPECT_EQ(StatusCode::OK_200, res->status);
  12556. EXPECT_EQ(body, res->body);
  12557. }
  12558. }
  12559. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12560. // gzip-encoded response even when the build has no zlib support.
  12561. static const char GZIPPED_HELLO_WORLD[] = {
  12562. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12563. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12564. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12565. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12566. // A content coding is a whole token, not something the field value merely
  12567. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12568. // as "fibre" look like Brotli, and turned a multi-coding value like
  12569. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12570. // it was never meant to see.
  12571. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12572. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12573. Server svr;
  12574. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12575. res.set_content(body, "image/jpeg");
  12576. res.set_header("Content-Encoding", "fibre");
  12577. });
  12578. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12579. res.set_content(body, "image/jpeg");
  12580. res.set_header("Content-Encoding", "gzip, br");
  12581. });
  12582. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12583. res.set_content(body, "image/jpeg");
  12584. res.set_header("Content-Encoding", "x-zstd-ish");
  12585. });
  12586. auto port = svr.bind_to_any_port(HOST);
  12587. thread t = thread([&]() { svr.listen_after_bind(); });
  12588. auto se = detail::scope_exit([&] {
  12589. svr.stop();
  12590. t.join();
  12591. ASSERT_FALSE(svr.is_running());
  12592. });
  12593. svr.wait_until_ready();
  12594. Client cli(HOST, port);
  12595. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12596. auto res = cli.Get(path);
  12597. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12598. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12599. // Not a coding we recognize, so the payload comes back untouched
  12600. EXPECT_EQ(body, res->body) << path;
  12601. }
  12602. }
  12603. // A content coding cpp-httplib recognizes but was not built with must be
  12604. // reported as such. Handing the still-compressed payload back to the caller
  12605. // would silently corrupt it.
  12606. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12607. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12608. Server svr;
  12609. // "image/jpeg" keeps the server from applying a content coding of its own,
  12610. // so the hand-crafted Content-Encoding below survives.
  12611. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12612. res.set_content(gzipped, "image/jpeg");
  12613. res.set_header("Content-Encoding", "gzip");
  12614. });
  12615. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12616. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12617. res.set_content(gzipped, "image/jpeg");
  12618. res.set_header("Content-Encoding", "GZIP");
  12619. });
  12620. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12621. auto se = detail::scope_exit([&] {
  12622. svr.stop();
  12623. t.join();
  12624. ASSERT_FALSE(svr.is_running());
  12625. });
  12626. svr.wait_until_ready();
  12627. Client cli(HOST, PORT);
  12628. {
  12629. auto res = cli.Get("/gzipped");
  12630. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12632. EXPECT_EQ("Hello World!", res->body);
  12633. #else
  12634. ASSERT_FALSE(res);
  12635. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12636. #endif
  12637. }
  12638. {
  12639. // open_stream() must behave the same way.
  12640. auto handle = cli.open_stream("GET", "/gzipped");
  12641. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12642. ASSERT_TRUE(handle.is_valid());
  12643. std::string received;
  12644. char buf[256];
  12645. ssize_t n;
  12646. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12647. received.append(buf, static_cast<size_t>(n));
  12648. }
  12649. EXPECT_EQ("Hello World!", received);
  12650. #else
  12651. EXPECT_FALSE(handle.is_valid());
  12652. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12653. #endif
  12654. }
  12655. {
  12656. // A differently-cased coding must not be mistaken for an unknown one, or
  12657. // the body would be handed back still compressed.
  12658. auto res = cli.Get("/gzipped-uppercase");
  12659. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12661. EXPECT_EQ("Hello World!", res->body);
  12662. #else
  12663. ASSERT_FALSE(res);
  12664. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12665. #endif
  12666. }
  12667. }
  12668. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12669. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12670. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12671. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12672. // body a second time and appending a second Content-Encoding field line, so
  12673. // clients that decode one coding per listed value handed back raw gzip bytes.
  12674. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12675. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12676. Server svr;
  12677. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12678. // keeps the server from applying a coding of its own.
  12679. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12680. res.set_content(gzipped, "text/plain");
  12681. res.set_header("Content-Encoding", "gzip");
  12682. });
  12683. auto port = svr.bind_to_any_port(HOST);
  12684. thread t = thread([&]() { svr.listen_after_bind(); });
  12685. auto se = detail::scope_exit([&] {
  12686. svr.stop();
  12687. t.join();
  12688. ASSERT_FALSE(svr.is_running());
  12689. });
  12690. svr.wait_until_ready();
  12691. Client cli(HOST, port);
  12692. Headers headers = {{"Accept-Encoding", "gzip"}};
  12693. auto res = cli.Get("/pre-gzipped", headers);
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. EXPECT_EQ(StatusCode::OK_200, res->status);
  12696. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12697. EXPECT_EQ("Hello World!", res->body);
  12698. }
  12699. // set_compress(false) sends every handler response as it is, buffered or
  12700. // streamed
  12701. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12702. const std::string text(1000, 'a');
  12703. Server svr;
  12704. svr.set_compress(false);
  12705. svr.Get("/buffered", [&](const Request &, Response &res) {
  12706. res.set_content(text, "text/plain");
  12707. });
  12708. svr.Get("/streamed", [&](const Request &, Response &res) {
  12709. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12710. sink.write(text.data(), text.size());
  12711. sink.done();
  12712. return true;
  12713. });
  12714. });
  12715. auto port = svr.bind_to_any_port(HOST);
  12716. ASSERT_LT(0, port);
  12717. thread t = thread([&] { svr.listen_after_bind(); });
  12718. auto se = detail::scope_exit([&] {
  12719. svr.stop();
  12720. t.join();
  12721. ASSERT_FALSE(svr.is_running());
  12722. });
  12723. svr.wait_until_ready();
  12724. Client cli(HOST, port);
  12725. cli.set_decompress(false);
  12726. for (auto path : {"/buffered", "/streamed"}) {
  12727. SCOPED_TRACE(path);
  12728. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12730. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12731. EXPECT_EQ(text, res->body);
  12732. }
  12733. }
  12734. // A chunked provider settles its coding where the headers are written and
  12735. // reuses it at write time. Both ends of that have to hold: a handler's own
  12736. // Content-Encoding suppresses the coding, and a response without one is still
  12737. // compressed as it always was.
  12738. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12739. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12740. const std::string plain = "Hello World! Hello World! Hello World!";
  12741. Server svr;
  12742. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12743. res.set_header("Content-Encoding", "gzip");
  12744. res.set_chunked_content_provider(
  12745. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12746. sink.write(gzipped.data(), gzipped.size());
  12747. sink.done();
  12748. return true;
  12749. });
  12750. });
  12751. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12752. res.set_chunked_content_provider(
  12753. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12754. sink.write(plain.data(), plain.size());
  12755. sink.done();
  12756. return true;
  12757. });
  12758. });
  12759. auto port = svr.bind_to_any_port(HOST);
  12760. thread t = thread([&]() { svr.listen_after_bind(); });
  12761. auto se = detail::scope_exit([&] {
  12762. svr.stop();
  12763. t.join();
  12764. ASSERT_FALSE(svr.is_running());
  12765. });
  12766. svr.wait_until_ready();
  12767. Client cli(HOST, port);
  12768. Headers headers = {{"Accept-Encoding", "gzip"}};
  12769. {
  12770. auto res = cli.Get("/pre-gzipped", headers);
  12771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12772. EXPECT_EQ(StatusCode::OK_200, res->status);
  12773. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12774. EXPECT_EQ("Hello World!", res->body);
  12775. }
  12776. {
  12777. auto res = cli.Get("/negotiated", headers);
  12778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12779. EXPECT_EQ(StatusCode::OK_200, res->status);
  12780. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12781. EXPECT_EQ(plain, res->body);
  12782. }
  12783. }
  12784. #endif
  12785. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12786. // the same message as the comma-joined one, so both have to be read the same
  12787. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12788. // single gzip coding, and a body the sender says was encoded twice was handed
  12789. // back after one pass, still compressed but presented as decoded.
  12790. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12791. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12792. Server svr;
  12793. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12794. res.set_content(body, "image/jpeg");
  12795. res.headers.emplace("Content-Encoding", "gzip");
  12796. res.headers.emplace("Content-Encoding", "gzip");
  12797. });
  12798. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12799. res.set_content(body, "image/jpeg");
  12800. res.set_header("Content-Encoding", "gzip, gzip");
  12801. });
  12802. auto port = svr.bind_to_any_port(HOST);
  12803. thread t = thread([&]() { svr.listen_after_bind(); });
  12804. auto se = detail::scope_exit([&] {
  12805. svr.stop();
  12806. t.join();
  12807. ASSERT_FALSE(svr.is_running());
  12808. });
  12809. svr.wait_until_ready();
  12810. Client cli(HOST, port);
  12811. // Two codings is not something cpp-httplib decodes, so both representations
  12812. // take the pass-through path rather than one of them being gunzipped once.
  12813. for (const char *path : {"/split", "/joined"}) {
  12814. auto res = cli.Get(path);
  12815. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12816. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12817. EXPECT_EQ(body, res->body) << path;
  12818. }
  12819. }
  12820. // Regression test for DoS vulnerability: a malicious server sending a response
  12821. // without Content-Length header must not cause unbounded memory consumption on
  12822. // the client side. The client should stop reading after a reasonable limit,
  12823. // similar to the server-side set_payload_max_length protection.
  12824. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12825. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12826. #ifndef _WIN32
  12827. signal(SIGPIPE, SIG_IGN);
  12828. #endif
  12829. auto server_thread = std::thread([] {
  12830. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12831. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12832. default_socket_options(srv);
  12833. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12834. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12835. sockaddr_in addr{};
  12836. addr.sin_family = AF_INET;
  12837. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12838. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12839. int opt = 1;
  12840. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12841. #ifdef _WIN32
  12842. reinterpret_cast<const char *>(&opt),
  12843. #else
  12844. &opt,
  12845. #endif
  12846. sizeof(opt));
  12847. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12848. ::listen(srv, 1);
  12849. sockaddr_in cli_addr{};
  12850. socklen_t cli_len = sizeof(cli_addr);
  12851. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12852. if (cli != INVALID_SOCKET) {
  12853. char buf[4096];
  12854. ::recv(cli, buf, sizeof(buf), 0);
  12855. // Malicious response: no Content-Length, no chunked encoding
  12856. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12857. "Connection: close\r\n"
  12858. "\r\n";
  12859. ::send(cli,
  12860. #ifdef _WIN32
  12861. static_cast<const char *>(response_header.c_str()),
  12862. static_cast<int>(response_header.size()),
  12863. #else
  12864. response_header.c_str(), response_header.size(),
  12865. #endif
  12866. 0);
  12867. // Send 10MB of data
  12868. std::string chunk(64 * 1024, 'A');
  12869. size_t total_sent = 0;
  12870. while (total_sent < MALICIOUS_DATA_SIZE) {
  12871. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12872. auto sent = ::send(cli,
  12873. #ifdef _WIN32
  12874. static_cast<const char *>(chunk.c_str()),
  12875. static_cast<int>(to_send),
  12876. #else
  12877. chunk.c_str(), to_send,
  12878. #endif
  12879. 0);
  12880. if (sent <= 0) break;
  12881. total_sent += static_cast<size_t>(sent);
  12882. }
  12883. detail::close_socket(cli);
  12884. }
  12885. detail::close_socket(srv);
  12886. });
  12887. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12888. size_t total_read = 0;
  12889. {
  12890. Client cli("127.0.0.1", PORT + 2);
  12891. cli.set_read_timeout(5, 0);
  12892. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12893. auto stream = cli.open_stream("GET", "/malicious");
  12894. ASSERT_TRUE(stream.is_valid());
  12895. char buffer[64 * 1024];
  12896. ssize_t n;
  12897. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12898. total_read += static_cast<size_t>(n);
  12899. }
  12900. } // StreamHandle and Client destroyed here, closing the socket
  12901. server_thread.join();
  12902. // With set_payload_max_length, the client must stop reading before consuming
  12903. // all 10MB. The read loop should be cut off at or near the configured limit.
  12904. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12905. << "Client read " << total_read << " bytes, exceeding the configured "
  12906. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12907. }
  12908. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12909. // the entire response body without truncation.
  12910. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12911. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12912. #ifndef _WIN32
  12913. signal(SIGPIPE, SIG_IGN);
  12914. #endif
  12915. auto server_thread = std::thread([] {
  12916. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12917. default_socket_options(srv);
  12918. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12919. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12920. sockaddr_in addr{};
  12921. addr.sin_family = AF_INET;
  12922. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12923. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12924. int opt = 1;
  12925. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12926. #ifdef _WIN32
  12927. reinterpret_cast<const char *>(&opt),
  12928. #else
  12929. &opt,
  12930. #endif
  12931. sizeof(opt));
  12932. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12933. ::listen(srv, 1);
  12934. sockaddr_in cli_addr{};
  12935. socklen_t cli_len = sizeof(cli_addr);
  12936. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12937. if (cli != INVALID_SOCKET) {
  12938. char buf[4096];
  12939. ::recv(cli, buf, sizeof(buf), 0);
  12940. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12941. "Connection: close\r\n"
  12942. "\r\n";
  12943. ::send(cli,
  12944. #ifdef _WIN32
  12945. static_cast<const char *>(response_header.c_str()),
  12946. static_cast<int>(response_header.size()),
  12947. #else
  12948. response_header.c_str(), response_header.size(),
  12949. #endif
  12950. 0);
  12951. std::string chunk(64 * 1024, 'A');
  12952. size_t total_sent = 0;
  12953. while (total_sent < DATA_SIZE) {
  12954. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12955. auto sent = ::send(cli,
  12956. #ifdef _WIN32
  12957. static_cast<const char *>(chunk.c_str()),
  12958. static_cast<int>(to_send),
  12959. #else
  12960. chunk.c_str(), to_send,
  12961. #endif
  12962. 0);
  12963. if (sent <= 0) break;
  12964. total_sent += static_cast<size_t>(sent);
  12965. }
  12966. #ifdef _WIN32
  12967. ::shutdown(cli, SD_SEND);
  12968. #else
  12969. ::shutdown(cli, SHUT_WR);
  12970. #endif
  12971. // Drain until the client closes its end, ensuring all data is delivered
  12972. char drain[1024];
  12973. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12974. detail::close_socket(cli);
  12975. }
  12976. detail::close_socket(srv);
  12977. });
  12978. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12979. size_t total_read = 0;
  12980. {
  12981. Client cli("127.0.0.1", PORT + 2);
  12982. cli.set_read_timeout(5, 0);
  12983. cli.set_payload_max_length(0); // 0 means no limit
  12984. auto stream = cli.open_stream("GET", "/data");
  12985. ASSERT_TRUE(stream.is_valid());
  12986. char buffer[64 * 1024];
  12987. ssize_t n;
  12988. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12989. total_read += static_cast<size_t>(n);
  12990. }
  12991. }
  12992. server_thread.join();
  12993. EXPECT_EQ(total_read, DATA_SIZE)
  12994. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12995. << " bytes without truncation, but only read " << total_read << " bytes.";
  12996. }
  12997. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12998. // enormous Content-Length must not cause the client to pre-allocate a huge
  12999. // response body buffer. The reservation is capped at payload_max_length_, and
  13000. // the read itself fails when the body exceeds the limit.
  13001. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13002. #ifndef _WIN32
  13003. signal(SIGPIPE, SIG_IGN);
  13004. #endif
  13005. auto server_thread = std::thread([] {
  13006. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13007. default_socket_options(srv);
  13008. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13009. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13010. sockaddr_in addr{};
  13011. addr.sin_family = AF_INET;
  13012. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13013. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13014. int opt = 1;
  13015. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13016. #ifdef _WIN32
  13017. reinterpret_cast<const char *>(&opt),
  13018. #else
  13019. &opt,
  13020. #endif
  13021. sizeof(opt));
  13022. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13023. ::listen(srv, 1);
  13024. sockaddr_in cli_addr{};
  13025. socklen_t cli_len = sizeof(cli_addr);
  13026. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13027. if (cli != INVALID_SOCKET) {
  13028. char buf[4096];
  13029. ::recv(cli, buf, sizeof(buf), 0);
  13030. // Malicious response: claim a 20GB body but send only a tiny payload.
  13031. std::string response = "HTTP/1.1 200 OK\r\n"
  13032. "Content-Length: 20000000000\r\n"
  13033. "\r\n"
  13034. "abc";
  13035. ::send(cli,
  13036. #ifdef _WIN32
  13037. static_cast<const char *>(response.c_str()),
  13038. static_cast<int>(response.size()),
  13039. #else
  13040. response.c_str(), response.size(),
  13041. #endif
  13042. 0);
  13043. detail::close_socket(cli);
  13044. }
  13045. detail::close_socket(srv);
  13046. });
  13047. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13048. {
  13049. Client cli("127.0.0.1", PORT + 2);
  13050. cli.set_read_timeout(5, 0);
  13051. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13052. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13053. // (server claims more bytes than payload_max_length permits), but it must
  13054. // not exhaust memory before getting there.
  13055. auto res = cli.Get("/malicious");
  13056. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13057. }
  13058. server_thread.join();
  13059. }
  13060. // Verify that content_receiver bypasses the default payload_max_length,
  13061. // allowing streaming downloads larger than 100MB without requiring an explicit
  13062. // set_payload_max_length call.
  13063. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13064. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13065. #ifndef _WIN32
  13066. signal(SIGPIPE, SIG_IGN);
  13067. #endif
  13068. auto server_thread = std::thread([] {
  13069. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13070. default_socket_options(srv);
  13071. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13072. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13073. sockaddr_in addr{};
  13074. addr.sin_family = AF_INET;
  13075. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13076. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13077. int opt = 1;
  13078. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13079. #ifdef _WIN32
  13080. reinterpret_cast<const char *>(&opt),
  13081. #else
  13082. &opt,
  13083. #endif
  13084. sizeof(opt));
  13085. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13086. ::listen(srv, 1);
  13087. sockaddr_in cli_addr{};
  13088. socklen_t cli_len = sizeof(cli_addr);
  13089. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13090. if (cli != INVALID_SOCKET) {
  13091. char buf[4096];
  13092. ::recv(cli, buf, sizeof(buf), 0);
  13093. // Response with Content-Length larger than default 100MB limit
  13094. auto content_length = std::to_string(DATA_SIZE);
  13095. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13096. "Content-Length: " +
  13097. content_length +
  13098. "\r\n"
  13099. "Connection: close\r\n"
  13100. "\r\n";
  13101. ::send(cli,
  13102. #ifdef _WIN32
  13103. static_cast<const char *>(response_header.c_str()),
  13104. static_cast<int>(response_header.size()),
  13105. #else
  13106. response_header.c_str(), response_header.size(),
  13107. #endif
  13108. 0);
  13109. std::string chunk(64 * 1024, 'A');
  13110. size_t total_sent = 0;
  13111. while (total_sent < DATA_SIZE) {
  13112. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13113. auto sent = ::send(cli,
  13114. #ifdef _WIN32
  13115. static_cast<const char *>(chunk.c_str()),
  13116. static_cast<int>(to_send),
  13117. #else
  13118. chunk.c_str(), to_send,
  13119. #endif
  13120. 0);
  13121. if (sent <= 0) break;
  13122. total_sent += static_cast<size_t>(sent);
  13123. }
  13124. detail::close_socket(cli);
  13125. }
  13126. detail::close_socket(srv);
  13127. });
  13128. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13129. size_t total_received = 0;
  13130. {
  13131. Client cli("127.0.0.1", PORT + 2);
  13132. cli.set_read_timeout(10, 0);
  13133. // Do NOT call set_payload_max_length — use the default 100MB limit
  13134. auto res =
  13135. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13136. total_received += data_length;
  13137. return true;
  13138. });
  13139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13140. EXPECT_EQ(StatusCode::OK_200, res->status);
  13141. }
  13142. server_thread.join();
  13143. EXPECT_EQ(total_received, DATA_SIZE)
  13144. << "With content_receiver, the client should read all " << DATA_SIZE
  13145. << " bytes despite the default 100MB payload_max_length, but only read "
  13146. << total_received << " bytes.";
  13147. }
  13148. // Verify that an explicit set_payload_max_length smaller than the response is
  13149. // enforced even when a content_receiver is used.
  13150. TEST(ClientVulnerabilityTest,
  13151. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13152. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13153. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13154. #ifndef _WIN32
  13155. signal(SIGPIPE, SIG_IGN);
  13156. #endif
  13157. auto server_thread = std::thread([] {
  13158. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13159. default_socket_options(srv);
  13160. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13161. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13162. sockaddr_in addr{};
  13163. addr.sin_family = AF_INET;
  13164. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13165. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13166. int opt = 1;
  13167. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13168. #ifdef _WIN32
  13169. reinterpret_cast<const char *>(&opt),
  13170. #else
  13171. &opt,
  13172. #endif
  13173. sizeof(opt));
  13174. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13175. ::listen(srv, 1);
  13176. sockaddr_in cli_addr{};
  13177. socklen_t cli_len = sizeof(cli_addr);
  13178. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13179. if (cli != INVALID_SOCKET) {
  13180. char buf[4096];
  13181. ::recv(cli, buf, sizeof(buf), 0);
  13182. auto content_length = std::to_string(DATA_SIZE);
  13183. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13184. "Content-Length: " +
  13185. content_length +
  13186. "\r\n"
  13187. "Connection: close\r\n"
  13188. "\r\n";
  13189. ::send(cli,
  13190. #ifdef _WIN32
  13191. static_cast<const char *>(response_header.c_str()),
  13192. static_cast<int>(response_header.size()),
  13193. #else
  13194. response_header.c_str(), response_header.size(),
  13195. #endif
  13196. 0);
  13197. std::string chunk(64 * 1024, 'A');
  13198. size_t total_sent = 0;
  13199. while (total_sent < DATA_SIZE) {
  13200. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13201. auto sent = ::send(cli,
  13202. #ifdef _WIN32
  13203. static_cast<const char *>(chunk.c_str()),
  13204. static_cast<int>(to_send),
  13205. #else
  13206. chunk.c_str(), to_send,
  13207. #endif
  13208. 0);
  13209. if (sent <= 0) break;
  13210. total_sent += static_cast<size_t>(sent);
  13211. }
  13212. detail::close_socket(cli);
  13213. }
  13214. detail::close_socket(srv);
  13215. });
  13216. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13217. size_t total_received = 0;
  13218. {
  13219. Client cli("127.0.0.1", PORT + 2);
  13220. cli.set_read_timeout(10, 0);
  13221. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13222. auto res =
  13223. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13224. total_received += data_length;
  13225. return true;
  13226. });
  13227. // Should fail because 200MB exceeds the explicit 150MB limit
  13228. EXPECT_FALSE(res);
  13229. }
  13230. server_thread.join();
  13231. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13232. << "Client with content_receiver should respect the explicit "
  13233. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13234. << total_received << " bytes.";
  13235. }
  13236. // Verify that an explicit set_payload_max_length larger than the response
  13237. // allows the content_receiver to read all data successfully.
  13238. TEST(ClientVulnerabilityTest,
  13239. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13240. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13241. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13242. #ifndef _WIN32
  13243. signal(SIGPIPE, SIG_IGN);
  13244. #endif
  13245. auto server_thread = std::thread([] {
  13246. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13247. default_socket_options(srv);
  13248. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13249. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13250. sockaddr_in addr{};
  13251. addr.sin_family = AF_INET;
  13252. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13253. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13254. int opt = 1;
  13255. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13256. #ifdef _WIN32
  13257. reinterpret_cast<const char *>(&opt),
  13258. #else
  13259. &opt,
  13260. #endif
  13261. sizeof(opt));
  13262. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13263. ::listen(srv, 1);
  13264. sockaddr_in cli_addr{};
  13265. socklen_t cli_len = sizeof(cli_addr);
  13266. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13267. if (cli != INVALID_SOCKET) {
  13268. char buf[4096];
  13269. ::recv(cli, buf, sizeof(buf), 0);
  13270. auto content_length = std::to_string(DATA_SIZE);
  13271. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13272. "Content-Length: " +
  13273. content_length +
  13274. "\r\n"
  13275. "Connection: close\r\n"
  13276. "\r\n";
  13277. ::send(cli,
  13278. #ifdef _WIN32
  13279. static_cast<const char *>(response_header.c_str()),
  13280. static_cast<int>(response_header.size()),
  13281. #else
  13282. response_header.c_str(), response_header.size(),
  13283. #endif
  13284. 0);
  13285. std::string chunk(64 * 1024, 'A');
  13286. size_t total_sent = 0;
  13287. while (total_sent < DATA_SIZE) {
  13288. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13289. auto sent = ::send(cli,
  13290. #ifdef _WIN32
  13291. static_cast<const char *>(chunk.c_str()),
  13292. static_cast<int>(to_send),
  13293. #else
  13294. chunk.c_str(), to_send,
  13295. #endif
  13296. 0);
  13297. if (sent <= 0) break;
  13298. total_sent += static_cast<size_t>(sent);
  13299. }
  13300. #ifdef _WIN32
  13301. ::shutdown(cli, SD_SEND);
  13302. #else
  13303. ::shutdown(cli, SHUT_WR);
  13304. #endif
  13305. char drain[1024];
  13306. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13307. detail::close_socket(cli);
  13308. }
  13309. detail::close_socket(srv);
  13310. });
  13311. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13312. size_t total_received = 0;
  13313. {
  13314. Client cli("127.0.0.1", PORT + 2);
  13315. cli.set_read_timeout(10, 0);
  13316. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13317. auto res =
  13318. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13319. total_received += data_length;
  13320. return true;
  13321. });
  13322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13323. EXPECT_EQ(StatusCode::OK_200, res->status);
  13324. }
  13325. server_thread.join();
  13326. EXPECT_EQ(total_received, DATA_SIZE)
  13327. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13328. << " bytes (larger than " << DATA_SIZE
  13329. << " bytes response), content_receiver should read all data, but only "
  13330. "read "
  13331. << total_received << " bytes.";
  13332. }
  13333. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13334. // Regression test for "zip bomb" attack on the client side: a malicious server
  13335. // sends a small gzip-compressed response that decompresses to a huge payload.
  13336. // The client must enforce payload_max_length on the decompressed size.
  13337. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13338. constexpr size_t DECOMPRESSED_SIZE =
  13339. 10 * 1024 * 1024; // 10MB after decompression
  13340. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13341. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13342. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13343. std::string compressed;
  13344. {
  13345. httplib::detail::gzip_compressor compressor;
  13346. bool ok =
  13347. compressor.compress(uncompressed.data(), uncompressed.size(),
  13348. /*last=*/true, [&](const char *buf, size_t len) {
  13349. compressed.append(buf, len);
  13350. return true;
  13351. });
  13352. ASSERT_TRUE(ok);
  13353. }
  13354. // Sanity: compressed data should be much smaller than the decompressed size
  13355. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13356. #ifndef _WIN32
  13357. signal(SIGPIPE, SIG_IGN);
  13358. #endif
  13359. // Set up the listening socket in the main thread so the server is guaranteed
  13360. // to be ready before the client connects (eliminates race condition).
  13361. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13362. default_socket_options(srv);
  13363. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13364. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13365. sockaddr_in addr{};
  13366. addr.sin_family = AF_INET;
  13367. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13368. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13369. int opt = 1;
  13370. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13371. #ifdef _WIN32
  13372. reinterpret_cast<const char *>(&opt),
  13373. #else
  13374. &opt,
  13375. #endif
  13376. sizeof(opt));
  13377. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13378. ASSERT_EQ(0, ::listen(srv, 1));
  13379. auto server_thread = std::thread([&compressed, srv] {
  13380. sockaddr_in cli_addr{};
  13381. socklen_t cli_len = sizeof(cli_addr);
  13382. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13383. if (cli != INVALID_SOCKET) {
  13384. // Read the full HTTP request (until \r\n\r\n)
  13385. char buf[4096];
  13386. size_t total = 0;
  13387. while (total < sizeof(buf)) {
  13388. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13389. if (n <= 0) break;
  13390. total += static_cast<size_t>(n);
  13391. // Check for end of headers
  13392. if (total >= 4) {
  13393. std::string req(buf, total);
  13394. if (req.find("\r\n\r\n") != std::string::npos) break;
  13395. }
  13396. }
  13397. // Malicious response: gzip-compressed body, no Content-Length
  13398. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13399. "Content-Encoding: gzip\r\n"
  13400. "Connection: close\r\n"
  13401. "\r\n";
  13402. ::send(cli,
  13403. #ifdef _WIN32
  13404. static_cast<const char *>(response_header.c_str()),
  13405. static_cast<int>(response_header.size()),
  13406. #else
  13407. response_header.c_str(), response_header.size(),
  13408. #endif
  13409. 0);
  13410. // Send the compressed payload (small on the wire, huge when decompressed)
  13411. size_t total_sent = 0;
  13412. while (total_sent < compressed.size()) {
  13413. auto to_send = std::min(compressed.size() - total_sent,
  13414. static_cast<size_t>(64 * 1024));
  13415. auto sent =
  13416. ::send(cli,
  13417. #ifdef _WIN32
  13418. static_cast<const char *>(compressed.c_str() + total_sent),
  13419. static_cast<int>(to_send),
  13420. #else
  13421. compressed.c_str() + total_sent, to_send,
  13422. #endif
  13423. 0);
  13424. if (sent <= 0) break;
  13425. total_sent += static_cast<size_t>(sent);
  13426. }
  13427. detail::close_socket(cli);
  13428. }
  13429. });
  13430. auto se = detail::scope_exit([&] {
  13431. detail::close_socket(srv);
  13432. server_thread.join();
  13433. });
  13434. size_t total_decompressed = 0;
  13435. {
  13436. Client cli("127.0.0.1", PORT + 3);
  13437. cli.set_read_timeout(5, 0);
  13438. cli.set_decompress(true);
  13439. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13440. auto stream = cli.open_stream("GET", "/zipbomb");
  13441. ASSERT_TRUE(stream.is_valid());
  13442. char buffer[64 * 1024];
  13443. ssize_t n;
  13444. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13445. total_decompressed += static_cast<size_t>(n);
  13446. }
  13447. }
  13448. // The decompressed size must be capped by payload_max_length. Without
  13449. // protection, the client would decompress the full 10MB from a tiny
  13450. // compressed payload, enabling a zip bomb DoS attack.
  13451. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13452. << "Client decompressed " << total_decompressed
  13453. << " bytes from a gzip response. The decompressed size should be "
  13454. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13455. }
  13456. #endif
  13457. TEST(HostAndPortPropertiesTest, NoSSL) {
  13458. httplib::Client cli("www.google.com", 1234);
  13459. ASSERT_EQ("www.google.com", cli.host());
  13460. ASSERT_EQ(1234, cli.port());
  13461. }
  13462. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13463. httplib::Client cli("www.google.com:1234");
  13464. ASSERT_EQ("www.google.com", cli.host());
  13465. ASSERT_EQ(1234, cli.port());
  13466. }
  13467. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13468. // Port number that overflows int — should not crash, client becomes invalid
  13469. httplib::Client cli("http://www.google.com:99999999999999999999");
  13470. ASSERT_FALSE(cli.is_valid());
  13471. }
  13472. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13473. // Port 99999 exceeds valid range (1-65535) — should not crash
  13474. httplib::Client cli("http://www.google.com:99999");
  13475. ASSERT_FALSE(cli.is_valid());
  13476. auto res = cli.Get("/");
  13477. EXPECT_FALSE(res);
  13478. EXPECT_EQ(Error::Connection, res.error());
  13479. }
  13480. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13481. httplib::Client cli("http://user:pass@localhost:1234");
  13482. ASSERT_FALSE(cli.is_valid());
  13483. EXPECT_FALSE(cli.Get("/"));
  13484. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13485. }
  13486. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13487. httplib::Client cli("http://www.google.com:80abc");
  13488. ASSERT_FALSE(cli.is_valid());
  13489. }
  13490. #ifdef CPPHTTPLIB_SSL_ENABLED
  13491. TEST(HostAndPortPropertiesTest, SSL) {
  13492. httplib::SSLClient cli("www.google.com");
  13493. ASSERT_EQ("www.google.com", cli.host());
  13494. ASSERT_EQ(443, cli.port());
  13495. }
  13496. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13497. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13498. std::string cert;
  13499. read_file(CA_CERT_FILE, cert);
  13500. httplib::SSLClient httplib_client("www.google.com");
  13501. // Load CA store first time
  13502. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13503. // Load CA store second time (update)
  13504. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13505. // Verify client is still valid and can make connections
  13506. httplib_client.enable_server_certificate_verification(true);
  13507. auto res = httplib_client.Get("/");
  13508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13509. // Google may return 200 or 301 depending on various factors
  13510. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13511. res->status == StatusCode::MovedPermanently_301);
  13512. }
  13513. TEST(SSLClientTest, ServerNameIndication_Online) {
  13514. auto host = "httpbingo.org";
  13515. auto path = std::string{"/get"};
  13516. SSLClient cli(host, 443);
  13517. auto res = cli.Get(path);
  13518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13519. ASSERT_EQ(StatusCode::OK_200, res->status);
  13520. }
  13521. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13522. // Use a site that will cause SSL verification failure due to self-signed cert
  13523. SSLClient cli("self-signed.badssl.com", 443);
  13524. cli.enable_server_certificate_verification(true);
  13525. auto res = cli.Get("/");
  13526. ASSERT_TRUE(!res);
  13527. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13528. // Verify backend error is captured for SSLServerVerification
  13529. // This occurs when certificate verification fails
  13530. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13531. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13532. EXPECT_NE(0UL, res.ssl_backend_error());
  13533. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13534. res.ssl_error());
  13535. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13536. #if !defined(_WIN32) || \
  13537. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13538. // On non-Windows or when Windows Schannel is disabled, the error comes
  13539. // from OpenSSL's verification
  13540. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13541. res.ssl_backend_error());
  13542. #endif
  13543. #endif
  13544. }
  13545. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13546. // Use a site where hostname doesn't match the certificate
  13547. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13548. SSLClient cli("wrong.host.badssl.com", 443);
  13549. cli.enable_server_certificate_verification(true);
  13550. cli.enable_server_hostname_verification(true);
  13551. auto res = cli.Get("/");
  13552. ASSERT_TRUE(!res);
  13553. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13554. // Verify backend error is captured for hostname verification failure
  13555. EXPECT_NE(0UL, res.ssl_backend_error());
  13556. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13557. res.ssl_error());
  13558. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13559. #if !defined(_WIN32) || \
  13560. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13561. // On non-Windows or when Windows Schannel is disabled, the error comes
  13562. // from OpenSSL's hostname verification
  13563. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13564. res.ssl_backend_error());
  13565. #endif
  13566. #endif
  13567. }
  13568. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13569. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13570. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13571. SSLClient cli("www.google.com", 443);
  13572. cli.enable_server_certificate_verification(true);
  13573. auto res = cli.Get("/");
  13574. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13575. }
  13576. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13577. SSLClient cli("www.google.com", 443);
  13578. cli.enable_server_certificate_verification(true);
  13579. cli.enable_windows_certificate_verification(false);
  13580. auto res = cli.Get("/");
  13581. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13582. }
  13583. // The server sends an intermediate cross-signed by a root Windows trusts,
  13584. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13585. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13586. SSLClient cli("accounts.spotify.com", 443);
  13587. auto res = cli.Get("/");
  13588. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13589. << " ssl_backend_error=" << res.ssl_backend_error();
  13590. }
  13591. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13592. // policy status, which no backend reports for a self-signed certificate.
  13593. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13594. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13595. ASSERT_TRUE(svr.is_valid());
  13596. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13597. auto se = detail::scope_exit([&] {
  13598. svr.stop();
  13599. t.join();
  13600. ASSERT_FALSE(svr.is_running());
  13601. });
  13602. svr.wait_until_ready();
  13603. SSLClient cli("127.0.0.1", PORT);
  13604. cli.set_connection_timeout(30);
  13605. auto res = cli.Get("/");
  13606. ASSERT_FALSE(res);
  13607. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13608. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13609. }
  13610. #endif
  13611. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13612. Client cli("https://google.com");
  13613. auto res = cli.Get("/");
  13614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13615. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13616. }
  13617. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13618. SSLClient cli("google.com");
  13619. cli.set_ca_cert_path(CA_CERT_FILE);
  13620. auto res = cli.Get("/");
  13621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13622. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13623. }
  13624. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13625. SSLClient cli("google.com");
  13626. cli.enable_server_certificate_verification(true);
  13627. cli.set_ca_cert_path("hello");
  13628. auto res = cli.Get("/");
  13629. ASSERT_TRUE(!res);
  13630. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13631. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13632. // should be set
  13633. EXPECT_EQ(0, res.ssl_error());
  13634. // Verify backend error is captured for SSLLoadingCerts
  13635. // This error occurs when loading CA certificates fails
  13636. EXPECT_NE(0UL, res.ssl_backend_error());
  13637. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13638. // OpenSSL specific error codes:
  13639. // > openssl errstr 0x80000002
  13640. // error:80000002:system library::No such file or directory
  13641. // > openssl errstr 0xA000126
  13642. // error:0A000126:SSL routines::unexpected eof while reading
  13643. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13644. res.ssl_backend_error() == 0xA000126);
  13645. #endif
  13646. }
  13647. TEST(SSLClientTest, ServerCertificateVerification4) {
  13648. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13649. ASSERT_TRUE(svr.is_valid());
  13650. svr.Get("/test", [&](const Request &, Response &res) {
  13651. res.set_content("test", "text/plain");
  13652. svr.stop();
  13653. ASSERT_TRUE(true);
  13654. });
  13655. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13656. auto se = detail::scope_exit([&] {
  13657. t.join();
  13658. ASSERT_FALSE(svr.is_running());
  13659. });
  13660. svr.wait_until_ready();
  13661. SSLClient cli("127.0.0.1", PORT);
  13662. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13663. cli.enable_server_certificate_verification(true);
  13664. cli.set_connection_timeout(30);
  13665. auto res = cli.Get("/test");
  13666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13667. ASSERT_EQ(StatusCode::OK_200, res->status);
  13668. }
  13669. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13670. std::string cert;
  13671. read_file(CA_CERT_FILE, cert);
  13672. SSLClient cli("google.com");
  13673. cli.load_ca_cert_store(cert.data(), cert.size());
  13674. const auto res = cli.Get("/");
  13675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13676. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13677. }
  13678. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13679. // clang-format off
  13680. static constexpr char cert[] =
  13681. "GlobalSign Root CA\n"
  13682. "==================\n"
  13683. "-----BEGIN CERTIFICATE-----\n"
  13684. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13685. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13686. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13687. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13688. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13689. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13690. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13691. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13692. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13693. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13694. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13695. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13696. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13697. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13698. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13699. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13700. "-----END CERTIFICATE-----\n";
  13701. // clang-format on
  13702. SSLClient cli("google.com");
  13703. cli.load_ca_cert_store(cert, sizeof(cert));
  13704. const auto res = cli.Get("/");
  13705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13706. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13707. }
  13708. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13709. SSLClient cli("www.youtube.com");
  13710. cli.set_ca_cert_path(CA_CERT_FILE);
  13711. cli.enable_server_certificate_verification(true);
  13712. cli.set_follow_location(true);
  13713. auto res = cli.Get("/");
  13714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13715. ASSERT_EQ(StatusCode::OK_200, res->status);
  13716. }
  13717. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13718. SSLClient cli("wWw.YouTube.Com");
  13719. cli.set_ca_cert_path(CA_CERT_FILE);
  13720. cli.enable_server_certificate_verification(true);
  13721. cli.enable_server_hostname_verification(true);
  13722. cli.set_follow_location(true);
  13723. auto res = cli.Get("/");
  13724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13725. ASSERT_EQ(StatusCode::OK_200, res->status);
  13726. }
  13727. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13728. SSLClient cli("gOoGlE.COm");
  13729. cli.enable_server_certificate_verification(true);
  13730. cli.enable_server_hostname_verification(true);
  13731. cli.set_follow_location(true);
  13732. auto res = cli.Get("/");
  13733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13734. ASSERT_EQ(StatusCode::OK_200, res->status);
  13735. }
  13736. TEST(SSLClientTest, Issue2004_Online) {
  13737. Client client("https://google.com");
  13738. client.set_follow_location(true);
  13739. auto res = client.Get("/");
  13740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13741. ASSERT_EQ(StatusCode::OK_200, res->status);
  13742. auto body = res->body;
  13743. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13744. }
  13745. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13746. // Create SSLClient with invalid cert/key to make is_valid() return false
  13747. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13748. "nonexistent_key.pem");
  13749. // is_valid() should be false due to cert loading failure
  13750. ASSERT_FALSE(cli.is_valid());
  13751. auto res = cli.Get("/");
  13752. ASSERT_FALSE(res);
  13753. EXPECT_EQ(Error::SSLConnection, res.error());
  13754. }
  13755. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13756. // Test for Issue #2251: SSL error not properly reported when client cert
  13757. // and key paths are swapped or mismatched
  13758. // This simulates the scenario where user accidentally swaps the cert and key
  13759. // files
  13760. // Using client cert file as private key and vice versa (completely wrong)
  13761. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13762. // Should fail validation due to cert/key mismatch
  13763. ASSERT_FALSE(cli.is_valid());
  13764. // Attempt to make a request should fail with proper error
  13765. auto res = cli.Get("/");
  13766. ASSERT_FALSE(res);
  13767. EXPECT_EQ(Error::SSLConnection, res.error());
  13768. // SSL error should be recorded in the Result object (this is the key fix for
  13769. // Issue #2251)
  13770. auto backend_error = res.ssl_backend_error();
  13771. EXPECT_NE(0u, backend_error);
  13772. }
  13773. // Tests cert/key mismatch detection at the TLS context level
  13774. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13775. // Test that using mismatched cert/key causes connection failure.
  13776. // We verify this at the SSLClient level rather than through internal
  13777. // TLS API functions.
  13778. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13779. cli.enable_server_certificate_verification(false);
  13780. cli.set_connection_timeout(2);
  13781. // The mismatch should cause a connection or handshake error
  13782. auto res = cli.Get("/test");
  13783. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13784. // Either way, the request should fail
  13785. EXPECT_FALSE(res);
  13786. }
  13787. #endif
  13788. #if 0
  13789. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13790. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13791. ASSERT_TRUE(cli != nullptr);
  13792. cli->set_address_family(AF_INET6);
  13793. cli->set_interface("en0");
  13794. auto res = cli->Get("/get");
  13795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13796. ASSERT_EQ(StatusCode::OK_200, res->status);
  13797. }
  13798. #endif
  13799. // Client certificate tests - work with all TLS backends
  13800. #ifdef CPPHTTPLIB_SSL_ENABLED
  13801. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13802. void ClientCertPresent(
  13803. const std::string &client_cert_file,
  13804. const std::string &client_private_key_file,
  13805. const std::string &client_encrypted_private_key_pass = std::string(),
  13806. const ClientCertServerSetup &setup = nullptr) {
  13807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13808. ASSERT_TRUE(svr.is_valid());
  13809. if (setup) { setup(svr); }
  13810. svr.Get("/test", [&](const Request &req, Response &res) {
  13811. res.set_content("test", "text/plain");
  13812. auto cert = req.peer_cert();
  13813. ASSERT_TRUE(static_cast<bool>(cert));
  13814. std::string common_name = cert.subject_cn();
  13815. EXPECT_EQ("Common Name", common_name);
  13816. });
  13817. auto port = svr.bind_to_any_port(HOST);
  13818. ASSERT_LT(0, port);
  13819. thread t = thread([&]() { svr.listen_after_bind(); });
  13820. auto se = detail::scope_exit([&] {
  13821. svr.stop();
  13822. t.join();
  13823. ASSERT_FALSE(svr.is_running());
  13824. });
  13825. svr.wait_until_ready();
  13826. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13827. client_encrypted_private_key_pass);
  13828. cli.enable_server_certificate_verification(false);
  13829. cli.set_connection_timeout(30);
  13830. auto res = cli.Get("/test");
  13831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13832. ASSERT_EQ(StatusCode::OK_200, res->status);
  13833. }
  13834. TEST(SSLClientServerTest, ClientCertPresent) {
  13835. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13836. }
  13837. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13838. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13839. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13840. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13841. }
  13842. // Expects svr, which must require client certificates, to reject a client
  13843. // that has none
  13844. void RejectsClientWithoutCert(SSLServer &svr) {
  13845. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13846. auto port = svr.bind_to_any_port(HOST);
  13847. ASSERT_LT(0, port);
  13848. thread t = thread([&]() { svr.listen_after_bind(); });
  13849. auto se = detail::scope_exit([&] {
  13850. svr.stop();
  13851. t.join();
  13852. ASSERT_FALSE(svr.is_running());
  13853. });
  13854. svr.wait_until_ready();
  13855. SSLClient cli(HOST, port);
  13856. cli.set_connection_timeout(30);
  13857. // Skip the server certificate check, so that the request fails because the
  13858. // client certificate is missing rather than because cert.pem is not trusted
  13859. cli.enable_server_certificate_verification(false);
  13860. auto res = cli.Get("/test");
  13861. ASSERT_FALSE(res);
  13862. // The server rejects the client during the handshake, or on TLS 1.3 right
  13863. // after it, which the client notices on its first write or read
  13864. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13865. res.error() == Error::Write || res.error() == Error::Read)
  13866. << to_string(res.error());
  13867. if (res.error() == Error::SSLConnection) {
  13868. EXPECT_NE(0UL, res.ssl_backend_error());
  13869. }
  13870. // A rejection noticed on the write keeps the TLS error the write hit
  13871. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13872. }
  13873. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13875. ASSERT_TRUE(svr.is_valid());
  13876. if (setup) { setup(svr); }
  13877. RejectsClientWithoutCert(svr);
  13878. }
  13879. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13880. // A server that requires client certificates must keep requiring them after
  13881. // setup changes it, and keep accepting a client that has one
  13882. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13883. ClientCertMissing(setup);
  13884. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13885. setup);
  13886. }
  13887. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13888. ClientCertStillRequired([](SSLServer &svr) {
  13889. ASSERT_TRUE(tls::set_verify_callback(
  13890. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13891. });
  13892. }
  13893. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13894. ClientCertStillRequired([](SSLServer &svr) {
  13895. ASSERT_TRUE(tls::set_verify_callback(
  13896. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13897. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13898. });
  13899. }
  13900. // The client verifies the server certificate during the handshake, so a
  13901. // server that fails the check never gets the client certificate, even when a
  13902. // verifier of the client's own accepts it
  13903. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13904. struct Case {
  13905. const char *trusted_ca;
  13906. const char *host;
  13907. Error error;
  13908. };
  13909. // cert2.pem names localhost: the first client does not trust it, and the
  13910. // second trusts it but asks for another name
  13911. for (const auto &c :
  13912. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13913. Case{SERVER_CERT2_FILE, "example.com",
  13914. Error::SSLServerHostnameVerification}}) {
  13915. for (auto with_verifier : {false, true}) {
  13916. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13917. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13918. CLIENT_CA_CERT_FILE);
  13919. ASSERT_TRUE(svr.is_valid());
  13920. std::atomic<bool> got_client_cert{false};
  13921. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13922. [&](const tls::VerifyContext &) {
  13923. got_client_cert = true;
  13924. return true;
  13925. }));
  13926. auto port = svr.bind_to_any_port("127.0.0.1");
  13927. ASSERT_LT(0, port);
  13928. thread t = thread([&] { svr.listen_after_bind(); });
  13929. svr.wait_until_ready();
  13930. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13931. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  13932. cli.set_ca_cert_path(c.trusted_ca);
  13933. if (with_verifier) {
  13934. cli.set_server_certificate_verifier(
  13935. [](const tls::VerifyContext &) { return true; });
  13936. }
  13937. auto res = cli.Get("/");
  13938. EXPECT_FALSE(res);
  13939. EXPECT_EQ(c.error, res.error());
  13940. svr.stop();
  13941. t.join();
  13942. EXPECT_FALSE(got_client_cert);
  13943. }
  13944. }
  13945. }
  13946. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13947. std::string cert_pem, key_pem, ca_pem;
  13948. read_file(SERVER_CERT_FILE, cert_pem);
  13949. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13950. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13951. ASSERT_TRUE(
  13952. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13953. }
  13954. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13956. ASSERT_TRUE(svr.is_valid());
  13957. UpdateCertsPemWithClientCA(svr);
  13958. RejectsClientWithoutCert(svr);
  13959. }
  13960. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13961. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13962. }
  13963. // A TLS error from one request must not show up in a later request's Result
  13964. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13966. ASSERT_TRUE(svr.is_valid());
  13967. svr.Get("/test", [](const Request &, Response &res) {
  13968. res.set_content("test", "text/plain");
  13969. });
  13970. auto port = svr.bind_to_any_port(HOST);
  13971. ASSERT_LT(0, port);
  13972. thread t = thread([&]() { svr.listen_after_bind(); });
  13973. auto se = detail::scope_exit([&] {
  13974. svr.stop();
  13975. t.join();
  13976. ASSERT_FALSE(svr.is_running());
  13977. });
  13978. svr.wait_until_ready();
  13979. SSLClient cli(HOST, port);
  13980. cli.set_connection_timeout(30);
  13981. cli.enable_server_hostname_verification(false);
  13982. // cert.pem is not trusted, so the handshake fails
  13983. ASSERT_FALSE(cli.Get("/test"));
  13984. cli.enable_server_certificate_verification(false);
  13985. auto res = cli.Get("/test");
  13986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13987. EXPECT_EQ(0, res.ssl_error());
  13988. EXPECT_EQ(0UL, res.ssl_backend_error());
  13989. }
  13990. // PEM memory-based constructor tests (works with all TLS backends).
  13991. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13992. // terminator after it.
  13993. void PemMemoryClientCertPresent(
  13994. const std::string &client_cert_file,
  13995. const std::string &client_private_key_file,
  13996. const std::string &client_encrypted_private_key_pass = std::string(),
  13997. bool exact_size = false) {
  13998. // Read PEM files into memory
  13999. std::string server_cert_pem, server_key_pem;
  14000. std::string client_ca_pem;
  14001. std::string client_cert_pem, client_key_pem;
  14002. read_file(SERVER_CERT_FILE, server_cert_pem);
  14003. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14004. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14005. read_file(client_cert_file, client_cert_pem);
  14006. read_file(client_private_key_file, client_key_pem);
  14007. std::list<std::vector<char>> exact_copies;
  14008. auto data = [&](const std::string &pem) -> const char * {
  14009. if (!exact_size) { return pem.c_str(); }
  14010. exact_copies.emplace_back(pem.begin(), pem.end());
  14011. return exact_copies.back().data();
  14012. };
  14013. // Create server with PEM memory
  14014. SSLServer::PemMemory server_pem = {
  14015. data(server_cert_pem),
  14016. server_cert_pem.size(),
  14017. data(server_key_pem),
  14018. server_key_pem.size(),
  14019. data(client_ca_pem),
  14020. client_ca_pem.size(),
  14021. nullptr // no password for server key
  14022. };
  14023. SSLServer svr(server_pem);
  14024. ASSERT_TRUE(svr.is_valid());
  14025. svr.Get("/test", [&](const Request &req, Response &res) {
  14026. res.set_content("test", "text/plain");
  14027. auto cert = req.peer_cert();
  14028. ASSERT_TRUE(static_cast<bool>(cert));
  14029. EXPECT_EQ("Common Name", cert.subject_cn());
  14030. });
  14031. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14032. auto se = detail::scope_exit([&] {
  14033. svr.stop();
  14034. t.join();
  14035. ASSERT_FALSE(svr.is_running());
  14036. });
  14037. svr.wait_until_ready();
  14038. // Create client with PEM memory
  14039. const char *password = client_encrypted_private_key_pass.empty()
  14040. ? nullptr
  14041. : client_encrypted_private_key_pass.c_str();
  14042. SSLClient::PemMemory client_pem = {
  14043. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14044. client_key_pem.size(), password};
  14045. SSLClient cli(HOST, PORT, client_pem);
  14046. cli.enable_server_certificate_verification(false);
  14047. cli.set_connection_timeout(30);
  14048. auto res = cli.Get("/test");
  14049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14050. ASSERT_EQ(StatusCode::OK_200, res->status);
  14051. }
  14052. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14053. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14054. }
  14055. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14056. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14057. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14058. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14059. }
  14060. // A server built from PEM memory with a client CA requires client certificates,
  14061. // also when the CA is a NUL-terminated string passed with a length of 0
  14062. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14063. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14064. read_file(SERVER_CERT_FILE, server_cert_pem);
  14065. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14066. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14067. SSLServer::PemMemory server_pem = {
  14068. server_cert_pem.c_str(),
  14069. server_cert_pem.size(),
  14070. server_key_pem.c_str(),
  14071. server_key_pem.size(),
  14072. client_ca_pem.c_str(),
  14073. client_ca_pem.size(),
  14074. nullptr // no password for server key
  14075. };
  14076. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14077. SCOPED_TRACE(client_ca_pem_len);
  14078. server_pem.client_ca_pem_len = client_ca_pem_len;
  14079. SSLServer svr(server_pem);
  14080. ASSERT_TRUE(svr.is_valid());
  14081. RejectsClientWithoutCert(svr);
  14082. }
  14083. // An empty CA fails to load instead of turning the check off
  14084. server_pem.client_ca_pem = "";
  14085. server_pem.client_ca_pem_len = 0;
  14086. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14087. }
  14088. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14089. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14090. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14091. true);
  14092. }
  14093. // A length shorter than the PEM cuts it short, so it no longer loads
  14094. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14095. std::string cert, key;
  14096. read_file(SERVER_CERT_FILE, cert);
  14097. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14098. for (auto cut_cert : {true, false}) {
  14099. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14100. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14101. SSLServer::PemMemory server_pem = {
  14102. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14103. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14104. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14105. key_len, nullptr};
  14106. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14107. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14108. key.c_str(), key_len, nullptr};
  14109. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14110. }
  14111. }
  14112. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14113. class NoListenSSLServer : public SSLServer {
  14114. public:
  14115. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14116. const char *client_ca_cert_file_path,
  14117. const char *client_ca_cert_dir_path = nullptr)
  14118. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14119. client_ca_cert_dir_path),
  14120. stop_(false) {}
  14121. std::atomic_bool stop_;
  14122. private:
  14123. bool process_and_close_socket(socket_t /*sock*/) override {
  14124. // Don't create SSL context
  14125. while (!stop_.load()) {
  14126. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14127. }
  14128. return true;
  14129. }
  14130. };
  14131. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14132. CLIENT_CA_CERT_FILE);
  14133. ASSERT_TRUE(svr.is_valid());
  14134. svr.Get("/test", [&](const Request &, Response &res) {
  14135. res.set_content("test", "text/plain");
  14136. });
  14137. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14138. auto se = detail::scope_exit([&] {
  14139. svr.stop_ = true;
  14140. svr.stop();
  14141. t.join();
  14142. ASSERT_FALSE(svr.is_running());
  14143. });
  14144. svr.wait_until_ready();
  14145. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14146. cli.enable_server_certificate_verification(false);
  14147. cli.set_connection_timeout(1);
  14148. auto res = cli.Get("/test");
  14149. ASSERT_TRUE(!res);
  14150. EXPECT_EQ(Error::SSLConnection, res.error());
  14151. // Timeout results in WantRead error code (maps to backend-specific value)
  14152. EXPECT_NE(0, res.ssl_error());
  14153. }
  14154. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14155. // Test SSLServer with client certificate verification using the standard
  14156. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14158. CLIENT_CA_CERT_DIR);
  14159. ASSERT_TRUE(svr.is_valid());
  14160. svr.Get("/test", [&](const Request &req, Response &res) {
  14161. res.set_content("test", "text/plain");
  14162. auto cert = req.peer_cert();
  14163. ASSERT_TRUE(static_cast<bool>(cert));
  14164. auto common_name = cert.subject_cn();
  14165. EXPECT_EQ("Common Name", common_name);
  14166. });
  14167. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14168. auto se = detail::scope_exit([&] {
  14169. svr.stop();
  14170. t.join();
  14171. ASSERT_FALSE(svr.is_running());
  14172. });
  14173. svr.wait_until_ready();
  14174. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14175. cli.enable_server_certificate_verification(false);
  14176. cli.set_connection_timeout(30);
  14177. auto res = cli.Get("/test");
  14178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14179. ASSERT_EQ(StatusCode::OK_200, res->status);
  14180. }
  14181. // Test verify_hostname on every backend: a host is named by a SAN only
  14182. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14183. using namespace httplib::tls;
  14184. // We need a running server to test against
  14185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14186. ASSERT_TRUE(svr.is_valid());
  14187. svr.Get("/test", [](const Request &, Response &res) {
  14188. res.set_content("ok", "text/plain");
  14189. });
  14190. thread t([&]() { svr.listen(HOST, PORT); });
  14191. auto se = detail::scope_exit([&] {
  14192. svr.stop();
  14193. t.join();
  14194. });
  14195. svr.wait_until_ready();
  14196. bool verify_callback_called = false;
  14197. bool verify_result_wrong = false;
  14198. SSLClient cli(HOST, PORT);
  14199. cli.enable_server_certificate_verification(true);
  14200. cli.set_ca_cert_path(CA_CERT_FILE);
  14201. cli.set_connection_timeout(5);
  14202. // Note: Test certificate has CN="Common Name", not "localhost"
  14203. bool verify_result_cn = false;
  14204. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14205. verify_callback_called = true;
  14206. if (!ctx.cert) return false;
  14207. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14208. verify_result_cn = ctx.check_hostname("Common Name");
  14209. // Test 2: wrong hostname should not match
  14210. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14211. return true; // Accept for the purpose of this test
  14212. });
  14213. auto res = cli.Get("/test");
  14214. // The request may succeed or fail depending on cert configuration
  14215. // but the callback should have been called
  14216. ASSERT_TRUE(verify_callback_called)
  14217. << "Verify callback should have been called";
  14218. EXPECT_FALSE(verify_result_cn)
  14219. << "verify_hostname must not match the certificate CN (no SAN)";
  14220. // Wrong hostname should not match
  14221. EXPECT_FALSE(verify_result_wrong)
  14222. << "verify_hostname should not match 'wronghost.example.com'";
  14223. }
  14224. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14225. // backend verifies it.
  14226. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14227. // Certificate CN is "localhost" and it carries no SAN.
  14228. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14229. ASSERT_TRUE(svr.is_valid());
  14230. svr.Get("/test", [](const Request &, Response &res) {
  14231. res.set_content("ok", "text/plain");
  14232. });
  14233. auto port = svr.bind_to_any_port(HOST);
  14234. thread t([&]() { svr.listen_after_bind(); });
  14235. auto se = detail::scope_exit([&] {
  14236. svr.stop();
  14237. t.join();
  14238. });
  14239. svr.wait_until_ready();
  14240. SSLClient cli("localhost", port);
  14241. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14242. cli.enable_server_certificate_verification(true);
  14243. cli.set_connection_timeout(5);
  14244. auto res = cli.Get("/test");
  14245. ASSERT_FALSE(res);
  14246. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14247. // The same certificate is accepted once host name verification is off, so the
  14248. // failure above is the host name and not the chain.
  14249. cli.enable_server_hostname_verification(false);
  14250. res = cli.Get("/test");
  14251. ASSERT_TRUE(res) << to_string(res.error());
  14252. EXPECT_EQ(StatusCode::OK_200, res->status);
  14253. }
  14254. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14255. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14256. // X509_check_ip behavior and must hold for every backend.
  14257. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14258. using namespace httplib::tls;
  14259. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14260. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14261. ASSERT_TRUE(svr.is_valid());
  14262. svr.Get("/test", [](const Request &, Response &res) {
  14263. res.set_content("ok", "text/plain");
  14264. });
  14265. thread t([&]() { svr.listen(HOST, PORT); });
  14266. auto se = detail::scope_exit([&] {
  14267. svr.stop();
  14268. t.join();
  14269. });
  14270. svr.wait_until_ready();
  14271. bool verify_callback_called = false;
  14272. bool ip_matched_via_cn = true;
  14273. SSLClient cli(HOST, PORT);
  14274. cli.enable_server_certificate_verification(true);
  14275. cli.set_ca_cert_path(CA_CERT_FILE);
  14276. cli.set_connection_timeout(5);
  14277. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14278. verify_callback_called = true;
  14279. if (!ctx.cert) return false;
  14280. // The IP appears only in the CN, so it must NOT be accepted.
  14281. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14282. return true; // Accept for the purpose of this test
  14283. });
  14284. cli.Get("/test");
  14285. ASSERT_TRUE(verify_callback_called)
  14286. << "Verify callback should have been called";
  14287. EXPECT_FALSE(ip_matched_via_cn)
  14288. << "An IP host must not be authenticated via the certificate CN";
  14289. }
  14290. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14291. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14292. using namespace httplib::tls;
  14293. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14294. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14295. ASSERT_TRUE(svr.is_valid());
  14296. svr.Get("/test", [](const Request &, Response &res) {
  14297. res.set_content("ok", "text/plain");
  14298. });
  14299. thread t([&]() { svr.listen(HOST, PORT); });
  14300. auto se = detail::scope_exit([&] {
  14301. svr.stop();
  14302. t.join();
  14303. });
  14304. svr.wait_until_ready();
  14305. bool verify_callback_called = false;
  14306. bool san_matched = false;
  14307. bool wrong_ipv6_matched = true;
  14308. bool cn_ipv6_matched = true;
  14309. SSLClient cli(HOST, PORT);
  14310. cli.enable_server_certificate_verification(true);
  14311. cli.set_ca_cert_path(CA_CERT_FILE);
  14312. cli.set_connection_timeout(5);
  14313. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14314. verify_callback_called = true;
  14315. if (!ctx.cert) return false;
  14316. // Matches the IPv6 iPAddress SAN.
  14317. san_matched = ctx.check_hostname("2001:db8::1");
  14318. // A different IPv6 address must not match.
  14319. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14320. // "::1" lives only in the CN, so it must not be accepted.
  14321. cn_ipv6_matched = ctx.check_hostname("::1");
  14322. return true; // Accept for the purpose of this test
  14323. });
  14324. cli.Get("/test");
  14325. ASSERT_TRUE(verify_callback_called)
  14326. << "Verify callback should have been called";
  14327. EXPECT_TRUE(san_matched)
  14328. << "verify_hostname should match an IPv6 iPAddress SAN";
  14329. EXPECT_FALSE(wrong_ipv6_matched)
  14330. << "verify_hostname should not match a non-matching IPv6 address";
  14331. EXPECT_FALSE(cn_ipv6_matched)
  14332. << "An IPv6 host must not be authenticated via the certificate CN";
  14333. }
  14334. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14335. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14336. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14337. using namespace httplib::tls;
  14338. // SANs: DNS:a.zz, IP:42.46.122.122
  14339. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14340. ASSERT_TRUE(svr.is_valid());
  14341. svr.Get("/test", [](const Request &, Response &res) {
  14342. res.set_content("ok", "text/plain");
  14343. });
  14344. auto port = svr.bind_to_any_port(HOST);
  14345. thread t([&]() { svr.listen_after_bind(); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. });
  14350. svr.wait_until_ready();
  14351. bool verify_callback_called = false;
  14352. bool dns_san_matched = false;
  14353. bool ip_san_matched = false;
  14354. bool ip_matched_via_dns_san = true;
  14355. bool dns_matched_via_ip_san = true;
  14356. bool cn_matched_next_to_dns_san = true;
  14357. SSLClient cli(HOST, port);
  14358. cli.enable_server_certificate_verification(true);
  14359. cli.set_ca_cert_path(CA_CERT_FILE);
  14360. cli.set_connection_timeout(5);
  14361. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14362. verify_callback_called = true;
  14363. if (!ctx.cert) return false;
  14364. dns_san_matched = ctx.check_hostname("a.zz");
  14365. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14366. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14367. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14368. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14369. return true; // Accept for the purpose of this test
  14370. });
  14371. cli.Get("/test");
  14372. ASSERT_TRUE(verify_callback_called)
  14373. << "Verify callback should have been called";
  14374. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14375. EXPECT_TRUE(ip_san_matched)
  14376. << "verify_hostname should match an iPAddress SAN";
  14377. EXPECT_FALSE(ip_matched_via_dns_san)
  14378. << "An IP host must not be authenticated via a dNSName SAN";
  14379. EXPECT_FALSE(dns_matched_via_ip_san)
  14380. << "A DNS host must not be authenticated via an iPAddress SAN";
  14381. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14382. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14383. }
  14384. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14385. // "www.*.example.test" names one host and not every host under example.test.
  14386. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14387. using namespace httplib::tls;
  14388. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14389. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14390. ASSERT_TRUE(svr.is_valid());
  14391. svr.Get("/test", [](const Request &, Response &res) {
  14392. res.set_content("ok", "text/plain");
  14393. });
  14394. auto port = svr.bind_to_any_port(HOST);
  14395. thread t([&]() { svr.listen_after_bind(); });
  14396. auto se = detail::scope_exit([&] {
  14397. svr.stop();
  14398. t.join();
  14399. });
  14400. svr.wait_until_ready();
  14401. bool verify_callback_called = false;
  14402. bool leftmost_wildcard_matched = false;
  14403. bool wildcard_spanned_labels = true;
  14404. bool inner_wildcard_matched = true;
  14405. SSLClient cli(HOST, port);
  14406. cli.enable_server_certificate_verification(true);
  14407. cli.set_ca_cert_path(CA_CERT_FILE);
  14408. cli.set_connection_timeout(5);
  14409. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14410. verify_callback_called = true;
  14411. if (!ctx.cert) return false;
  14412. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14413. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14414. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14415. return true; // Accept for the purpose of this test
  14416. });
  14417. cli.Get("/test");
  14418. ASSERT_TRUE(verify_callback_called)
  14419. << "Verify callback should have been called";
  14420. EXPECT_TRUE(leftmost_wildcard_matched)
  14421. << "A leftmost wildcard should match a single label";
  14422. EXPECT_FALSE(wildcard_spanned_labels)
  14423. << "A wildcard label must not match more than one label";
  14424. EXPECT_FALSE(inner_wildcard_matched)
  14425. << "A wildcard outside the leftmost label must not be honoured";
  14426. }
  14427. // sans() must report each SAN entry under its own type.
  14428. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14429. using namespace httplib::tls;
  14430. // SANs: DNS:a.zz, IP:42.46.122.122
  14431. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14432. ASSERT_TRUE(svr.is_valid());
  14433. svr.Get("/test", [](const Request &, Response &res) {
  14434. res.set_content("ok", "text/plain");
  14435. });
  14436. auto port = svr.bind_to_any_port(HOST);
  14437. thread t([&]() { svr.listen_after_bind(); });
  14438. auto se = detail::scope_exit([&] {
  14439. svr.stop();
  14440. t.join();
  14441. });
  14442. svr.wait_until_ready();
  14443. bool verify_callback_called = false;
  14444. std::vector<SanEntry> sans;
  14445. SSLClient cli(HOST, port);
  14446. cli.enable_server_certificate_verification(true);
  14447. cli.set_ca_cert_path(CA_CERT_FILE);
  14448. cli.set_connection_timeout(5);
  14449. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14450. verify_callback_called = true;
  14451. if (!ctx.cert) return false;
  14452. sans = ctx.sans();
  14453. return true; // Accept for the purpose of this test
  14454. });
  14455. cli.Get("/test");
  14456. ASSERT_TRUE(verify_callback_called)
  14457. << "Verify callback should have been called";
  14458. auto has_san = [&](SanType type, const std::string &value) {
  14459. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14460. return san.type == type && san.value == value;
  14461. });
  14462. };
  14463. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14464. << "sans() should report the dNSName SAN";
  14465. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14466. << "sans() should report the iPAddress SAN";
  14467. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14468. << "sans() must not report the dNSName SAN as an address";
  14469. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14470. << "sans() must not report the iPAddress SAN as a DNS name";
  14471. }
  14472. #endif
  14473. // mbedTLS-specific callback constructor test
  14474. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14475. #ifdef CPPHTTPLIB_SSL_ENABLED
  14476. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14478. ASSERT_TRUE(svr.is_valid());
  14479. // Set up a handler to verify client certificate is present
  14480. bool client_cert_verified = false;
  14481. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14482. // Verify that client certificate was provided
  14483. client_cert_verified = true;
  14484. res.set_content("success", "text/plain");
  14485. });
  14486. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14487. auto se = detail::scope_exit([&] {
  14488. svr.stop();
  14489. t.join();
  14490. ASSERT_FALSE(svr.is_running());
  14491. });
  14492. svr.wait_until_ready();
  14493. // Client with certificate
  14494. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14495. cli.enable_server_certificate_verification(false);
  14496. cli.set_connection_timeout(30);
  14497. auto res = cli.Get("/test");
  14498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14499. ASSERT_EQ(StatusCode::OK_200, res->status);
  14500. ASSERT_TRUE(client_cert_verified);
  14501. EXPECT_EQ("success", res->body);
  14502. }
  14503. #endif
  14504. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14505. // backends
  14506. #ifdef CPPHTTPLIB_SSL_ENABLED
  14507. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14508. using namespace httplib::tls;
  14509. // Test that when client CA cert file is provided,
  14510. // the server properly requests and validates client certificates
  14511. // Create a server with client authentication
  14512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14513. ASSERT_TRUE(svr.is_valid());
  14514. bool handler_called = false;
  14515. svr.Get("/test", [&](const Request &req, Response &res) {
  14516. handler_called = true;
  14517. // Verify that a client certificate was provided
  14518. auto cert = req.peer_cert();
  14519. ASSERT_TRUE(static_cast<bool>(cert));
  14520. // Get the issuer name
  14521. std::string issuer_str = cert.issuer_name();
  14522. ASSERT_FALSE(issuer_str.empty());
  14523. // The client certificate should be issued by our test CA
  14524. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14525. res.set_content("authenticated", "text/plain");
  14526. });
  14527. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14528. auto se = detail::scope_exit([&] {
  14529. svr.stop();
  14530. t.join();
  14531. ASSERT_FALSE(svr.is_running());
  14532. });
  14533. svr.wait_until_ready();
  14534. // Connect with a client certificate issued by the CA
  14535. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14536. cli.enable_server_certificate_verification(false);
  14537. cli.set_connection_timeout(30);
  14538. auto res = cli.Get("/test");
  14539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14540. ASSERT_EQ(StatusCode::OK_200, res->status);
  14541. ASSERT_TRUE(handler_called);
  14542. EXPECT_EQ("authenticated", res->body);
  14543. }
  14544. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14545. using namespace httplib::tls;
  14546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14547. ASSERT_TRUE(svr.is_valid());
  14548. svr.Get("/test", [](const Request &, Response &res) {
  14549. res.set_content("ok", "text/plain");
  14550. });
  14551. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14552. auto se = detail::scope_exit([&] {
  14553. svr.stop();
  14554. t.join();
  14555. });
  14556. svr.wait_until_ready();
  14557. SSLClient cli(HOST, PORT);
  14558. cli.enable_server_certificate_verification(false);
  14559. cli.set_connection_timeout(30);
  14560. bool cert_checked = false;
  14561. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14562. if (ctx.cert) {
  14563. auto sans = ctx.sans();
  14564. // Test certificate may or may not have SANs - just verify the API
  14565. // works If SANs exist, verify the types are valid
  14566. for (const auto &san : sans) {
  14567. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14568. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14569. san.type == SanType::OTHER);
  14570. EXPECT_FALSE(san.value.empty());
  14571. }
  14572. cert_checked = true;
  14573. }
  14574. return true;
  14575. });
  14576. auto res = cli.Get("/test");
  14577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14578. EXPECT_TRUE(cert_checked);
  14579. }
  14580. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14581. using namespace httplib::tls;
  14582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14583. ASSERT_TRUE(svr.is_valid());
  14584. svr.Get("/test", [](const Request &, Response &res) {
  14585. res.set_content("ok", "text/plain");
  14586. });
  14587. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14588. auto se = detail::scope_exit([&] {
  14589. svr.stop();
  14590. t.join();
  14591. });
  14592. svr.wait_until_ready();
  14593. SSLClient cli(HOST, PORT);
  14594. cli.enable_server_certificate_verification(false);
  14595. cli.set_connection_timeout(30);
  14596. bool validity_checked = false;
  14597. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14598. if (ctx.cert) {
  14599. time_t not_before = 0, not_after = 0;
  14600. bool result = ctx.validity(not_before, not_after);
  14601. EXPECT_TRUE(result);
  14602. // Verify that not_before < now < not_after for a valid cert
  14603. time_t now = time(nullptr);
  14604. EXPECT_LT(not_before, now);
  14605. EXPECT_GT(not_after, now);
  14606. validity_checked = true;
  14607. }
  14608. return true;
  14609. });
  14610. auto res = cli.Get("/test");
  14611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14612. EXPECT_TRUE(validity_checked);
  14613. }
  14614. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14615. using namespace httplib::tls;
  14616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14617. ASSERT_TRUE(svr.is_valid());
  14618. svr.Get("/test", [](const Request &, Response &res) {
  14619. res.set_content("ok", "text/plain");
  14620. });
  14621. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14622. auto se = detail::scope_exit([&] {
  14623. svr.stop();
  14624. t.join();
  14625. });
  14626. svr.wait_until_ready();
  14627. SSLClient cli(HOST, PORT);
  14628. cli.enable_server_certificate_verification(false);
  14629. cli.set_connection_timeout(30);
  14630. bool serial_checked = false;
  14631. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14632. if (ctx.cert) {
  14633. std::string serial = ctx.serial();
  14634. EXPECT_FALSE(serial.empty());
  14635. // Serial should be a hex string
  14636. for (char c : serial) {
  14637. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14638. (c >= 'a' && c <= 'f'));
  14639. }
  14640. serial_checked = true;
  14641. }
  14642. return true;
  14643. });
  14644. auto res = cli.Get("/test");
  14645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14646. EXPECT_TRUE(serial_checked);
  14647. }
  14648. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14649. // Test 1: Valid CA file - no error should be recorded
  14650. {
  14651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14652. CLIENT_CA_CERT_FILE);
  14653. ASSERT_TRUE(svr.is_valid());
  14654. // With valid setup, last_ssl_error should be 0
  14655. EXPECT_EQ(0, svr.ssl_last_error());
  14656. }
  14657. // Test 2: Invalid CA file content
  14658. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14659. {
  14660. // Create a temporary file with completely invalid content
  14661. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14662. {
  14663. std::ofstream ofs(temp_invalid_ca);
  14664. ofs << "This is not a certificate file at all\n";
  14665. ofs << "Just plain text content\n";
  14666. }
  14667. // Create server with invalid CA file
  14668. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14669. // Clean up temporary file
  14670. std::remove(temp_invalid_ca);
  14671. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14672. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14673. // Note: SSL_CTX_load_verify_locations typically fails first,
  14674. // but our error handling code path is still exercised
  14675. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14676. }
  14677. }
  14678. TEST(VerifyCallbackTest, VerifyContextFields) {
  14679. using namespace httplib::tls;
  14680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14681. ASSERT_TRUE(svr.is_valid());
  14682. svr.Get("/test", [](const Request &, Response &res) {
  14683. res.set_content("ok", "text/plain");
  14684. });
  14685. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14686. auto se = detail::scope_exit([&] {
  14687. svr.stop();
  14688. t.join();
  14689. });
  14690. svr.wait_until_ready();
  14691. SSLClient cli(HOST, PORT);
  14692. cli.enable_server_certificate_verification(false);
  14693. cli.set_connection_timeout(30);
  14694. int callback_count = 0;
  14695. bool saw_leaf_cert = false;
  14696. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14697. if (ctx.cert) {
  14698. callback_count++;
  14699. // We should see at least one certificate (the leaf)
  14700. std::string cn = ctx.subject_cn();
  14701. if (!cn.empty()) { saw_leaf_cert = true; }
  14702. // Verify context fields are populated
  14703. EXPECT_NE(ctx.session, nullptr);
  14704. EXPECT_GE(ctx.depth, 0);
  14705. }
  14706. return true;
  14707. });
  14708. auto res = cli.Get("/test");
  14709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14710. EXPECT_GT(callback_count, 0);
  14711. EXPECT_TRUE(saw_leaf_cert);
  14712. }
  14713. // A verifier that accepts runs alongside the built-in verification, and is the
  14714. // only check once that is turned off.
  14715. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14716. using namespace httplib::tls;
  14717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14718. ASSERT_TRUE(svr.is_valid());
  14719. svr.Get("/test", [](const Request &, Response &res) {
  14720. res.set_content("ok", "text/plain");
  14721. });
  14722. auto port = svr.bind_to_any_port(HOST);
  14723. thread t([&]() { svr.listen_after_bind(); });
  14724. auto se = detail::scope_exit([&] {
  14725. svr.stop();
  14726. t.join();
  14727. });
  14728. svr.wait_until_ready();
  14729. SSLClient cli(HOST, port);
  14730. cli.enable_server_hostname_verification(false);
  14731. auto calls = 0;
  14732. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14733. calls++;
  14734. return true;
  14735. });
  14736. // cert.pem is not trusted
  14737. auto res = cli.Get("/test");
  14738. ASSERT_FALSE(res);
  14739. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14740. EXPECT_GT(calls, 0);
  14741. cli.enable_server_certificate_verification(false);
  14742. res = cli.Get("/test");
  14743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14744. EXPECT_EQ("ok", res->body);
  14745. }
  14746. // A verifier belongs to the client that set it, not to the thread that set it.
  14747. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14748. using namespace httplib::tls;
  14749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14750. ASSERT_TRUE(svr.is_valid());
  14751. svr.Get("/test", [](const Request &, Response &res) {
  14752. res.set_content("ok", "text/plain");
  14753. });
  14754. auto port = svr.bind_to_any_port(HOST);
  14755. thread t([&]() { svr.listen_after_bind(); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. t.join();
  14759. });
  14760. svr.wait_until_ready();
  14761. auto rejecting_calls = 0;
  14762. SSLClient rejecting(HOST, port);
  14763. rejecting.enable_server_certificate_verification(false);
  14764. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14765. rejecting_calls++;
  14766. return false;
  14767. });
  14768. auto accepting_calls = 0;
  14769. SSLClient accepting(HOST, port);
  14770. accepting.enable_server_certificate_verification(false);
  14771. // Set on another thread than the requests below.
  14772. thread([&]() {
  14773. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14774. accepting_calls++;
  14775. return true;
  14776. });
  14777. }).join();
  14778. // Requested on another thread than the verifier was set on.
  14779. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14780. EXPECT_GT(rejecting_calls, 0);
  14781. auto res = accepting.Get("/test");
  14782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14783. EXPECT_GT(accepting_calls, 0);
  14784. }
  14785. // A verifier replaced while a handshake runs it lives until it returns.
  14786. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14787. using namespace httplib::tls;
  14788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14789. ASSERT_TRUE(svr.is_valid());
  14790. svr.Get("/test", [](const Request &, Response &res) {
  14791. res.set_content("ok", "text/plain");
  14792. });
  14793. auto port = svr.bind_to_any_port(HOST);
  14794. thread t([&]() { svr.listen_after_bind(); });
  14795. auto se = detail::scope_exit([&] {
  14796. svr.stop();
  14797. t.join();
  14798. });
  14799. svr.wait_until_ready();
  14800. SSLClient cli(HOST, port);
  14801. cli.enable_server_certificate_verification(false);
  14802. std::promise<void> entered;
  14803. std::promise<void> replaced;
  14804. auto replaced_future = replaced.get_future();
  14805. auto first_call = true;
  14806. // Long enough to live on the heap
  14807. std::string expected(64, 'v');
  14808. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14809. if (first_call) {
  14810. first_call = false;
  14811. entered.set_value();
  14812. replaced_future.wait();
  14813. }
  14814. return expected == std::string(64, 'v');
  14815. });
  14816. thread request([&]() {
  14817. auto res = cli.Get("/test");
  14818. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14819. });
  14820. entered.get_future().wait();
  14821. cli.set_server_certificate_verifier(
  14822. [](const VerifyContext &) { return true; });
  14823. replaced.set_value();
  14824. request.join();
  14825. }
  14826. // VerifyContext::session is the same handle the other tls:: functions take.
  14827. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14828. using namespace httplib::tls;
  14829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14830. ASSERT_TRUE(svr.is_valid());
  14831. svr.Get("/test", [](const Request &, Response &res) {
  14832. res.set_content("ok", "text/plain");
  14833. });
  14834. auto port = svr.bind_to_any_port(HOST);
  14835. thread t([&]() { svr.listen_after_bind(); });
  14836. auto se = detail::scope_exit([&] {
  14837. svr.stop();
  14838. t.join();
  14839. });
  14840. svr.wait_until_ready();
  14841. SSLClient cli(HOST, port);
  14842. cli.enable_server_certificate_verification(false);
  14843. session_t verifier_session = nullptr;
  14844. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14845. verifier_session = ctx.session;
  14846. return true;
  14847. });
  14848. session_t session_verifier_session = nullptr;
  14849. cli.set_session_verifier([&](session_t session) {
  14850. session_verifier_session = session;
  14851. return SSLVerifierResponse::NoDecisionMade;
  14852. });
  14853. auto res = cli.Get("/test");
  14854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14855. EXPECT_NE(nullptr, verifier_session);
  14856. EXPECT_EQ(session_verifier_session, verifier_session);
  14857. }
  14858. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14859. using httplib::tls::TlsError;
  14860. // Test that verify_error_to_string returns empty for success
  14861. std::string success_str = TlsError::verify_error_to_string(0);
  14862. EXPECT_TRUE(success_str.empty());
  14863. // Test that verify_error_to_string returns non-empty for error codes
  14864. // Using a common error code (certificate expired)
  14865. std::string error_str =
  14866. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14867. EXPECT_FALSE(error_str.empty());
  14868. }
  14869. TEST(SessionVerifierTest, CertificateAccepted) {
  14870. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14871. ASSERT_TRUE(svr.is_valid());
  14872. svr.Get("/test", [](const Request &, Response &res) {
  14873. res.set_content("ok", "text/plain");
  14874. });
  14875. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14876. auto se = detail::scope_exit([&] {
  14877. svr.stop();
  14878. t.join();
  14879. });
  14880. svr.wait_until_ready();
  14881. SSLClient cli(HOST, PORT);
  14882. cli.enable_server_certificate_verification(false);
  14883. cli.set_connection_timeout(30);
  14884. bool callback_called = false;
  14885. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14886. EXPECT_NE(session, nullptr);
  14887. callback_called = true;
  14888. return SSLVerifierResponse::CertificateAccepted;
  14889. });
  14890. auto res = cli.Get("/test");
  14891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14892. EXPECT_EQ(200, res->status);
  14893. EXPECT_TRUE(callback_called);
  14894. }
  14895. TEST(SessionVerifierTest, CertificateRejected) {
  14896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14897. ASSERT_TRUE(svr.is_valid());
  14898. svr.Get("/test", [](const Request &, Response &res) {
  14899. res.set_content("ok", "text/plain");
  14900. });
  14901. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14902. auto se = detail::scope_exit([&] {
  14903. svr.stop();
  14904. t.join();
  14905. });
  14906. svr.wait_until_ready();
  14907. SSLClient cli(HOST, PORT);
  14908. cli.enable_server_certificate_verification(false);
  14909. cli.set_connection_timeout(30);
  14910. bool callback_called = false;
  14911. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14912. EXPECT_NE(session, nullptr);
  14913. callback_called = true;
  14914. return SSLVerifierResponse::CertificateRejected;
  14915. });
  14916. auto res = cli.Get("/test");
  14917. EXPECT_FALSE(res);
  14918. EXPECT_TRUE(callback_called);
  14919. }
  14920. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14922. ASSERT_TRUE(svr.is_valid());
  14923. svr.Get("/test", [](const Request &, Response &res) {
  14924. res.set_content("ok", "text/plain");
  14925. });
  14926. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14927. auto se = detail::scope_exit([&] {
  14928. svr.stop();
  14929. t.join();
  14930. });
  14931. svr.wait_until_ready();
  14932. // NoDecisionMade with verification disabled should succeed (no default check)
  14933. SSLClient cli(HOST, PORT);
  14934. cli.enable_server_certificate_verification(false);
  14935. cli.set_connection_timeout(30);
  14936. bool callback_called = false;
  14937. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14938. EXPECT_NE(session, nullptr);
  14939. callback_called = true;
  14940. return SSLVerifierResponse::NoDecisionMade;
  14941. });
  14942. auto res = cli.Get("/test");
  14943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14944. EXPECT_EQ(200, res->status);
  14945. EXPECT_TRUE(callback_called);
  14946. }
  14947. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14949. ASSERT_TRUE(svr.is_valid());
  14950. svr.Get("/test", [](const Request &, Response &res) {
  14951. res.set_content("ok", "text/plain");
  14952. });
  14953. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14954. auto se = detail::scope_exit([&] {
  14955. svr.stop();
  14956. t.join();
  14957. });
  14958. svr.wait_until_ready();
  14959. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14960. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14961. // so we only check that the request fails, not whether the callback was
  14962. // called.
  14963. SSLClient cli(HOST, PORT);
  14964. cli.enable_server_certificate_verification(true);
  14965. cli.set_connection_timeout(30);
  14966. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14967. EXPECT_NE(session, nullptr);
  14968. return SSLVerifierResponse::NoDecisionMade;
  14969. });
  14970. auto res = cli.Get("/test");
  14971. EXPECT_FALSE(res);
  14972. }
  14973. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14974. // Test SSL server using PemMemory constructor with client CA certificates
  14975. // Read PEM files
  14976. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14977. read_file(SERVER_CERT_FILE, server_cert_pem);
  14978. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14979. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14980. // Create SSLServer with PemMemory constructor including client CA
  14981. SSLServer::PemMemory server_pem = {
  14982. server_cert_pem.c_str(),
  14983. server_cert_pem.size(),
  14984. server_key_pem.c_str(),
  14985. server_key_pem.size(),
  14986. client_ca_pem.c_str(),
  14987. client_ca_pem.size(),
  14988. nullptr // no password for server key
  14989. };
  14990. SSLServer svr(server_pem);
  14991. ASSERT_TRUE(svr.is_valid());
  14992. // No SSL error should be recorded for valid setup
  14993. EXPECT_EQ(0, svr.ssl_last_error());
  14994. // Set up server endpoints
  14995. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14996. res.set_content("ok", "text/plain");
  14997. });
  14998. // Start server in a thread
  14999. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15000. svr.wait_until_ready();
  15001. // Connect with client certificate (using constructor with paths)
  15002. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15003. cli.enable_server_certificate_verification(false);
  15004. auto res = cli.Get("/test-pem-ca");
  15005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15006. EXPECT_EQ(200, res->status);
  15007. EXPECT_EQ("ok", res->body);
  15008. svr.stop();
  15009. server_thread.join();
  15010. }
  15011. #endif
  15012. #ifdef _WIN32
  15013. TEST(CleanupTest, WSACleanup) {
  15014. int ret = WSACleanup();
  15015. ASSERT_EQ(0, ret);
  15016. }
  15017. #endif
  15018. #ifndef CPPHTTPLIB_SSL_ENABLED
  15019. TEST(NoSSLSupport, SimpleInterface) {
  15020. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15021. }
  15022. #endif
  15023. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15024. TEST(InvalidScheme, SimpleInterface) {
  15025. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15026. }
  15027. #endif
  15028. TEST(NoScheme, SimpleInterface) {
  15029. Client cli("yahoo.com:80");
  15030. ASSERT_TRUE(cli.is_valid());
  15031. }
  15032. TEST(SendAPI, SimpleInterface_Online) {
  15033. Client cli("http://yahoo.com");
  15034. Request req;
  15035. req.method = "GET";
  15036. req.path = "/";
  15037. auto res = cli.send(req);
  15038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15039. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15040. }
  15041. TEST(SendAPI, WithParamsInRequest) {
  15042. Server svr;
  15043. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15044. EXPECT_TRUE(req.has_param("test"));
  15045. EXPECT_EQ("test_value", req.get_param_value("test"));
  15046. });
  15047. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15048. auto se = detail::scope_exit([&] {
  15049. svr.stop();
  15050. t.join();
  15051. ASSERT_FALSE(svr.is_running());
  15052. });
  15053. svr.wait_until_ready();
  15054. Client cli(HOST, PORT);
  15055. {
  15056. Request req;
  15057. req.method = "GET";
  15058. req.path = "/";
  15059. req.params.emplace("test", "test_value");
  15060. auto res = cli.send(req);
  15061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15062. }
  15063. {
  15064. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15066. }
  15067. }
  15068. TEST(ClientImplMethods, GetSocketTest) {
  15069. httplib::Server svr;
  15070. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15071. res.status = StatusCode::OK_200;
  15072. });
  15073. auto port = svr.bind_to_any_port("127.0.0.1");
  15074. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15075. auto se = detail::scope_exit([&] {
  15076. svr.stop();
  15077. thread.join();
  15078. ASSERT_FALSE(svr.is_running());
  15079. });
  15080. svr.wait_until_ready();
  15081. {
  15082. httplib::Client cli("127.0.0.1", port);
  15083. cli.set_keep_alive(true);
  15084. // Use the behavior of cpp-httplib of opening the connection
  15085. // only when the first request happens. If that changes,
  15086. // this test would be obsolete.
  15087. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15088. // This also implicitly tests the server. But other tests would fail much
  15089. // earlier than this one to be considered.
  15090. auto res = cli.Get("/");
  15091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15092. EXPECT_EQ(StatusCode::OK_200, res->status);
  15093. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15094. }
  15095. }
  15096. #ifdef CPPHTTPLIB_SSL_ENABLED
  15097. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15098. Client cli("http://yahoo.com");
  15099. auto res = cli.Get("/");
  15100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15101. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15102. cli.set_follow_location(true);
  15103. res = cli.Get("/");
  15104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15105. EXPECT_EQ(StatusCode::OK_200, res->status);
  15106. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15107. }
  15108. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15109. Client cli("https://yahoo.com");
  15110. auto res = cli.Get("/");
  15111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15112. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15113. cli.set_follow_location(true);
  15114. res = cli.Get("/");
  15115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15116. EXPECT_EQ(StatusCode::OK_200, res->status);
  15117. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15118. }
  15119. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15120. Client cli("https://yahoo.com");
  15121. auto res = cli.Get("/");
  15122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15123. ASSERT_FALSE(!res);
  15124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15125. ASSERT_FALSE(res == nullptr);
  15126. ASSERT_TRUE(res != nullptr);
  15127. EXPECT_EQ(Error::Success, res.error());
  15128. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15129. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15130. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15131. cli.set_follow_location(true);
  15132. res = cli.Get("/");
  15133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15134. EXPECT_EQ(Error::Success, res.error());
  15135. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15136. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15137. EXPECT_EQ(StatusCode::OK_200, res->status);
  15138. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15139. }
  15140. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15141. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15142. Client cli("https://cdnjs.cloudflare.com");
  15143. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15144. Headers{{"Accept-Encoding", "br"}});
  15145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15146. EXPECT_EQ(StatusCode::OK_200, res->status);
  15147. EXPECT_EQ(287630U, res->body.size());
  15148. EXPECT_EQ("application/javascript; charset=utf-8",
  15149. res->get_header_value("Content-Type"));
  15150. }
  15151. #endif
  15152. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15153. #undef REDIR_HOST // Silence compiler warning
  15154. #define REDIR_HOST "https://httpbingo.org"
  15155. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15156. Client cli(REDIR_HOST);
  15157. cli.set_follow_location(true);
  15158. auto res =
  15159. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15161. EXPECT_EQ(StatusCode::OK_200, res->status);
  15162. }
  15163. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15164. Client cli(REDIR_HOST);
  15165. cli.set_follow_location(true);
  15166. Params params;
  15167. params.emplace("url", "http://example.com");
  15168. params.emplace("status_code", "302");
  15169. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15171. EXPECT_EQ(StatusCode::OK_200, res->status);
  15172. }
  15173. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15174. Client cli(REDIR_HOST);
  15175. cli.set_follow_location(true);
  15176. Params params;
  15177. params.emplace("url", "http://example.com");
  15178. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15180. EXPECT_EQ(StatusCode::OK_200, res->status);
  15181. }
  15182. TEST(HttpToHttpsRedirectTest, CertFile) {
  15183. auto ssl_port = PORT + 1;
  15184. Server svr;
  15185. ASSERT_TRUE(svr.is_valid());
  15186. svr.Get("/index", [&](const Request &, Response &res) {
  15187. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15188. "/index");
  15189. svr.stop();
  15190. });
  15191. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15192. ASSERT_TRUE(ssl_svr.is_valid());
  15193. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15194. res.set_content("test", "text/plain");
  15195. ssl_svr.stop();
  15196. });
  15197. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15198. thread t2 =
  15199. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15200. auto se = detail::scope_exit([&] {
  15201. t2.join();
  15202. t.join();
  15203. ASSERT_FALSE(svr.is_running());
  15204. });
  15205. svr.wait_until_ready();
  15206. ssl_svr.wait_until_ready();
  15207. Client cli("127.0.0.1", PORT);
  15208. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15209. cli.enable_server_certificate_verification(true);
  15210. cli.set_follow_location(true);
  15211. cli.set_connection_timeout(30);
  15212. auto res = cli.Get("/index");
  15213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15214. ASSERT_EQ(StatusCode::OK_200, res->status);
  15215. }
  15216. TEST(SSLClientRedirectTest, CertFile) {
  15217. auto ssl_port = PORT + 1;
  15218. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15219. ASSERT_TRUE(ssl_svr1.is_valid());
  15220. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15221. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15222. "/index");
  15223. ssl_svr1.stop();
  15224. });
  15225. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15226. ASSERT_TRUE(ssl_svr2.is_valid());
  15227. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15228. res.set_content("test", "text/plain");
  15229. ssl_svr2.stop();
  15230. });
  15231. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15232. thread t2 =
  15233. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15234. auto se = detail::scope_exit([&] {
  15235. t2.join();
  15236. t.join();
  15237. ASSERT_FALSE(ssl_svr1.is_running());
  15238. });
  15239. ssl_svr1.wait_until_ready();
  15240. ssl_svr2.wait_until_ready();
  15241. SSLClient cli("127.0.0.1", PORT);
  15242. std::string cert;
  15243. read_file(SERVER_CERT2_FILE, cert);
  15244. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15245. cli.enable_server_certificate_verification(true);
  15246. cli.set_follow_location(true);
  15247. cli.set_connection_timeout(30);
  15248. auto res = cli.Get("/index");
  15249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15250. ASSERT_EQ(StatusCode::OK_200, res->status);
  15251. }
  15252. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15253. // another port, so the client follows it with a new client.
  15254. static Result GetThroughTlsRedirectToDifferentPort(
  15255. const std::function<void(SSLClient &)> &setup,
  15256. const char *target_cert = SERVER_CERT2_FILE,
  15257. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15258. auto ssl_port = PORT + 1;
  15259. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15260. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15261. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15262. "/index");
  15263. });
  15264. SSLServer ssl_svr2(target_cert, target_key);
  15265. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15266. res.set_content("test", "text/plain");
  15267. });
  15268. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15269. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15270. auto se = detail::scope_exit([&] {
  15271. ssl_svr2.stop();
  15272. ssl_svr1.stop();
  15273. t2.join();
  15274. t.join();
  15275. });
  15276. ssl_svr1.wait_until_ready();
  15277. ssl_svr2.wait_until_ready();
  15278. SSLClient cli("127.0.0.1", PORT);
  15279. cli.set_follow_location(true);
  15280. cli.set_connection_timeout(30);
  15281. setup(cli);
  15282. return cli.Get("/index");
  15283. }
  15284. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15285. auto calls = 0;
  15286. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15287. cli.enable_server_certificate_verification(false);
  15288. // Accept the first server only.
  15289. cli.set_session_verifier([&](tls::session_t) {
  15290. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15291. : SSLVerifierResponse::CertificateRejected;
  15292. });
  15293. });
  15294. ASSERT_FALSE(res);
  15295. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15296. EXPECT_EQ(2, calls);
  15297. }
  15298. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15299. std::string pinned;
  15300. auto res = GetThroughTlsRedirectToDifferentPort(
  15301. [&](SSLClient &cli) {
  15302. cli.enable_server_certificate_verification(false);
  15303. // Pin the first certificate seen.
  15304. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15305. if (pinned.empty()) { pinned = ctx.serial(); }
  15306. return ctx.serial() == pinned;
  15307. });
  15308. },
  15309. // A certificate other than the first server's.
  15310. SERVER_CERT_FILE);
  15311. EXPECT_FALSE(res);
  15312. EXPECT_FALSE(pinned.empty());
  15313. }
  15314. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15315. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15316. std::string cert;
  15317. read_file(SERVER_CERT2_FILE, cert);
  15318. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15319. });
  15320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15321. EXPECT_EQ(StatusCode::OK_200, res->status);
  15322. }
  15323. // The target's certificate is signed by the root CA, which the first server's
  15324. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15325. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15326. auto res = GetThroughTlsRedirectToDifferentPort(
  15327. [](SSLClient &cli) {
  15328. std::string root_ca, cert;
  15329. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15330. read_file(SERVER_CERT2_FILE, cert);
  15331. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15332. cli.load_ca_cert_store(cert.data(), cert.size());
  15333. cli.enable_server_hostname_verification(false);
  15334. },
  15335. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15337. EXPECT_EQ(StatusCode::OK_200, res->status);
  15338. }
  15339. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15340. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15341. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15342. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15343. auto res = GetThroughTlsRedirectToDifferentPort(
  15344. [](SSLClient &cli) {
  15345. std::string root_ca, cert;
  15346. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15347. read_file(SERVER_CERT2_FILE, cert);
  15348. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15349. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15350. cli.enable_server_hostname_verification(false);
  15351. },
  15352. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15353. ASSERT_FALSE(res);
  15354. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15355. }
  15356. #endif
  15357. #endif
  15358. #ifdef CPPHTTPLIB_SSL_ENABLED
  15359. // Test that set_ca_cert_store() skips system certs (consistent with
  15360. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15361. // should be trusted - system certs should NOT be loaded.
  15362. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15363. // Load a specific cert that is NOT a system CA cert
  15364. std::string cert;
  15365. read_file(SERVER_CERT2_FILE, cert);
  15366. SSLClient cli("google.com");
  15367. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15368. cli.enable_server_certificate_verification(true);
  15369. // This should FAIL because:
  15370. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15371. // 2. System certs should NOT be loaded when custom store is set
  15372. // If system certs WERE loaded, this would succeed
  15373. auto res = cli.Get("/");
  15374. ASSERT_FALSE(res);
  15375. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15376. }
  15377. // Same as above, but through the native store handle path. Regression test:
  15378. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15379. // merged system certs into the user-provided store.
  15380. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15381. std::string cert;
  15382. read_file(SERVER_CERT2_FILE, cert);
  15383. SSLClient cli("google.com");
  15384. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15385. cli.enable_server_certificate_verification(true);
  15386. auto res = cli.Get("/");
  15387. ASSERT_FALSE(res);
  15388. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15389. }
  15390. // A custom store set via the native handle must still verify a server whose
  15391. // cert it does contain.
  15392. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15393. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15394. ASSERT_TRUE(svr.is_valid());
  15395. svr.Get("/test", [&](const Request &, Response &res) {
  15396. res.set_content("test", "text/plain");
  15397. });
  15398. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15399. auto se = detail::scope_exit([&] {
  15400. svr.stop();
  15401. t.join();
  15402. ASSERT_FALSE(svr.is_running());
  15403. });
  15404. svr.wait_until_ready();
  15405. SSLClient cli("127.0.0.1", PORT);
  15406. std::string cert;
  15407. read_file(SERVER_CERT2_FILE, cert);
  15408. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15409. cli.enable_server_certificate_verification(true);
  15410. cli.set_connection_timeout(30);
  15411. auto res = cli.Get("/test");
  15412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15413. ASSERT_EQ(StatusCode::OK_200, res->status);
  15414. }
  15415. // CA certs loaded through the universal Client must be transferred to the
  15416. // client created internally for following an HTTPS redirect. Regression test:
  15417. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15418. // the CA data for redirect transfer.
  15419. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15420. auto ssl_port = PORT + 1;
  15421. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15422. ASSERT_TRUE(ssl_svr1.is_valid());
  15423. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15424. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15425. "/index");
  15426. });
  15427. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15428. ASSERT_TRUE(ssl_svr2.is_valid());
  15429. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15430. res.set_content("test", "text/plain");
  15431. });
  15432. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15433. thread t2 =
  15434. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15435. auto se = detail::scope_exit([&] {
  15436. ssl_svr2.stop();
  15437. ssl_svr1.stop();
  15438. t2.join();
  15439. t.join();
  15440. ASSERT_FALSE(ssl_svr1.is_running());
  15441. });
  15442. ssl_svr1.wait_until_ready();
  15443. ssl_svr2.wait_until_ready();
  15444. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15445. std::string cert;
  15446. read_file(SERVER_CERT2_FILE, cert);
  15447. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15448. cli.enable_server_certificate_verification(true);
  15449. cli.set_follow_location(true);
  15450. cli.set_connection_timeout(30);
  15451. auto res = cli.Get("/index");
  15452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15453. ASSERT_EQ(StatusCode::OK_200, res->status);
  15454. }
  15455. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15456. // so a host signed by a system CA verifies even though a custom CA is set
  15457. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15458. std::string cert;
  15459. read_file(SERVER_CERT2_FILE, cert);
  15460. SSLClient cli("google.com");
  15461. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15462. cli.enable_system_ca(true);
  15463. cli.enable_server_certificate_verification(true);
  15464. auto res = cli.Get("/");
  15465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15466. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15467. }
  15468. // The custom CA remains effective when combined with the system CA
  15469. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15470. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15471. ASSERT_TRUE(svr.is_valid());
  15472. svr.Get("/test", [&](const Request &, Response &res) {
  15473. res.set_content("test", "text/plain");
  15474. });
  15475. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15476. auto se = detail::scope_exit([&] {
  15477. svr.stop();
  15478. t.join();
  15479. ASSERT_FALSE(svr.is_running());
  15480. });
  15481. svr.wait_until_ready();
  15482. SSLClient cli("127.0.0.1", PORT);
  15483. std::string cert;
  15484. read_file(SERVER_CERT2_FILE, cert);
  15485. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15486. cli.enable_system_ca(true);
  15487. cli.enable_server_certificate_verification(true);
  15488. cli.set_connection_timeout(30);
  15489. auto res = cli.Get("/test");
  15490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15491. ASSERT_EQ(StatusCode::OK_200, res->status);
  15492. }
  15493. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15494. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15495. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15496. static CFDictionaryRef
  15497. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15498. const SecTrustSettingsResult *result) {
  15499. auto constraint =
  15500. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15501. &kCFTypeDictionaryValueCallBacks);
  15502. if (policy) {
  15503. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15504. }
  15505. if (policy_string) {
  15506. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15507. kCFStringEncodingUTF8);
  15508. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15509. CFRelease(str);
  15510. }
  15511. if (result) {
  15512. auto number_value = static_cast<SInt32>(*result);
  15513. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15514. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15515. CFRelease(number);
  15516. }
  15517. return constraint;
  15518. }
  15519. static SecTrustSettingsResult
  15520. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15521. auto trust_settings =
  15522. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15523. for (auto constraint : constraints) {
  15524. CFArrayAppendValue(trust_settings, constraint);
  15525. CFRelease(constraint);
  15526. }
  15527. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15528. CFRelease(trust_settings);
  15529. return result;
  15530. }
  15531. // The system CA loader takes a Keychain certificate as a trusted root only
  15532. // when its Trust Settings say so for SSL, not merely because it has some.
  15533. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15534. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15535. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15536. const auto deny = kSecTrustSettingsResultDeny;
  15537. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15538. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15539. auto x509_policy = SecPolicyCreateBasicX509();
  15540. // "Always Trust", which stores no constraint at all
  15541. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15542. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15543. ssl_trust_settings_result(
  15544. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15545. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15546. ssl_trust_settings_result(
  15547. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15548. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15549. ssl_trust_settings_result(
  15550. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15551. // "Never Trust", for everything or for SSL
  15552. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15553. ssl_trust_settings_result(
  15554. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15555. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15556. ssl_trust_settings_result(
  15557. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15558. // Trusted for another policy, for one host, or not at all
  15559. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15560. ssl_trust_settings_result(
  15561. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15562. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15563. ssl_trust_settings_result({make_usage_constraint(
  15564. ssl_policy, "www.example.com", &trust_root)}));
  15565. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15566. ssl_trust_settings_result(
  15567. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15568. // The first constraint that applies to SSL decides
  15569. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15570. ssl_trust_settings_result(
  15571. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15572. make_usage_constraint(nullptr, nullptr, &deny)}));
  15573. CFRelease(x509_policy);
  15574. CFRelease(ssl_policy);
  15575. }
  15576. #endif
  15577. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15578. // skip chain verification entirely (only the certificate identity was
  15579. // checked), so a server presenting an untrusted certificate with a matching
  15580. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15581. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15582. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15583. ASSERT_TRUE(svr.is_valid());
  15584. svr.Get("/test", [&](const Request &, Response &res) {
  15585. res.set_content("test", "text/plain");
  15586. });
  15587. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15588. auto se = detail::scope_exit([&] {
  15589. svr.stop();
  15590. t.join();
  15591. ASSERT_FALSE(svr.is_running());
  15592. });
  15593. svr.wait_until_ready();
  15594. SSLClient cli("127.0.0.1", PORT);
  15595. std::string cert;
  15596. // A trusted CA that did not sign the server certificate. The server cert
  15597. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15598. // this connection.
  15599. read_file(CLIENT_CA_CERT_FILE, cert);
  15600. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15601. cli.enable_server_certificate_verification(true);
  15602. cli.set_connection_timeout(30);
  15603. auto res = cli.Get("/test");
  15604. ASSERT_FALSE(res);
  15605. }
  15606. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15607. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15608. // CA that failed to come through fails verification instead of trusting them.
  15609. // (wolfSSL does not list the system CAs it loaded.)
  15610. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15611. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15612. ASSERT_TRUE(svr.is_valid());
  15613. auto port = svr.bind_to_any_port("127.0.0.1");
  15614. ASSERT_LT(0, port);
  15615. thread t = thread([&] { svr.listen_after_bind(); });
  15616. auto se = detail::scope_exit([&] {
  15617. svr.stop();
  15618. t.join();
  15619. ASSERT_FALSE(svr.is_running());
  15620. });
  15621. svr.wait_until_ready();
  15622. // The CAs a client trusts once its first request has loaded them
  15623. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15624. Client cli("https://127.0.0.1:" + std::to_string(port));
  15625. setup(cli);
  15626. cli.Get("/");
  15627. return tls::get_ca_names(cli.tls_context()).size();
  15628. };
  15629. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15630. EXPECT_EQ(0u,
  15631. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15632. }
  15633. #endif
  15634. // A TLS setting changed between requests applies to the next one, not just to
  15635. // the next connection
  15636. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15637. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15638. ASSERT_TRUE(svr.is_valid());
  15639. svr.Get("/", [](const Request &req, Response &res) {
  15640. res.set_content(std::to_string(req.remote_port), "text/plain");
  15641. });
  15642. auto port = svr.bind_to_any_port("127.0.0.1");
  15643. ASSERT_LT(0, port);
  15644. thread t = thread([&] { svr.listen_after_bind(); });
  15645. auto se = detail::scope_exit([&] {
  15646. svr.stop();
  15647. t.join();
  15648. ASSERT_FALSE(svr.is_running());
  15649. });
  15650. svr.wait_until_ready();
  15651. SSLClient cli("127.0.0.1", port);
  15652. cli.set_keep_alive(true);
  15653. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15654. cli.enable_server_certificate_verification(false);
  15655. // The port the request went out from, so a new one means a new connection
  15656. auto client_port = [&] {
  15657. auto res = cli.Get("/");
  15658. return res ? res->body : std::string();
  15659. };
  15660. auto last = client_port();
  15661. ASSERT_FALSE(last.empty());
  15662. // Setting a value it already has keeps the connection
  15663. cli.enable_server_certificate_verification(false);
  15664. cli.enable_server_hostname_verification(true);
  15665. EXPECT_EQ(last, client_port());
  15666. cli.enable_server_certificate_verification(true);
  15667. auto res = cli.Get("/");
  15668. EXPECT_FALSE(res);
  15669. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15670. std::string ca;
  15671. read_file(SERVER_CERT2_FILE, ca);
  15672. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15673. last = client_port();
  15674. ASSERT_FALSE(last.empty());
  15675. std::vector<std::function<void()>> setters = {
  15676. [&] { cli.enable_server_hostname_verification(false); },
  15677. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15678. [&] {
  15679. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15680. },
  15681. [&] {
  15682. cli.set_server_certificate_verifier(
  15683. [](const tls::VerifyContext &) { return true; });
  15684. },
  15685. [&] {
  15686. cli.set_session_verifier(
  15687. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15688. },
  15689. };
  15690. for (const auto &setter : setters) {
  15691. setter();
  15692. auto next = client_port();
  15693. ASSERT_FALSE(next.empty());
  15694. EXPECT_NE(last, next);
  15695. last = next;
  15696. }
  15697. cli.set_session_verifier(
  15698. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15699. auto handle = cli.open_stream("GET", "/");
  15700. EXPECT_FALSE(handle.is_valid());
  15701. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15702. }
  15703. // A PEM given to create_ca_store() needs no NUL after it
  15704. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15705. std::string pem;
  15706. read_file(SERVER_CERT2_FILE, pem);
  15707. auto buf = pem + "X";
  15708. auto store = tls::create_ca_store(buf.data(), pem.size());
  15709. EXPECT_TRUE(store != nullptr);
  15710. SSLClient cli("localhost");
  15711. cli.set_ca_cert_store(store);
  15712. }
  15713. // enable_system_ca(false) prevents system CA loading entirely
  15714. TEST(SSLClientTest, DisableSystemCa_Online) {
  15715. SSLClient cli("google.com");
  15716. cli.enable_system_ca(false);
  15717. cli.enable_server_certificate_verification(true);
  15718. auto res = cli.Get("/");
  15719. ASSERT_FALSE(res);
  15720. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15721. // itself when the CA chain is empty
  15722. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15723. res.error() == Error::SSLConnection);
  15724. }
  15725. // The universal Client forwards enable_system_ca()
  15726. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15727. std::string cert;
  15728. read_file(SERVER_CERT2_FILE, cert);
  15729. Client cli("https://google.com");
  15730. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15731. cli.enable_system_ca(true);
  15732. cli.enable_server_certificate_verification(true);
  15733. auto res = cli.Get("/");
  15734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15735. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15736. }
  15737. // The system CA policy must carry over to the client created internally for
  15738. // following a cross-host HTTPS redirect
  15739. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15740. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15741. ASSERT_TRUE(svr.is_valid());
  15742. svr.Get("/index", [&](const Request &, Response &res) {
  15743. res.set_redirect("https://www.google.com/");
  15744. });
  15745. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15746. auto se = detail::scope_exit([&] {
  15747. svr.stop();
  15748. t.join();
  15749. ASSERT_FALSE(svr.is_running());
  15750. });
  15751. svr.wait_until_ready();
  15752. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15753. std::string cert;
  15754. read_file(SERVER_CERT2_FILE, cert);
  15755. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15756. cli.enable_system_ca(true);
  15757. cli.enable_server_certificate_verification(true);
  15758. cli.set_follow_location(true);
  15759. cli.set_connection_timeout(30);
  15760. // Receiving any response proves the redirect client completed the TLS
  15761. // handshake with a system-CA-signed host
  15762. auto res = cli.Get("/index");
  15763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15764. }
  15765. TEST(MultipartFormDataTest, LargeData) {
  15766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15767. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15768. const ContentReader &content_reader) {
  15769. if (req.is_multipart_form_data()) {
  15770. std::vector<FormData> items;
  15771. content_reader(
  15772. [&](const FormData &file) {
  15773. items.push_back(file);
  15774. return true;
  15775. },
  15776. [&](const char *data, size_t data_length) {
  15777. items.back().content.append(data, data_length);
  15778. return true;
  15779. });
  15780. EXPECT_TRUE(std::string(items[0].name) == "document");
  15781. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15782. EXPECT_TRUE(items[0].filename == "2MB_data");
  15783. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15784. EXPECT_TRUE(items[1].name == "hello");
  15785. EXPECT_TRUE(items[1].content == "world");
  15786. EXPECT_TRUE(items[1].filename == "");
  15787. EXPECT_TRUE(items[1].content_type == "");
  15788. } else {
  15789. std::string body;
  15790. content_reader([&](const char *data, size_t data_length) {
  15791. body.append(data, data_length);
  15792. return true;
  15793. });
  15794. }
  15795. });
  15796. auto port = svr.bind_to_any_port(HOST);
  15797. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15798. auto se = detail::scope_exit([&] {
  15799. svr.stop();
  15800. t.join();
  15801. ASSERT_FALSE(svr.is_running());
  15802. });
  15803. svr.wait_until_ready();
  15804. {
  15805. std::string data(1024 * 1024 * 2, '.');
  15806. std::stringstream buffer;
  15807. buffer << data;
  15808. SSLClient cli(HOST, port);
  15809. cli.enable_server_certificate_verification(false);
  15810. UploadFormDataItems items{
  15811. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15812. {"hello", "world", "", ""},
  15813. };
  15814. auto res = cli.Post("/post", items);
  15815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15816. ASSERT_EQ(StatusCode::OK_200, res->status);
  15817. }
  15818. }
  15819. TEST(MultipartFormDataTest, DataProviderItems) {
  15820. std::random_device seed_gen;
  15821. std::mt19937 random(seed_gen());
  15822. std::string rand1;
  15823. rand1.resize(1000);
  15824. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15825. std::string rand2;
  15826. rand2.resize(3000);
  15827. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15829. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15830. const ContentReader &content_reader) {
  15831. ASSERT_FALSE(req.is_multipart_form_data());
  15832. std::string body;
  15833. content_reader([&](const char *data, size_t data_length) {
  15834. body.append(data, data_length);
  15835. return true;
  15836. });
  15837. EXPECT_EQ(body, "");
  15838. });
  15839. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15840. const ContentReader &content_reader) {
  15841. ASSERT_TRUE(req.is_multipart_form_data());
  15842. std::vector<FormData> items;
  15843. content_reader(
  15844. [&](const FormData &file) {
  15845. items.push_back(file);
  15846. return true;
  15847. },
  15848. [&](const char *data, size_t data_length) {
  15849. items.back().content.append(data, data_length);
  15850. return true;
  15851. });
  15852. ASSERT_TRUE(items.size() == 2);
  15853. EXPECT_EQ(std::string(items[0].name), "name1");
  15854. EXPECT_EQ(items[0].content, "Testing123");
  15855. EXPECT_EQ(items[0].filename, "filename1");
  15856. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15857. EXPECT_EQ(items[1].name, "name2");
  15858. EXPECT_EQ(items[1].content, "Testing456");
  15859. EXPECT_EQ(items[1].filename, "");
  15860. EXPECT_EQ(items[1].content_type, "");
  15861. });
  15862. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15863. const ContentReader &content_reader) {
  15864. ASSERT_TRUE(req.is_multipart_form_data());
  15865. std::vector<FormData> items;
  15866. content_reader(
  15867. [&](const FormData &file) {
  15868. items.push_back(file);
  15869. return true;
  15870. },
  15871. [&](const char *data, size_t data_length) {
  15872. items.back().content.append(data, data_length);
  15873. return true;
  15874. });
  15875. ASSERT_TRUE(items.size() == 2);
  15876. EXPECT_EQ(items[0].name, "name3");
  15877. EXPECT_EQ(items[0].content, rand1);
  15878. EXPECT_EQ(items[0].filename, "filename3");
  15879. EXPECT_EQ(items[0].content_type, "");
  15880. EXPECT_EQ(items[1].name, "name4");
  15881. EXPECT_EQ(items[1].content, rand2);
  15882. EXPECT_EQ(items[1].filename, "filename4");
  15883. EXPECT_EQ(items[1].content_type, "");
  15884. });
  15885. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15886. const ContentReader &content_reader) {
  15887. ASSERT_TRUE(req.is_multipart_form_data());
  15888. std::vector<FormData> items;
  15889. content_reader(
  15890. [&](const FormData &file) {
  15891. items.push_back(file);
  15892. return true;
  15893. },
  15894. [&](const char *data, size_t data_length) {
  15895. items.back().content.append(data, data_length);
  15896. return true;
  15897. });
  15898. ASSERT_TRUE(items.size() == 4);
  15899. EXPECT_EQ(std::string(items[0].name), "name1");
  15900. EXPECT_EQ(items[0].content, "Testing123");
  15901. EXPECT_EQ(items[0].filename, "filename1");
  15902. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15903. EXPECT_EQ(items[1].name, "name2");
  15904. EXPECT_EQ(items[1].content, "Testing456");
  15905. EXPECT_EQ(items[1].filename, "");
  15906. EXPECT_EQ(items[1].content_type, "");
  15907. EXPECT_EQ(items[2].name, "name3");
  15908. EXPECT_EQ(items[2].content, rand1);
  15909. EXPECT_EQ(items[2].filename, "filename3");
  15910. EXPECT_EQ(items[2].content_type, "");
  15911. EXPECT_EQ(items[3].name, "name4");
  15912. EXPECT_EQ(items[3].content, rand2);
  15913. EXPECT_EQ(items[3].filename, "filename4");
  15914. EXPECT_EQ(items[3].content_type, "");
  15915. });
  15916. auto port = svr.bind_to_any_port("localhost");
  15917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15918. auto se = detail::scope_exit([&] {
  15919. svr.stop();
  15920. t.join();
  15921. ASSERT_FALSE(svr.is_running());
  15922. });
  15923. svr.wait_until_ready();
  15924. {
  15925. SSLClient cli("localhost", port);
  15926. cli.enable_server_certificate_verification(false);
  15927. UploadFormDataItems items{
  15928. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15929. {"name2", "Testing456", "", ""}, // not a file
  15930. };
  15931. {
  15932. auto res = cli.Post("/post-none", {}, {}, {});
  15933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15934. ASSERT_EQ(StatusCode::OK_200, res->status);
  15935. }
  15936. FormDataProviderItems providers;
  15937. {
  15938. auto res =
  15939. cli.Post("/post-items", {}, items, providers); // empty providers
  15940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15941. ASSERT_EQ(StatusCode::OK_200, res->status);
  15942. }
  15943. providers.push_back({"name3",
  15944. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15945. // test the offset is given correctly at each step
  15946. if (!offset)
  15947. sink.os.write(rand1.data(), 30);
  15948. else if (offset == 30)
  15949. sink.os.write(rand1.data() + 30, 300);
  15950. else if (offset == 330)
  15951. sink.os.write(rand1.data() + 330, 670);
  15952. else if (offset == rand1.size())
  15953. sink.done();
  15954. return true;
  15955. },
  15956. "filename3",
  15957. {}});
  15958. providers.push_back({"name4",
  15959. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15960. // test the offset is given correctly at each step
  15961. if (!offset)
  15962. sink.os.write(rand2.data(), 2000);
  15963. else if (offset == 2000)
  15964. sink.os.write(rand2.data() + 2000, 1);
  15965. else if (offset == 2001)
  15966. sink.os.write(rand2.data() + 2001, 999);
  15967. else if (offset == rand2.size())
  15968. sink.done();
  15969. return true;
  15970. },
  15971. "filename4",
  15972. {}});
  15973. {
  15974. auto res = cli.Post("/post-providers", {}, {}, providers);
  15975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15976. ASSERT_EQ(StatusCode::OK_200, res->status);
  15977. }
  15978. {
  15979. auto res = cli.Post("/post-both", {}, items, providers);
  15980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15981. ASSERT_EQ(StatusCode::OK_200, res->status);
  15982. }
  15983. }
  15984. }
  15985. TEST(MultipartFormDataTest, BadHeader) {
  15986. Server svr;
  15987. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15988. res.set_content("ok", "text/plain");
  15989. });
  15990. thread t = thread([&] { svr.listen(HOST, PORT); });
  15991. auto se = detail::scope_exit([&] {
  15992. svr.stop();
  15993. t.join();
  15994. ASSERT_FALSE(svr.is_running());
  15995. });
  15996. svr.wait_until_ready();
  15997. const std::string body =
  15998. "This is the preamble. It is to be ignored, though it\r\n"
  15999. "is a handy place for composition agents to include an\r\n"
  16000. "explanatory note to non-MIME conformant readers.\r\n"
  16001. "\r\n"
  16002. "\r\n"
  16003. "--simple boundary\r\n"
  16004. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16005. ": BAD...\r\n"
  16006. "\r\n"
  16007. "value1\r\n"
  16008. "--simple boundary\r\n"
  16009. "Content-Disposition: form-data; name=\"field2\"; "
  16010. "filename=\"example.txt\"\r\n"
  16011. "\r\n"
  16012. "value2\r\n"
  16013. "--simple boundary--\r\n"
  16014. "This is the epilogue. It is also to be ignored.\r\n";
  16015. std::string content_type =
  16016. R"(multipart/form-data; boundary="simple boundary")";
  16017. Client cli(HOST, PORT);
  16018. auto res = cli.Post("/post", body, content_type.c_str());
  16019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16020. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16021. }
  16022. TEST(MultipartFormDataTest, WithPreamble) {
  16023. Server svr;
  16024. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16025. res.set_content("ok", "text/plain");
  16026. });
  16027. thread t = thread([&] { svr.listen(HOST, PORT); });
  16028. auto se = detail::scope_exit([&] {
  16029. svr.stop();
  16030. t.join();
  16031. ASSERT_FALSE(svr.is_running());
  16032. });
  16033. svr.wait_until_ready();
  16034. const std::string body =
  16035. "This is the preamble. It is to be ignored, though it\r\n"
  16036. "is a handy place for composition agents to include an\r\n"
  16037. "explanatory note to non-MIME conformant readers.\r\n"
  16038. "\r\n"
  16039. "\r\n"
  16040. "--simple boundary\r\n"
  16041. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16042. "\r\n"
  16043. "value1\r\n"
  16044. "--simple boundary\r\n"
  16045. "Content-Disposition: form-data; name=\"field2\"; "
  16046. "filename=\"example.txt\"\r\n"
  16047. "\r\n"
  16048. "value2\r\n"
  16049. "--simple boundary--\r\n"
  16050. "This is the epilogue. It is also to be ignored.\r\n";
  16051. std::string content_type =
  16052. R"(multipart/form-data; boundary="simple boundary")";
  16053. Client cli(HOST, PORT);
  16054. auto res = cli.Post("/post", body, content_type.c_str());
  16055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16056. EXPECT_EQ(StatusCode::OK_200, res->status);
  16057. }
  16058. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16060. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16061. const ContentReader &content_reader) {
  16062. if (req.is_multipart_form_data()) {
  16063. std::vector<FormData> items;
  16064. content_reader(
  16065. [&](const FormData &file) {
  16066. items.push_back(file);
  16067. return true;
  16068. },
  16069. [&](const char *data, size_t data_length) {
  16070. items.back().content.append(data, data_length);
  16071. return true;
  16072. });
  16073. EXPECT_TRUE(std::string(items[0].name) == "document");
  16074. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16075. EXPECT_TRUE(items[0].filename == "2MB_data");
  16076. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16077. EXPECT_TRUE(items[1].name == "hello");
  16078. EXPECT_TRUE(items[1].content == "world");
  16079. EXPECT_TRUE(items[1].filename == "");
  16080. EXPECT_TRUE(items[1].content_type == "");
  16081. } else {
  16082. std::string body;
  16083. content_reader([&](const char *data, size_t data_length) {
  16084. body.append(data, data_length);
  16085. return true;
  16086. });
  16087. }
  16088. });
  16089. auto port = svr.bind_to_any_port("localhost");
  16090. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16091. auto se = detail::scope_exit([&] {
  16092. svr.stop();
  16093. t.join();
  16094. ASSERT_FALSE(svr.is_running());
  16095. });
  16096. svr.wait_until_ready();
  16097. {
  16098. std::string data(1024 * 1024 * 2, '.');
  16099. std::stringstream buffer;
  16100. buffer << data;
  16101. SSLClient cli("localhost", port);
  16102. cli.enable_server_certificate_verification(false);
  16103. UploadFormDataItems items{
  16104. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16105. {"hello", "world", "", ""},
  16106. };
  16107. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16109. ASSERT_EQ(StatusCode::OK_200, res->status);
  16110. }
  16111. }
  16112. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16113. std::string data(1024 * 1024 * 2, '&');
  16114. std::stringstream buffer;
  16115. buffer << data;
  16116. Client cli("https://localhost:8080");
  16117. UploadFormDataItems items{
  16118. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16119. {"hello", "world", "", ""},
  16120. };
  16121. for (const char &c : " \t\r\n") {
  16122. auto res =
  16123. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16124. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16125. ASSERT_FALSE(res);
  16126. }
  16127. }
  16128. TEST(MultipartFormDataTest, PutFormData) {
  16129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16130. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16131. const ContentReader &content_reader) {
  16132. if (req.is_multipart_form_data()) {
  16133. std::vector<FormData> items;
  16134. content_reader(
  16135. [&](const FormData &file) {
  16136. items.push_back(file);
  16137. return true;
  16138. },
  16139. [&](const char *data, size_t data_length) {
  16140. items.back().content.append(data, data_length);
  16141. return true;
  16142. });
  16143. EXPECT_TRUE(std::string(items[0].name) == "document");
  16144. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16145. EXPECT_TRUE(items[0].filename == "2MB_data");
  16146. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16147. EXPECT_TRUE(items[1].name == "hello");
  16148. EXPECT_TRUE(items[1].content == "world");
  16149. EXPECT_TRUE(items[1].filename == "");
  16150. EXPECT_TRUE(items[1].content_type == "");
  16151. } else {
  16152. std::string body;
  16153. content_reader([&](const char *data, size_t data_length) {
  16154. body.append(data, data_length);
  16155. return true;
  16156. });
  16157. }
  16158. });
  16159. auto port = svr.bind_to_any_port("localhost");
  16160. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16161. auto se = detail::scope_exit([&] {
  16162. svr.stop();
  16163. t.join();
  16164. ASSERT_FALSE(svr.is_running());
  16165. });
  16166. svr.wait_until_ready();
  16167. {
  16168. std::string data(1024 * 1024 * 2, '&');
  16169. std::stringstream buffer;
  16170. buffer << data;
  16171. SSLClient cli("localhost", port);
  16172. cli.enable_server_certificate_verification(false);
  16173. UploadFormDataItems items{
  16174. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16175. {"hello", "world", "", ""},
  16176. };
  16177. auto res = cli.Put("/put", items);
  16178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16179. ASSERT_EQ(StatusCode::OK_200, res->status);
  16180. }
  16181. }
  16182. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16184. svr.Put("/put_customboundary",
  16185. [&](const Request &req, const Response & /*res*/,
  16186. const ContentReader &content_reader) {
  16187. if (req.is_multipart_form_data()) {
  16188. std::vector<FormData> items;
  16189. content_reader(
  16190. [&](const FormData &file) {
  16191. items.push_back(file);
  16192. return true;
  16193. },
  16194. [&](const char *data, size_t data_length) {
  16195. items.back().content.append(data, data_length);
  16196. return true;
  16197. });
  16198. EXPECT_TRUE(std::string(items[0].name) == "document");
  16199. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16200. EXPECT_TRUE(items[0].filename == "2MB_data");
  16201. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16202. EXPECT_TRUE(items[1].name == "hello");
  16203. EXPECT_TRUE(items[1].content == "world");
  16204. EXPECT_TRUE(items[1].filename == "");
  16205. EXPECT_TRUE(items[1].content_type == "");
  16206. } else {
  16207. std::string body;
  16208. content_reader([&](const char *data, size_t data_length) {
  16209. body.append(data, data_length);
  16210. return true;
  16211. });
  16212. }
  16213. });
  16214. auto port = svr.bind_to_any_port("localhost");
  16215. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16216. auto se = detail::scope_exit([&] {
  16217. svr.stop();
  16218. t.join();
  16219. ASSERT_FALSE(svr.is_running());
  16220. });
  16221. svr.wait_until_ready();
  16222. {
  16223. std::string data(1024 * 1024 * 2, '&');
  16224. std::stringstream buffer;
  16225. buffer << data;
  16226. SSLClient cli("localhost", port);
  16227. cli.enable_server_certificate_verification(false);
  16228. UploadFormDataItems items{
  16229. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16230. {"hello", "world", "", ""},
  16231. };
  16232. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16234. ASSERT_EQ(StatusCode::OK_200, res->status);
  16235. }
  16236. }
  16237. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16238. std::string data(1024 * 1024 * 2, '&');
  16239. std::stringstream buffer;
  16240. buffer << data;
  16241. Client cli("https://localhost:8080");
  16242. cli.enable_server_certificate_verification(false);
  16243. UploadFormDataItems items{
  16244. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16245. {"hello", "world", "", ""},
  16246. };
  16247. for (const char &c : " \t\r\n") {
  16248. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16249. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16250. ASSERT_FALSE(res);
  16251. }
  16252. }
  16253. TEST(MultipartFormDataTest, AlternateFilename) {
  16254. auto handled = false;
  16255. Server svr;
  16256. svr.Post("/test", [&](const Request &req, Response &res) {
  16257. ASSERT_EQ(2u, req.form.files.size());
  16258. ASSERT_EQ(1u, req.form.fields.size());
  16259. // Test files
  16260. const auto &file1 = req.form.get_file("file1");
  16261. ASSERT_EQ("file1", file1.name);
  16262. ASSERT_EQ("A.txt", file1.filename);
  16263. ASSERT_EQ("text/plain", file1.content_type);
  16264. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16265. const auto &file2 = req.form.get_file("file2");
  16266. ASSERT_EQ("file2", file2.name);
  16267. ASSERT_EQ("a.html", file2.filename);
  16268. ASSERT_EQ("text/html", file2.content_type);
  16269. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16270. file2.content);
  16271. // Test text field
  16272. const auto &text = req.form.get_field("text");
  16273. ASSERT_EQ("text default", text);
  16274. res.set_content("ok", "text/plain");
  16275. handled = true;
  16276. });
  16277. thread t = thread([&] { svr.listen(HOST, PORT); });
  16278. auto se = detail::scope_exit([&] {
  16279. svr.stop();
  16280. t.join();
  16281. ASSERT_FALSE(svr.is_running());
  16282. ASSERT_TRUE(handled);
  16283. });
  16284. svr.wait_until_ready();
  16285. auto req = "POST /test HTTP/1.1\r\n"
  16286. "Host: localhost\r\n"
  16287. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16288. "Content-Length: 399\r\n"
  16289. "\r\n"
  16290. "----------\r\n"
  16291. "Content-Disposition: form-data; name=\"text\"\r\n"
  16292. "\r\n"
  16293. "text default\r\n"
  16294. "----------\r\n"
  16295. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16296. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16297. "Content-Type: text/plain\r\n"
  16298. "\r\n"
  16299. "Content of a.txt.\r\n"
  16300. "\r\n"
  16301. "----------\r\n"
  16302. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16303. "\"a.html\"\r\n"
  16304. "Content-Type: text/html\r\n"
  16305. "\r\n"
  16306. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16307. "\r\n"
  16308. "------------\r\n";
  16309. ASSERT_TRUE(send_request(1, req));
  16310. }
  16311. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16312. auto handled = false;
  16313. Server svr;
  16314. svr.Post("/test", [&](const Request &req, Response &res) {
  16315. // Case-insensitive "utf-8''" prefix with a long value
  16316. const auto &file = req.form.get_file("file1");
  16317. ASSERT_EQ("file1", file.name);
  16318. // 8000 chars exercises both the Content-Disposition parser and the
  16319. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16320. // Prior to the fix, std::regex_match on this header would cause O(N)
  16321. // stack recursion in libstdc++, leading to SIGSEGV.
  16322. std::string expected_filename(8000, 'A');
  16323. ASSERT_EQ(expected_filename, file.filename);
  16324. res.set_content("ok", "text/plain");
  16325. handled = true;
  16326. });
  16327. thread t = thread([&] { svr.listen(HOST, PORT); });
  16328. auto se = detail::scope_exit([&] {
  16329. svr.stop();
  16330. t.join();
  16331. ASSERT_FALSE(svr.is_running());
  16332. ASSERT_TRUE(handled);
  16333. });
  16334. svr.wait_until_ready();
  16335. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16336. // Regression test for GHSA-qq6v-r583-3h69
  16337. std::string long_filename(8000, 'A');
  16338. std::string body = "----------\r\n"
  16339. "Content-Disposition: form-data; name=\"file1\"; "
  16340. "filename*=\"Utf-8''" +
  16341. long_filename +
  16342. "\"\r\n"
  16343. "\r\n"
  16344. "hello\r\n"
  16345. "------------\r\n";
  16346. auto req = "POST /test HTTP/1.1\r\n"
  16347. "Host: localhost\r\n"
  16348. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16349. "Content-Length: " +
  16350. std::to_string(body.size()) + "\r\n\r\n" + body;
  16351. ASSERT_TRUE(send_request(1, req));
  16352. }
  16353. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16354. auto handled = false;
  16355. Server svr;
  16356. svr.Post("/test", [&](const Request &req, Response &) {
  16357. ASSERT_EQ(2u, req.form.fields.size());
  16358. const auto &text1 = req.form.get_field("text1");
  16359. ASSERT_EQ("text1", text1);
  16360. const auto &text2 = req.form.get_field("text2");
  16361. ASSERT_EQ("text2", text2);
  16362. handled = true;
  16363. });
  16364. thread t = thread([&] { svr.listen(HOST, PORT); });
  16365. auto se = detail::scope_exit([&] {
  16366. svr.stop();
  16367. t.join();
  16368. ASSERT_FALSE(svr.is_running());
  16369. ASSERT_TRUE(handled);
  16370. });
  16371. svr.wait_until_ready();
  16372. auto req = "POST /test HTTP/1.1\r\n"
  16373. "Host: localhost\r\n"
  16374. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16375. "Content-Length: 146\r\n"
  16376. "\r\n----------\r\n"
  16377. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16378. "\r\n"
  16379. "text1"
  16380. "\r\n----------\r\n"
  16381. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16382. "\r\n"
  16383. "text2"
  16384. "\r\n------------";
  16385. std::string response;
  16386. ASSERT_TRUE(send_request(1, req, &response));
  16387. ASSERT_EQ("200", response.substr(9, 3));
  16388. }
  16389. TEST(MultipartFormDataTest, ContentLength) {
  16390. auto handled = false;
  16391. Server svr;
  16392. svr.Post("/test", [&](const Request &req, Response &) {
  16393. ASSERT_EQ(2u, req.form.fields.size());
  16394. const auto &text1 = req.form.get_field("text1");
  16395. ASSERT_EQ("text1", text1);
  16396. const auto &text2 = req.form.get_field("text2");
  16397. ASSERT_EQ("text2", text2);
  16398. handled = true;
  16399. });
  16400. thread t = thread([&] { svr.listen(HOST, PORT); });
  16401. auto se = detail::scope_exit([&] {
  16402. svr.stop();
  16403. t.join();
  16404. ASSERT_FALSE(svr.is_running());
  16405. ASSERT_TRUE(handled);
  16406. });
  16407. svr.wait_until_ready();
  16408. auto req = "POST /test HTTP/1.1\r\n"
  16409. "Host: localhost\r\n"
  16410. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16411. "Content-Length: 167\r\n"
  16412. "\r\n----------\r\n"
  16413. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16414. "Content-Length: 5\r\n"
  16415. "\r\n"
  16416. "text1"
  16417. "\r\n----------\r\n"
  16418. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16419. "\r\n"
  16420. "text2"
  16421. "\r\n------------\r\n";
  16422. std::string response;
  16423. ASSERT_TRUE(send_request(1, req, &response));
  16424. ASSERT_EQ("200", response.substr(9, 3));
  16425. }
  16426. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16427. auto handled = false;
  16428. Server svr;
  16429. svr.Post("/test", [&](const Request &req, Response &) {
  16430. ASSERT_EQ(2u, req.form.fields.size());
  16431. const auto &text1 = req.form.get_field("text1");
  16432. ASSERT_EQ("text1", text1);
  16433. // TODO: Add header access for text fields if needed
  16434. const auto &text2 = req.form.get_field("text2");
  16435. ASSERT_EQ("text2", text2);
  16436. // TODO: Header access for text fields needs to be implemented
  16437. // auto &headers = it->second.headers;
  16438. // ASSERT_EQ(3U, headers.size());
  16439. // auto custom_header = headers.find("x-whatever");
  16440. // ASSERT_TRUE(custom_header != headers.end());
  16441. // ASSERT_NE("customvalue", custom_header->second);
  16442. // ASSERT_EQ("CustomValue", custom_header->second);
  16443. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16444. handled = true;
  16445. });
  16446. thread t = thread([&] { svr.listen(HOST, PORT); });
  16447. auto se = detail::scope_exit([&] {
  16448. svr.stop();
  16449. t.join();
  16450. ASSERT_FALSE(svr.is_running());
  16451. ASSERT_TRUE(handled);
  16452. });
  16453. svr.wait_until_ready();
  16454. auto req = "POST /test HTTP/1.1\r\n"
  16455. "Host: localhost\r\n"
  16456. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16457. "Content-Length: 232\r\n"
  16458. "\r\n----------\r\n"
  16459. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16460. "Content-Length: 5\r\n"
  16461. "X-Test: 1\r\n"
  16462. "\r\n"
  16463. "text1"
  16464. "\r\n----------\r\n"
  16465. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16466. "Content-Type: text/plain\r\n"
  16467. "X-Whatever: CustomValue\r\n"
  16468. "\r\n"
  16469. "text2"
  16470. "\r\n------------\r\n"
  16471. "That should be disregarded. Not even read";
  16472. std::string response;
  16473. ASSERT_TRUE(send_request(1, req, &response));
  16474. ASSERT_EQ("200", response.substr(9, 3));
  16475. }
  16476. TEST(MultipartFormDataTest, LargeHeader) {
  16477. auto handled = false;
  16478. Server svr;
  16479. svr.Post("/test", [&](const Request &req, Response &) {
  16480. ASSERT_EQ(1u, req.form.fields.size());
  16481. const auto &text = req.form.get_field("name1");
  16482. ASSERT_EQ("text1", text);
  16483. handled = true;
  16484. });
  16485. thread t = thread([&] { svr.listen(HOST, PORT); });
  16486. auto se = detail::scope_exit([&] {
  16487. svr.stop();
  16488. t.join();
  16489. ASSERT_FALSE(svr.is_running());
  16490. ASSERT_TRUE(handled);
  16491. });
  16492. svr.wait_until_ready();
  16493. auto boundary = std::string("cpp-httplib-multipart-data");
  16494. std::string content = "--" + boundary +
  16495. "\r\n"
  16496. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16497. "\r\n"
  16498. "text1\r\n"
  16499. "--" +
  16500. boundary + "--\r\n";
  16501. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16502. "Host: localhost\r\n"
  16503. "Content-Type: multipart/form-data;boundary=" +
  16504. boundary +
  16505. "\r\n"
  16506. "Content-Length: " +
  16507. std::to_string(content.size()) +
  16508. "\r\n"
  16509. "Dummy-Header: ";
  16510. std::string header_suffix = "\r\n"
  16511. "\r\n";
  16512. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16513. size_t header_dummy_size =
  16514. read_buff_size -
  16515. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16516. auto header_dummy = std::string(header_dummy_size, '@');
  16517. auto req = header_prefix + header_dummy + header_suffix + content;
  16518. std::string response;
  16519. ASSERT_TRUE(send_request(1, req, &response));
  16520. ASSERT_EQ("200", response.substr(9, 3));
  16521. }
  16522. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16523. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16524. // (not chunked Transfer-Encoding) after the streaming refactor.
  16525. auto handled = false;
  16526. Server svr;
  16527. svr.Post("/upload", [&](const Request &req, Response &res) {
  16528. auto cl_it = req.headers.find("Content-Length");
  16529. EXPECT_TRUE(cl_it != req.headers.end());
  16530. auto te_it = req.headers.find("Transfer-Encoding");
  16531. EXPECT_TRUE(te_it == req.headers.end());
  16532. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16533. res.set_content("ok", "text/plain");
  16534. handled = true;
  16535. });
  16536. auto port = svr.bind_to_any_port(HOST);
  16537. auto t = thread([&] { svr.listen_after_bind(); });
  16538. auto se = detail::scope_exit([&] {
  16539. svr.stop();
  16540. t.join();
  16541. ASSERT_FALSE(svr.is_running());
  16542. ASSERT_TRUE(handled);
  16543. });
  16544. svr.wait_until_ready();
  16545. UploadFormDataItems items = {
  16546. {"field1", "hello", "", "text/plain"},
  16547. {"file1", "world", "test.txt", "application/octet-stream"},
  16548. };
  16549. Client cli(HOST, port);
  16550. auto res = cli.Post("/upload", {}, items);
  16551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16552. EXPECT_EQ(StatusCode::OK_200, res->status);
  16553. }
  16554. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16555. // Verify that make_multipart_content_provider coalesces many small segments
  16556. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16557. constexpr size_t kItemCount = 1000;
  16558. UploadFormDataItems items;
  16559. items.reserve(kItemCount);
  16560. for (size_t i = 0; i < kItemCount; i++) {
  16561. items.push_back(
  16562. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16563. }
  16564. const std::string boundary = "----test-boundary";
  16565. auto content_length = detail::get_multipart_content_length(items, boundary);
  16566. auto provider = detail::make_multipart_content_provider(items, boundary);
  16567. // Drive the provider the same way write_content_with_progress does
  16568. size_t write_count = 0;
  16569. size_t total_bytes = 0;
  16570. DataSink sink;
  16571. size_t offset = 0;
  16572. sink.write = [&](const char *d, size_t l) -> bool {
  16573. (void)d;
  16574. write_count++;
  16575. total_bytes += l;
  16576. offset += l;
  16577. return true;
  16578. };
  16579. sink.is_writable = []() -> bool { return true; };
  16580. while (offset < content_length) {
  16581. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16582. }
  16583. EXPECT_EQ(content_length, total_bytes);
  16584. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16585. // With buffering into 64KB blocks, write_count should be much smaller.
  16586. auto segment_count = 3 * kItemCount + 1;
  16587. EXPECT_LT(write_count, segment_count / 10);
  16588. }
  16589. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16590. // Integration test: send many UploadFormDataItems and verify the server
  16591. // receives all of them correctly (#2410).
  16592. constexpr size_t kItemCount = 500;
  16593. auto handled = false;
  16594. Server svr;
  16595. svr.Post("/upload", [&](const Request &req, Response &res) {
  16596. EXPECT_EQ(kItemCount, req.form.fields.size());
  16597. for (size_t i = 0; i < kItemCount; i++) {
  16598. auto key = "field" + std::to_string(i);
  16599. auto val = "value" + std::to_string(i);
  16600. auto it = req.form.fields.find(key);
  16601. if (it != req.form.fields.end()) {
  16602. EXPECT_EQ(val, it->second.content);
  16603. } else {
  16604. ADD_FAILURE() << "Missing field: " << key;
  16605. }
  16606. }
  16607. res.set_content("ok", "text/plain");
  16608. handled = true;
  16609. });
  16610. auto port = svr.bind_to_any_port(HOST);
  16611. auto t = thread([&] { svr.listen_after_bind(); });
  16612. auto se = detail::scope_exit([&] {
  16613. svr.stop();
  16614. t.join();
  16615. ASSERT_FALSE(svr.is_running());
  16616. ASSERT_TRUE(handled);
  16617. });
  16618. svr.wait_until_ready();
  16619. UploadFormDataItems items;
  16620. items.reserve(kItemCount);
  16621. for (size_t i = 0; i < kItemCount; i++) {
  16622. items.push_back(
  16623. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16624. }
  16625. Client cli(HOST, port);
  16626. auto res = cli.Post("/upload", items);
  16627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16628. EXPECT_EQ(StatusCode::OK_200, res->status);
  16629. }
  16630. TEST(MultipartFormDataTest, MakeFileProvider) {
  16631. // Verify make_file_provider sends a file's contents correctly.
  16632. const std::string file_content(4096, 'Z');
  16633. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16634. {
  16635. std::ofstream ofs(tmp_path, std::ios::binary);
  16636. ofs.write(file_content.data(),
  16637. static_cast<std::streamsize>(file_content.size()));
  16638. }
  16639. auto handled = false;
  16640. Server svr;
  16641. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16642. const ContentReader &content_reader) {
  16643. ASSERT_TRUE(req.is_multipart_form_data());
  16644. std::vector<FormData> items;
  16645. content_reader(
  16646. [&](const FormData &file) {
  16647. items.push_back(file);
  16648. return true;
  16649. },
  16650. [&](const char *data, size_t data_length) {
  16651. items.back().content.append(data, data_length);
  16652. return true;
  16653. });
  16654. ASSERT_EQ(1u, items.size());
  16655. EXPECT_EQ("myfile", items[0].name);
  16656. EXPECT_EQ("data.bin", items[0].filename);
  16657. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16658. EXPECT_EQ(file_content, items[0].content);
  16659. handled = true;
  16660. });
  16661. auto port = svr.bind_to_any_port(HOST);
  16662. auto t = thread([&] { svr.listen_after_bind(); });
  16663. auto se = detail::scope_exit([&] {
  16664. svr.stop();
  16665. t.join();
  16666. ASSERT_FALSE(svr.is_running());
  16667. ASSERT_TRUE(handled);
  16668. std::remove(tmp_path.c_str());
  16669. });
  16670. svr.wait_until_ready();
  16671. FormDataProviderItems providers;
  16672. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16673. "application/octet-stream"));
  16674. Client cli(HOST, port);
  16675. auto res = cli.Post("/upload", {}, {}, providers);
  16676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16677. EXPECT_EQ(StatusCode::OK_200, res->status);
  16678. }
  16679. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16680. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16681. // (100) headers is rejected with a 400 Bad Request response.
  16682. Server svr;
  16683. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16684. res.set_content("ok", "text/plain");
  16685. });
  16686. thread t = thread([&] { svr.listen(HOST, PORT); });
  16687. auto se = detail::scope_exit([&] {
  16688. svr.stop();
  16689. t.join();
  16690. ASSERT_FALSE(svr.is_running());
  16691. });
  16692. svr.wait_until_ready();
  16693. // Build a multipart part with 101 custom headers (exceeding
  16694. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16695. std::stringstream body;
  16696. body << "--simpleboundary\r\n"
  16697. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16698. for (int i = 0; i < 101; i++) {
  16699. body << "X-Custom-Header-" << i << ": value\r\n";
  16700. }
  16701. body << "\r\n"
  16702. << "value1\r\n"
  16703. << "--simpleboundary--\r\n";
  16704. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16705. Client cli(HOST, PORT);
  16706. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16708. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16709. }
  16710. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16711. // A body that never contains the declared boundary must not be accumulated
  16712. // while the parser waits for it. Buffering it would also make every read
  16713. // rescan everything seen so far, which is quadratic in the body size.
  16714. Server svr;
  16715. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16716. res.set_content("ok", "text/plain");
  16717. });
  16718. auto port = svr.bind_to_any_port(HOST);
  16719. thread t = thread([&] { svr.listen_after_bind(); });
  16720. auto se = detail::scope_exit([&] {
  16721. svr.stop();
  16722. t.join();
  16723. ASSERT_FALSE(svr.is_running());
  16724. });
  16725. svr.wait_until_ready();
  16726. Client cli(HOST, port);
  16727. cli.set_read_timeout(60, 0);
  16728. cli.set_write_timeout(60, 0);
  16729. // '-' is the worst case: it matches the first character of the boundary, so
  16730. // every position has to be checked against it.
  16731. auto post_dashes = [&](size_t size) {
  16732. const std::string body(size, '-');
  16733. auto start = std::chrono::steady_clock::now();
  16734. auto res =
  16735. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16736. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16737. std::chrono::steady_clock::now() - start)
  16738. .count();
  16739. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16740. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16741. return ms;
  16742. };
  16743. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16744. // Windows.
  16745. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16746. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16747. // Comparing the two sizes rather than checking an absolute duration keeps
  16748. // this meaningful across build types and CI load, both of which move the
  16749. // absolute numbers by more than an order of magnitude. Four times the bytes
  16750. // costs about four times the time when parsing is linear, and about sixteen
  16751. // times when the body is buffered and rescanned.
  16752. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16753. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16754. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16755. << "ms, which suggests the body is being buffered and rescanned";
  16756. }
  16757. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16758. // A boundary can only be followed by CRLF or by "--", so anything else is
  16759. // malformed no matter what comes next. The parser must say so right away
  16760. // instead of buffering the rest of the declared body.
  16761. Server svr;
  16762. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16763. res.set_content("ok", "text/plain");
  16764. });
  16765. auto port = svr.bind_to_any_port(HOST);
  16766. thread t = thread([&] { svr.listen_after_bind(); });
  16767. auto se = detail::scope_exit([&] {
  16768. svr.stop();
  16769. t.join();
  16770. ASSERT_FALSE(svr.is_running());
  16771. });
  16772. svr.wait_until_ready();
  16773. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16774. // buffers instead of failing would still be waiting for the remaining bytes.
  16775. const std::string body = "--zzzz\r\n"
  16776. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16777. "\r\n"
  16778. "text1"
  16779. "\r\n--zzzzXX";
  16780. const std::string req = "POST /post HTTP/1.1\r\n"
  16781. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16782. "Content-Length: 1048576\r\n"
  16783. "\r\n" +
  16784. body;
  16785. std::string response;
  16786. ASSERT_TRUE(send_request(3, req, &response, port));
  16787. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16788. EXPECT_EQ("400", response.substr(9, 3));
  16789. }
  16790. // Posts a multipart body split into two writes, so that the server sees the
  16791. // split at whatever offset the caller chose, and expects the single "text1"
  16792. // field to come through.
  16793. static void expect_split_multipart_ok(const std::string &body1,
  16794. const std::string &body2) {
  16795. auto handled = false;
  16796. Server svr;
  16797. svr.Post("/post", [&](const Request &req, Response &) {
  16798. EXPECT_EQ(1u, req.form.fields.size());
  16799. EXPECT_EQ("text1", req.form.get_field("text1"));
  16800. handled = true;
  16801. });
  16802. auto port = svr.bind_to_any_port(HOST);
  16803. thread t = thread([&] { svr.listen_after_bind(); });
  16804. auto se = detail::scope_exit([&] {
  16805. svr.stop();
  16806. t.join();
  16807. ASSERT_FALSE(svr.is_running());
  16808. ASSERT_TRUE(handled);
  16809. });
  16810. svr.wait_until_ready();
  16811. // "Connection: close" makes the server close once it has answered, so the
  16812. // response drain ends immediately instead of idling until the read timeout.
  16813. const std::string head =
  16814. "POST /post HTTP/1.1\r\n"
  16815. "Host: localhost\r\n"
  16816. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16817. "Connection: close\r\n"
  16818. "Content-Length: " +
  16819. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16820. std::string response;
  16821. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16822. ASSERT_GE(response.size(), 12u) << "no response";
  16823. EXPECT_EQ("200", response.substr(9, 3));
  16824. }
  16825. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16826. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16827. // ignored, including when it does not arrive in the same read as the
  16828. // close-delimiter itself.
  16829. expect_split_multipart_ok("--zzzz\r\n"
  16830. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16831. "\r\n"
  16832. "text1"
  16833. "\r\n--zzzz--",
  16834. "\r\nthis epilogue must be ignored\r\n");
  16835. }
  16836. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16837. // The initial boundary may be preceded by a preamble of any length and may
  16838. // straddle a read boundary. Discarding data while waiting for it must not
  16839. // throw away a partial boundary sitting at the end of the buffer.
  16840. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16841. "zz\r\n"
  16842. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16843. "\r\n"
  16844. "text1"
  16845. "\r\n--zzzz--\r\n");
  16846. }
  16847. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16848. // The received boundary was only checked for being non-empty, so it could be
  16849. // as long as a header is allowed to be. The parser scans the body for
  16850. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16851. // costs a nearly full comparison at nearly every position, making the
  16852. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16853. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16854. Server svr;
  16855. svr.Post("/post", [](const Request &req, Response &res) {
  16856. EXPECT_EQ(1u, req.form.fields.size());
  16857. EXPECT_EQ("text1", req.form.get_field("text1"));
  16858. res.set_content("ok", "text/plain");
  16859. });
  16860. auto port = svr.bind_to_any_port(HOST);
  16861. thread t = thread([&] { svr.listen_after_bind(); });
  16862. auto se = detail::scope_exit([&] {
  16863. svr.stop();
  16864. t.join();
  16865. ASSERT_FALSE(svr.is_running());
  16866. });
  16867. svr.wait_until_ready();
  16868. Client cli(HOST, port);
  16869. auto post_with_boundary_of_length = [&](size_t len) {
  16870. const std::string boundary(len, 'a');
  16871. const std::string body =
  16872. "--" + boundary +
  16873. "\r\n"
  16874. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16875. "\r\n"
  16876. "text1"
  16877. "\r\n--" +
  16878. boundary + "--\r\n";
  16879. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16880. };
  16881. auto res = post_with_boundary_of_length(70);
  16882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16883. EXPECT_EQ(StatusCode::OK_200, res->status);
  16884. res = post_with_boundary_of_length(71);
  16885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16886. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16887. }
  16888. TEST(MakeFileBodyTest, Basic) {
  16889. const std::string file_content(4096, 'Z');
  16890. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16891. {
  16892. std::ofstream ofs(tmp_path, std::ios::binary);
  16893. ofs.write(file_content.data(),
  16894. static_cast<std::streamsize>(file_content.size()));
  16895. }
  16896. auto handled = false;
  16897. Server svr;
  16898. svr.Post("/upload", [&](const Request &req, Response &res) {
  16899. EXPECT_EQ(file_content, req.body);
  16900. handled = true;
  16901. res.status = StatusCode::OK_200;
  16902. });
  16903. auto port = svr.bind_to_any_port(HOST);
  16904. auto t = thread([&] { svr.listen_after_bind(); });
  16905. auto se = detail::scope_exit([&] {
  16906. svr.stop();
  16907. t.join();
  16908. ASSERT_FALSE(svr.is_running());
  16909. ASSERT_TRUE(handled);
  16910. std::remove(tmp_path.c_str());
  16911. });
  16912. svr.wait_until_ready();
  16913. auto fb = make_file_body(tmp_path);
  16914. ASSERT_GT(fb.first, 0u);
  16915. Client cli(HOST, port);
  16916. auto res =
  16917. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16919. EXPECT_EQ(StatusCode::OK_200, res->status);
  16920. }
  16921. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16922. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16923. {
  16924. std::ofstream ofs(path, std::ios::binary);
  16925. const std::string content(100, 'A');
  16926. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16927. }
  16928. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16929. auto body = make_file_body(path);
  16930. ASSERT_EQ(100u, body.first);
  16931. ASSERT_TRUE(static_cast<bool>(body.second));
  16932. // Rewritten shorter after its length was measured - and, on a server, after
  16933. // that length has already gone out as Content-Length.
  16934. {
  16935. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16936. const std::string content(10, 'A');
  16937. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16938. }
  16939. std::string written;
  16940. DataSink sink;
  16941. sink.write = [&](const char *d, size_t l) {
  16942. written.append(d, l);
  16943. return true;
  16944. };
  16945. // The provider has to report failure. write_content_with_progress() advances
  16946. // its offset only by what was written, so a provider that returns true
  16947. // without completing the length it promised is called again straight away,
  16948. // and again.
  16949. EXPECT_FALSE(body.second(0, body.first, sink));
  16950. EXPECT_EQ(std::string(10, 'A'), written);
  16951. }
  16952. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16953. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16954. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16955. {
  16956. std::ofstream ofs(path, std::ios::binary);
  16957. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16958. }
  16959. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16960. auto body = make_file_body(path);
  16961. ASSERT_EQ(content.size(), body.first);
  16962. ASSERT_TRUE(static_cast<bool>(body.second));
  16963. std::string written;
  16964. DataSink sink;
  16965. sink.write = [&](const char *d, size_t l) {
  16966. written.append(d, l);
  16967. return true;
  16968. };
  16969. EXPECT_TRUE(body.second(0, body.first, sink));
  16970. EXPECT_EQ(content, written);
  16971. }
  16972. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16973. static constexpr unsigned int number_of_tasks{1000000};
  16974. std::atomic_uint count{0};
  16975. std::unique_ptr<TaskQueue> task_queue{
  16976. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16977. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16978. auto queued = task_queue->enqueue(
  16979. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16980. EXPECT_TRUE(queued);
  16981. }
  16982. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16983. task_queue->shutdown();
  16984. #else
  16985. EXPECT_NO_THROW(task_queue->shutdown());
  16986. #endif
  16987. EXPECT_EQ(number_of_tasks, count.load());
  16988. }
  16989. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16990. static constexpr unsigned int number_of_tasks{1000000};
  16991. static constexpr unsigned int qlimit{2};
  16992. unsigned int queued_count{0};
  16993. std::atomic_uint count{0};
  16994. std::unique_ptr<TaskQueue> task_queue{
  16995. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16996. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16997. if (task_queue->enqueue(
  16998. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16999. queued_count++;
  17000. }
  17001. }
  17002. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17003. task_queue->shutdown();
  17004. #else
  17005. EXPECT_NO_THROW(task_queue->shutdown());
  17006. #endif
  17007. EXPECT_EQ(queued_count, count.load());
  17008. EXPECT_TRUE(queued_count <= number_of_tasks);
  17009. EXPECT_TRUE(queued_count >= qlimit);
  17010. }
  17011. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17012. // Use a short idle timeout so a dynamic thread spawns, times out and
  17013. // exits during the test, and the pool keeps working afterwards.
  17014. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17015. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17016. /*idle_timeout_sec=*/1}};
  17017. std::atomic_uint count{0};
  17018. std::condition_variable cv;
  17019. std::mutex mtx;
  17020. bool release = false;
  17021. // Block the base thread so the second task spawns a dynamic thread.
  17022. EXPECT_TRUE(task_queue->enqueue([&] {
  17023. std::unique_lock<std::mutex> lock(mtx);
  17024. while (!release) {
  17025. cv.wait(lock);
  17026. }
  17027. count++;
  17028. }));
  17029. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17030. // Let the dynamic thread finish its task and exceed the idle timeout.
  17031. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17032. {
  17033. std::unique_lock<std::mutex> lock(mtx);
  17034. release = true;
  17035. }
  17036. cv.notify_all();
  17037. // The pool must still accept and run tasks after the dynamic thread exited.
  17038. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17039. task_queue->shutdown();
  17040. EXPECT_EQ(3u, count.load());
  17041. }
  17042. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17043. static constexpr size_t number_of_tasks{32};
  17044. std::unique_ptr<TaskQueue> task_queue{
  17045. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17046. // Let the base threads go idle so the burst below finds them waiting.
  17047. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17048. std::mutex mtx;
  17049. std::condition_variable cv;
  17050. size_t running = 0;
  17051. bool release = false;
  17052. for (size_t i = 0; i < number_of_tasks; i++) {
  17053. EXPECT_TRUE(task_queue->enqueue([&] {
  17054. std::unique_lock<std::mutex> lock(mtx);
  17055. running++;
  17056. cv.notify_all();
  17057. cv.wait(lock, [&] { return release; });
  17058. }));
  17059. }
  17060. {
  17061. std::unique_lock<std::mutex> lock(mtx);
  17062. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17063. [&] { return running == number_of_tasks; }));
  17064. release = true;
  17065. }
  17066. cv.notify_all();
  17067. task_queue->shutdown();
  17068. }
  17069. TEST(TaskQueueTest, MaxQueuedRequests) {
  17070. static constexpr unsigned int qlimit{3};
  17071. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17072. std::condition_variable sem_cv;
  17073. std::mutex sem_mtx;
  17074. int credits = 0;
  17075. bool queued;
  17076. /* Fill up the queue with tasks that will block until we give them credits to
  17077. * complete. */
  17078. for (unsigned int n = 0; n <= qlimit;) {
  17079. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17080. std::unique_lock<std::mutex> lock(sem_mtx);
  17081. while (credits <= 0) {
  17082. sem_cv.wait(lock);
  17083. }
  17084. /* Consume the credit and signal the test code if they are all gone. */
  17085. if (--credits == 0) { sem_cv.notify_one(); }
  17086. });
  17087. if (n < qlimit) {
  17088. /* The first qlimit enqueues must succeed. */
  17089. EXPECT_TRUE(queued);
  17090. } else {
  17091. /* The last one will succeed only when the worker thread
  17092. * starts and dequeues the first blocking task. Although
  17093. * not necessary for the correctness of this test, we sleep for
  17094. * a short while to avoid busy waiting. */
  17095. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17096. }
  17097. if (queued) { n++; }
  17098. }
  17099. /* Further enqueues must fail since the queue is full. */
  17100. for (auto i = 0; i < 4; i++) {
  17101. queued = task_queue->enqueue([] {});
  17102. EXPECT_FALSE(queued);
  17103. }
  17104. /* Give the credits to allow the previous tasks to complete. */
  17105. {
  17106. std::unique_lock<std::mutex> lock(sem_mtx);
  17107. credits += qlimit + 1;
  17108. }
  17109. sem_cv.notify_all();
  17110. /* Wait for all the credits to be consumed. */
  17111. {
  17112. std::unique_lock<std::mutex> lock(sem_mtx);
  17113. while (credits > 0) {
  17114. sem_cv.wait(lock);
  17115. }
  17116. }
  17117. /* Check that we are able again to enqueue at least qlimit tasks. */
  17118. for (unsigned int i = 0; i < qlimit; i++) {
  17119. queued = task_queue->enqueue([] {});
  17120. EXPECT_TRUE(queued);
  17121. }
  17122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17123. task_queue->shutdown();
  17124. #else
  17125. EXPECT_NO_THROW(task_queue->shutdown());
  17126. #endif
  17127. }
  17128. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17129. Server svr;
  17130. std::string method;
  17131. std::string body;
  17132. auto has_content_length = false;
  17133. auto has_transfer_encoding = false;
  17134. std::atomic<int> bad_requests{0};
  17135. // Leftover body bytes get parsed as a malformed request and answered with
  17136. // 400
  17137. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17138. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17139. });
  17140. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17141. res.set_redirect("/down", StatusCode::SeeOther_303);
  17142. });
  17143. svr.Get("/down", [&](const Request &req, Response &res) {
  17144. method = req.method;
  17145. body = req.body;
  17146. has_content_length = req.has_header("Content-Length");
  17147. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17148. res.set_content("ok", "text/plain");
  17149. });
  17150. auto port = svr.bind_to_any_port(HOST);
  17151. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17152. auto se = detail::scope_exit([&] {
  17153. svr.stop();
  17154. thread.join();
  17155. ASSERT_FALSE(svr.is_running());
  17156. });
  17157. svr.wait_until_ready();
  17158. const std::string payload = "SECRET-BODY";
  17159. auto check = [&](Client &cli, const Result &res) {
  17160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17161. EXPECT_EQ(StatusCode::OK_200, res->status);
  17162. EXPECT_EQ("ok", res->body);
  17163. EXPECT_EQ("GET", method);
  17164. EXPECT_TRUE(body.empty());
  17165. EXPECT_FALSE(has_content_length);
  17166. EXPECT_FALSE(has_transfer_encoding);
  17167. // Nothing of the original body may be left on the connection
  17168. auto res2 = cli.Get("/down");
  17169. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17170. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17171. EXPECT_EQ("ok", res2->body);
  17172. EXPECT_EQ(0, bad_requests);
  17173. };
  17174. // With content length
  17175. {
  17176. Client cli(HOST, port);
  17177. cli.set_keep_alive(true);
  17178. cli.set_follow_location(true);
  17179. auto res = cli.Post(
  17180. "/up", payload.size(),
  17181. [&](size_t offset, size_t length, DataSink &sink) {
  17182. return sink.write(payload.data() + offset, length);
  17183. },
  17184. "text/plain");
  17185. check(cli, res);
  17186. }
  17187. // Without content length (chunked)
  17188. {
  17189. Client cli(HOST, port);
  17190. cli.set_keep_alive(true);
  17191. cli.set_follow_location(true);
  17192. auto res = cli.Post(
  17193. "/up",
  17194. [&](size_t /*offset*/, DataSink &sink) {
  17195. sink.write(payload.data(), payload.size());
  17196. sink.done();
  17197. return true;
  17198. },
  17199. "text/plain");
  17200. check(cli, res);
  17201. }
  17202. }
  17203. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17204. Server svr;
  17205. std::string target;
  17206. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17207. // Echo the still-encoded name back in the Location
  17208. const std::string prefix = "/start/";
  17209. res.status = StatusCode::Found_302;
  17210. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17211. });
  17212. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17213. target = req.target;
  17214. res.set_content("ok", "text/plain");
  17215. });
  17216. auto port = svr.bind_to_any_port(HOST);
  17217. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17218. auto se = detail::scope_exit([&] {
  17219. svr.stop();
  17220. thread.join();
  17221. ASSERT_FALSE(svr.is_running());
  17222. });
  17223. svr.wait_until_ready();
  17224. // Decoding the Location path would turn the first four into a path
  17225. // separator, a query delimiter, a fragment delimiter and a different
  17226. // percent-encoded octet. The rest must keep reaching the server as they are.
  17227. const std::vector<std::string> names = {
  17228. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17229. };
  17230. for (auto path_encode : {true, false}) {
  17231. Client cli(HOST, port);
  17232. cli.set_follow_location(true);
  17233. cli.set_path_encode(path_encode);
  17234. for (const auto &name : names) {
  17235. target.clear();
  17236. auto res = cli.Get("/start/" + name);
  17237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17238. EXPECT_EQ(StatusCode::OK_200, res->status);
  17239. EXPECT_EQ("/dest/" + name, target);
  17240. }
  17241. }
  17242. }
  17243. TEST(RedirectTest, NotModifiedIsReturned) {
  17244. Server svr;
  17245. svr.Get("/cached", [](const Request &, Response &res) {
  17246. res.status = StatusCode::NotModified_304;
  17247. });
  17248. auto port = svr.bind_to_any_port(HOST);
  17249. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17250. auto se = detail::scope_exit([&] {
  17251. svr.stop();
  17252. thread.join();
  17253. ASSERT_FALSE(svr.is_running());
  17254. });
  17255. svr.wait_until_ready();
  17256. Client cli(HOST, port);
  17257. cli.set_follow_location(true);
  17258. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17260. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17261. }
  17262. TEST(RedirectTest, NoLocationIsReturned) {
  17263. Server svr;
  17264. svr.Get("/no-location", [](const Request &, Response &res) {
  17265. res.status = StatusCode::Found_302;
  17266. res.set_content("no location", "text/plain");
  17267. });
  17268. auto port = svr.bind_to_any_port(HOST);
  17269. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17270. auto se = detail::scope_exit([&] {
  17271. svr.stop();
  17272. thread.join();
  17273. ASSERT_FALSE(svr.is_running());
  17274. });
  17275. svr.wait_until_ready();
  17276. Client cli(HOST, port);
  17277. cli.set_follow_location(true);
  17278. auto res = cli.Get("/no-location");
  17279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17280. EXPECT_EQ(StatusCode::Found_302, res->status);
  17281. EXPECT_EQ("no location", res->body);
  17282. // The callbacks see the body of the response that is returned
  17283. auto handler_called = false;
  17284. auto progress_called = false;
  17285. std::string body;
  17286. auto res2 = cli.Get(
  17287. "/no-location",
  17288. [&](const Response &) {
  17289. handler_called = true;
  17290. return true;
  17291. },
  17292. [&](const char *data, size_t data_length) {
  17293. body.append(data, data_length);
  17294. return true;
  17295. },
  17296. [&](size_t, size_t) {
  17297. progress_called = true;
  17298. return true;
  17299. });
  17300. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17301. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17302. EXPECT_TRUE(handler_called);
  17303. EXPECT_TRUE(progress_called);
  17304. EXPECT_EQ("no location", body);
  17305. }
  17306. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17307. Server svr;
  17308. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17309. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17310. });
  17311. svr.Get("/hello", [](const Request &req, Response &res) {
  17312. res.set_content(req.get_param_value("key"), "text/plain");
  17313. });
  17314. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17315. auto se = detail::scope_exit([&] {
  17316. svr.stop();
  17317. thread.join();
  17318. ASSERT_FALSE(svr.is_running());
  17319. });
  17320. svr.wait_until_ready();
  17321. {
  17322. Client cli(HOST, PORT);
  17323. cli.set_follow_location(true);
  17324. auto res = cli.Get("/");
  17325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17326. EXPECT_EQ(StatusCode::OK_200, res->status);
  17327. EXPECT_EQ("val&key2=val2", res->body);
  17328. }
  17329. }
  17330. #endif
  17331. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17332. Server svr;
  17333. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17334. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17335. });
  17336. svr.Get("/hello", [](const Request &req, Response &res) {
  17337. res.set_content(req.get_param_value("key"), "text/plain");
  17338. });
  17339. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17340. auto se = detail::scope_exit([&] {
  17341. svr.stop();
  17342. thread.join();
  17343. ASSERT_FALSE(svr.is_running());
  17344. });
  17345. svr.wait_until_ready();
  17346. {
  17347. Client cli(HOST, PORT);
  17348. cli.set_follow_location(true);
  17349. auto res = cli.Get("/");
  17350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17351. EXPECT_EQ(StatusCode::OK_200, res->status);
  17352. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17353. }
  17354. }
  17355. TEST(RedirectTest, RedirectWithPlusInPath) {
  17356. Server svr;
  17357. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17358. res.set_redirect("/a+b");
  17359. });
  17360. // Route pattern uses regex; escape + as \\+
  17361. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17362. res.set_content(req.path, "text/plain");
  17363. });
  17364. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17365. auto se = detail::scope_exit([&] {
  17366. svr.stop();
  17367. thread.join();
  17368. ASSERT_FALSE(svr.is_running());
  17369. });
  17370. svr.wait_until_ready();
  17371. {
  17372. Client cli(HOST, PORT);
  17373. cli.set_follow_location(true);
  17374. auto res = cli.Get("/");
  17375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17376. EXPECT_EQ(StatusCode::OK_200, res->status);
  17377. EXPECT_EQ("/a+b", res->body);
  17378. }
  17379. }
  17380. TEST(RedirectTest, ResolveRelativeLocation) {
  17381. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17382. const std::vector<std::pair<std::string, std::string>> cases = {
  17383. {"g", "/b/c/g"},
  17384. {"./g", "/b/c/g"},
  17385. {"g/", "/b/c/g/"},
  17386. {"?y", "/b/c/d;p?y"},
  17387. {"g?y", "/b/c/g?y"},
  17388. {"#s", "/b/c/d;p?q#s"},
  17389. {"g#s", "/b/c/g#s"},
  17390. {"g?y#s", "/b/c/g?y#s"},
  17391. {";x", "/b/c/;x"},
  17392. {"g;x", "/b/c/g;x"},
  17393. {".", "/b/c/"},
  17394. {"./", "/b/c/"},
  17395. {"..", "/b/"},
  17396. {"../", "/b/"},
  17397. {"../g", "/b/g"},
  17398. {"../..", "/"},
  17399. {"../../", "/"},
  17400. {"../../g", "/g"},
  17401. {"../../../g", "/g"},
  17402. {"g.", "/b/c/g."},
  17403. {".g", "/b/c/.g"},
  17404. {"g..", "/b/c/g.."},
  17405. {"..g", "/b/c/..g"},
  17406. {"./../g", "/b/g"},
  17407. {"./g/.", "/b/c/g/"},
  17408. {"g/./h", "/b/c/g/h"},
  17409. {"g/../h", "/b/c/h"},
  17410. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17411. {"g;x=1/../y", "/b/c/y"},
  17412. {"g?y/./x", "/b/c/g?y/./x"},
  17413. {"g#s/../x", "/b/c/g#s/../x"},
  17414. // Not relative-path references, so left for parse_url.
  17415. {"/g", "/g"},
  17416. {"//g", "//g"},
  17417. {"http://g/x", "http://g/x"},
  17418. {"g:h", "g:h"},
  17419. };
  17420. for (const auto &c : cases) {
  17421. EXPECT_EQ(c.second,
  17422. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17423. << c.first;
  17424. }
  17425. }
  17426. TEST(RedirectTest, RemoveDotSegments) {
  17427. // RFC 3986 section 5.2.4
  17428. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17429. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17430. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17431. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17432. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17433. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17434. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17435. }
  17436. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17437. Server svr;
  17438. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17439. res.set_redirect("/dir/../target?x=1");
  17440. });
  17441. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17442. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17443. "/dir/./../target");
  17444. });
  17445. svr.Get("/target", [](const Request &req, Response &res) {
  17446. res.set_content(req.path, "text/plain");
  17447. });
  17448. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17449. auto se = detail::scope_exit([&] {
  17450. svr.stop();
  17451. th.join();
  17452. ASSERT_FALSE(svr.is_running());
  17453. });
  17454. svr.wait_until_ready();
  17455. Client cli("localhost", PORT);
  17456. cli.set_follow_location(true);
  17457. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17458. auto res = cli.Get(path);
  17459. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17460. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17461. EXPECT_EQ("/target", res->body) << path;
  17462. }
  17463. }
  17464. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17465. Server svr;
  17466. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17467. res.set_redirect(req.get_param_value("to"));
  17468. });
  17469. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17470. res.set_content(req.target, "text/plain");
  17471. });
  17472. svr.Get("/other", [](const Request &req, Response &res) {
  17473. res.set_content(req.target, "text/plain");
  17474. });
  17475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17476. auto se = detail::scope_exit([&] {
  17477. svr.stop();
  17478. thread.join();
  17479. ASSERT_FALSE(svr.is_running());
  17480. });
  17481. svr.wait_until_ready();
  17482. const std::vector<std::pair<std::string, std::string>> cases = {
  17483. {"next", "/dir/next"},
  17484. {"./next?x=1", "/dir/next?x=1"},
  17485. {"../other", "/other"},
  17486. };
  17487. for (const auto &c : cases) {
  17488. Client cli(HOST, PORT);
  17489. cli.set_follow_location(true);
  17490. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17491. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17492. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17493. EXPECT_EQ(c.second, res->body) << c.first;
  17494. }
  17495. }
  17496. #ifdef CPPHTTPLIB_SSL_ENABLED
  17497. TEST(RedirectTest, Issue2185_Online) {
  17498. SSLClient client("github.com");
  17499. client.set_follow_location(true);
  17500. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17501. "Coollab-Windows.zip");
  17502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17503. EXPECT_EQ(StatusCode::OK_200, res->status);
  17504. EXPECT_EQ(9920427U, res->body.size());
  17505. }
  17506. #endif
  17507. TEST(VulnerabilityTest, CRLFInjection) {
  17508. Server svr;
  17509. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17510. res.set_content("Hello 1", "text/plain");
  17511. });
  17512. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17513. res.set_content("Hello 2", "text/plain");
  17514. });
  17515. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17516. res.set_content("Hello 3", "text/plain");
  17517. });
  17518. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17519. res.set_content("Hello 4", "text/plain");
  17520. });
  17521. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17522. for (const auto &x : req.headers) {
  17523. auto key = x.first;
  17524. EXPECT_STRNE("evil", key.c_str());
  17525. }
  17526. });
  17527. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17528. auto se = detail::scope_exit([&] {
  17529. svr.stop();
  17530. thread.join();
  17531. ASSERT_FALSE(svr.is_running());
  17532. });
  17533. svr.wait_until_ready();
  17534. {
  17535. Client cli(HOST, PORT);
  17536. cli.Post("/test1", "A=B",
  17537. "application/x-www-form-urlencoded\r\nevil: hello1");
  17538. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17539. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17540. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17541. }
  17542. }
  17543. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17544. auto server_thread = std::thread([] {
  17545. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17546. default_socket_options(srv);
  17547. sockaddr_in addr{};
  17548. addr.sin_family = AF_INET;
  17549. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17550. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17551. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17552. ::listen(srv, 1);
  17553. sockaddr_in cli_addr{};
  17554. socklen_t cli_len = sizeof(cli_addr);
  17555. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17556. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17557. std::string buf_all;
  17558. char buf[2048];
  17559. ssize_t n;
  17560. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17561. buf_all.append(buf, static_cast<size_t>(n));
  17562. size_t pos;
  17563. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17564. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17565. auto e = request_block.find("\r\n");
  17566. if (e != std::string::npos) {
  17567. auto request_line = request_block.substr(0, e);
  17568. std::string msg =
  17569. "CRLF injection detected in request line: '" + request_line + "'";
  17570. EXPECT_FALSE(true) << msg;
  17571. }
  17572. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17573. ::send(cli,
  17574. #ifdef _WIN32
  17575. static_cast<const char *>(resp.c_str()),
  17576. static_cast<int>(resp.size()),
  17577. #else
  17578. resp.c_str(), resp.size(),
  17579. #endif
  17580. 0);
  17581. buf_all.erase(0, pos + 4);
  17582. }
  17583. }
  17584. detail::close_socket(cli);
  17585. detail::close_socket(srv);
  17586. });
  17587. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17588. auto cli = Client("127.0.0.1", PORT + 1);
  17589. auto headers = Headers{
  17590. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17591. {"Connection", "keep-alive"}};
  17592. auto res = cli.Get("/hi", headers);
  17593. EXPECT_FALSE(res);
  17594. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17595. server_thread.join();
  17596. }
  17597. // A request rejected before any byte reaches the socket must fail right away
  17598. // instead of waiting for a response the server will never send.
  17599. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17600. // The kernel completes the TCP handshake from the listen backlog, so the
  17601. // client connects, but nothing ever reads, responds or closes.
  17602. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17603. default_socket_options(srv);
  17604. sockaddr_in addr{};
  17605. addr.sin_family = AF_INET;
  17606. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17607. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17608. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17609. ASSERT_EQ(0, ::listen(srv, 8));
  17610. auto cli = Client("127.0.0.1", PORT + 1);
  17611. cli.set_read_timeout(10, 0);
  17612. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17613. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17614. std::chrono::steady_clock::now() - start)
  17615. .count();
  17616. };
  17617. {
  17618. Request req;
  17619. req.method = "GE T";
  17620. req.path = "/";
  17621. auto start = std::chrono::steady_clock::now();
  17622. auto res = cli.send(req);
  17623. EXPECT_FALSE(res);
  17624. EXPECT_EQ(Error::Write, res.error());
  17625. EXPECT_LT(elapsed_ms(start), 1000);
  17626. }
  17627. {
  17628. auto start = std::chrono::steady_clock::now();
  17629. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17630. EXPECT_FALSE(res);
  17631. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17632. EXPECT_LT(elapsed_ms(start), 1000);
  17633. }
  17634. EXPECT_FALSE(cli.is_socket_open());
  17635. detail::close_socket(srv);
  17636. }
  17637. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17638. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17639. default_socket_options(srv);
  17640. sockaddr_in addr{};
  17641. addr.sin_family = AF_INET;
  17642. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17643. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17644. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17645. ASSERT_EQ(0, ::listen(srv, 1));
  17646. std::string received;
  17647. auto server_thread = std::thread([&] {
  17648. auto sock = ::accept(srv, nullptr, nullptr);
  17649. if (sock == INVALID_SOCKET) { return; }
  17650. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17651. char buf[2048];
  17652. ssize_t n;
  17653. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17654. received.append(buf, static_cast<size_t>(n));
  17655. }
  17656. detail::close_socket(sock);
  17657. });
  17658. {
  17659. auto cli = Client("127.0.0.1", PORT + 1);
  17660. // "Z" sorts after the default headers, so writing straight to the socket
  17661. // would have sent the request line and those headers before the rejection.
  17662. auto handle =
  17663. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17664. EXPECT_FALSE(handle.is_valid());
  17665. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17666. }
  17667. server_thread.join();
  17668. detail::close_socket(srv);
  17669. EXPECT_TRUE(received.empty()) << received;
  17670. }
  17671. TEST(PathParamsTest, StaticMatch) {
  17672. const auto pattern = "/users/all";
  17673. detail::PathParamsMatcher matcher(pattern);
  17674. Request request;
  17675. request.path = "/users/all";
  17676. ASSERT_TRUE(matcher.match(request));
  17677. std::unordered_map<std::string, std::string> expected_params = {};
  17678. EXPECT_EQ(request.path_params, expected_params);
  17679. }
  17680. TEST(PathParamsTest, StaticMismatch) {
  17681. const auto pattern = "/users/all";
  17682. detail::PathParamsMatcher matcher(pattern);
  17683. Request request;
  17684. request.path = "/users/1";
  17685. ASSERT_FALSE(matcher.match(request));
  17686. }
  17687. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17688. const auto pattern = "/users/:id/subscriptions";
  17689. detail::PathParamsMatcher matcher(pattern);
  17690. Request request;
  17691. request.path = "/users/42/subscriptions";
  17692. ASSERT_TRUE(matcher.match(request));
  17693. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17694. EXPECT_EQ(request.path_params, expected_params);
  17695. }
  17696. TEST(PathParamsTest, SingleParamInTheEnd) {
  17697. const auto pattern = "/users/:id";
  17698. detail::PathParamsMatcher matcher(pattern);
  17699. Request request;
  17700. request.path = "/users/24";
  17701. ASSERT_TRUE(matcher.match(request));
  17702. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17703. EXPECT_EQ(request.path_params, expected_params);
  17704. }
  17705. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17706. const auto pattern = "/users/:id/";
  17707. detail::PathParamsMatcher matcher(pattern);
  17708. Request request;
  17709. request.path = "/users/42/";
  17710. ASSERT_TRUE(matcher.match(request));
  17711. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17712. EXPECT_EQ(request.path_params, expected_params);
  17713. }
  17714. TEST(PathParamsTest, EmptyParam) {
  17715. const auto pattern = "/users/:id/";
  17716. detail::PathParamsMatcher matcher(pattern);
  17717. Request request;
  17718. request.path = "/users//";
  17719. ASSERT_TRUE(matcher.match(request));
  17720. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17721. EXPECT_EQ(request.path_params, expected_params);
  17722. }
  17723. TEST(PathParamsTest, FragmentMismatch) {
  17724. const auto pattern = "/users/:id/";
  17725. detail::PathParamsMatcher matcher(pattern);
  17726. Request request;
  17727. request.path = "/admins/24/";
  17728. ASSERT_FALSE(matcher.match(request));
  17729. }
  17730. TEST(PathParamsTest, ExtraFragments) {
  17731. const auto pattern = "/users/:id";
  17732. detail::PathParamsMatcher matcher(pattern);
  17733. Request request;
  17734. request.path = "/users/42/subscriptions";
  17735. ASSERT_FALSE(matcher.match(request));
  17736. }
  17737. TEST(PathParamsTest, MissingTrailingParam) {
  17738. const auto pattern = "/users/:id";
  17739. detail::PathParamsMatcher matcher(pattern);
  17740. Request request;
  17741. request.path = "/users";
  17742. ASSERT_FALSE(matcher.match(request));
  17743. }
  17744. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17745. const auto pattern = "/users/:id/subscriptions";
  17746. detail::PathParamsMatcher matcher(pattern);
  17747. Request request;
  17748. request.path = "/users/subscriptions";
  17749. ASSERT_FALSE(matcher.match(request));
  17750. }
  17751. TEST(PathParamsTest, MultipleParams) {
  17752. const auto pattern = "/users/:userid/subscriptions/:subid";
  17753. detail::PathParamsMatcher matcher(pattern);
  17754. Request request;
  17755. request.path = "/users/42/subscriptions/2";
  17756. ASSERT_TRUE(matcher.match(request));
  17757. std::unordered_map<std::string, std::string> expected_params = {
  17758. {"userid", "42"}, {"subid", "2"}};
  17759. EXPECT_EQ(request.path_params, expected_params);
  17760. }
  17761. TEST(PathParamsTest, SequenceOfParams) {
  17762. const auto pattern = "/values/:x/:y/:z";
  17763. detail::PathParamsMatcher matcher(pattern);
  17764. Request request;
  17765. request.path = "/values/1/2/3";
  17766. ASSERT_TRUE(matcher.match(request));
  17767. std::unordered_map<std::string, std::string> expected_params = {
  17768. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17769. EXPECT_EQ(request.path_params, expected_params);
  17770. }
  17771. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17772. const auto pattern = "/prefix:suffix";
  17773. detail::PathParamsMatcher matcher(pattern);
  17774. Request request;
  17775. request.path = "/prefix:suffix";
  17776. ASSERT_TRUE(matcher.match(request));
  17777. const std::unordered_map<std::string, std::string> expected_params = {};
  17778. EXPECT_EQ(request.path_params, expected_params);
  17779. }
  17780. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17781. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17782. // calling thread's stack on a long enough path for a quantified pattern;
  17783. // RegexMatcher must refuse to run regex matching on paths beyond
  17784. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17785. detail::RegexMatcher matcher("/files/(.*)");
  17786. Request within_limit;
  17787. within_limit.path = "/files/" + std::string(10, 'A');
  17788. EXPECT_TRUE(matcher.match(within_limit));
  17789. Request over_limit;
  17790. over_limit.path =
  17791. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17792. EXPECT_FALSE(matcher.match(over_limit));
  17793. }
  17794. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17795. Server svr;
  17796. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17797. res.set_content("ok", "text/plain");
  17798. });
  17799. auto port = svr.bind_to_any_port(HOST);
  17800. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17801. auto se = detail::scope_exit([&] {
  17802. svr.stop();
  17803. thread.join();
  17804. ASSERT_FALSE(svr.is_running());
  17805. });
  17806. svr.wait_until_ready();
  17807. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17808. // request URI limit; this used to be able to crash the process.
  17809. std::string path =
  17810. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17811. std::string req = "GET " + path +
  17812. " HTTP/1.1\r\n"
  17813. "Host: " +
  17814. std::string(HOST) + ":" + std::to_string(port) +
  17815. "\r\n"
  17816. "Connection: close\r\n"
  17817. "\r\n";
  17818. std::string response;
  17819. ASSERT_TRUE(send_request(5, req, &response, port));
  17820. EXPECT_NE(std::string::npos, response.find("404"));
  17821. }
  17822. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17823. Server svr;
  17824. auto handler = [](const Request & /*req*/, Response &res) {
  17825. res.set_content("hit", "text/plain");
  17826. };
  17827. // No regex metacharacter, so this one is compared literally
  17828. svr.Get("/literal/route", handler);
  17829. // '.' is a regex metacharacter, so this one must keep regex semantics
  17830. svr.Get("/a.c", handler);
  17831. auto port = svr.bind_to_any_port(HOST);
  17832. std::thread t([&]() { svr.listen_after_bind(); });
  17833. auto se = detail::scope_exit([&] {
  17834. svr.stop();
  17835. t.join();
  17836. ASSERT_FALSE(svr.is_running());
  17837. });
  17838. svr.wait_until_ready();
  17839. Client cli(HOST, port);
  17840. struct {
  17841. const char *path;
  17842. int status;
  17843. } cases[] = {
  17844. {"/literal/route", StatusCode::OK_200},
  17845. {"/literal/routes", StatusCode::NotFound_404},
  17846. {"/literal/rout", StatusCode::NotFound_404},
  17847. {"/abc", StatusCode::OK_200},
  17848. {"/a.c", StatusCode::OK_200},
  17849. };
  17850. for (const auto &x : cases) {
  17851. auto res = cli.Get(x.path);
  17852. ASSERT_TRUE(res) << x.path;
  17853. EXPECT_EQ(x.status, res->status) << x.path;
  17854. }
  17855. }
  17856. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17857. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17858. // from exhausting the stack, so it must only constrain routes that actually
  17859. // run a regular expression. A literal route is matched by comparison and
  17860. // stays usable at any length.
  17861. Server svr;
  17862. const std::string pattern =
  17863. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17864. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17865. res.set_content("hit", "text/plain");
  17866. });
  17867. auto port = svr.bind_to_any_port(HOST);
  17868. std::thread t([&]() { svr.listen_after_bind(); });
  17869. auto se = detail::scope_exit([&] {
  17870. svr.stop();
  17871. t.join();
  17872. ASSERT_FALSE(svr.is_running());
  17873. });
  17874. svr.wait_until_ready();
  17875. Client cli(HOST, port);
  17876. auto res = cli.Get(pattern);
  17877. ASSERT_TRUE(res);
  17878. EXPECT_EQ(StatusCode::OK_200, res->status);
  17879. }
  17880. TEST(ParseUrlTest, VariousPatterns) {
  17881. {
  17882. detail::UrlComponents uc;
  17883. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17884. EXPECT_EQ("http", uc.scheme);
  17885. EXPECT_EQ("example.com", uc.host);
  17886. EXPECT_EQ("8080", uc.port);
  17887. EXPECT_EQ("/path", uc.path);
  17888. EXPECT_EQ("?q=1", uc.query);
  17889. }
  17890. {
  17891. detail::UrlComponents uc;
  17892. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17893. EXPECT_EQ("https", uc.scheme);
  17894. EXPECT_EQ("example.com", uc.host);
  17895. EXPECT_TRUE(uc.port.empty());
  17896. EXPECT_EQ("/path", uc.path);
  17897. }
  17898. {
  17899. detail::UrlComponents uc;
  17900. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17901. EXPECT_EQ("::1", uc.host);
  17902. EXPECT_EQ("8080", uc.port);
  17903. EXPECT_EQ("/path", uc.path);
  17904. }
  17905. {
  17906. detail::UrlComponents uc;
  17907. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17908. }
  17909. {
  17910. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17911. // the path while the connection still targets the bracketed host.
  17912. detail::UrlComponents uc;
  17913. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17914. }
  17915. {
  17916. detail::UrlComponents uc;
  17917. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17918. }
  17919. {
  17920. detail::UrlComponents uc;
  17921. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17922. EXPECT_EQ("::1", uc.host);
  17923. EXPECT_TRUE(uc.port.empty());
  17924. EXPECT_EQ("/path", uc.path);
  17925. }
  17926. {
  17927. detail::UrlComponents uc;
  17928. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17929. EXPECT_TRUE(uc.scheme.empty());
  17930. EXPECT_EQ("example.com", uc.host);
  17931. EXPECT_EQ("/path", uc.path);
  17932. EXPECT_EQ("?q=1", uc.query);
  17933. }
  17934. {
  17935. detail::UrlComponents uc;
  17936. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17937. EXPECT_TRUE(uc.host.empty());
  17938. EXPECT_EQ("/path", uc.path);
  17939. EXPECT_EQ("?q=1", uc.query);
  17940. }
  17941. {
  17942. detail::UrlComponents uc;
  17943. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17944. EXPECT_EQ("example.com", uc.host);
  17945. EXPECT_EQ("8080", uc.port);
  17946. }
  17947. {
  17948. // Unix socket path — must not be parsed as host
  17949. detail::UrlComponents uc;
  17950. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17951. EXPECT_TRUE(uc.host.empty());
  17952. }
  17953. {
  17954. detail::UrlComponents uc;
  17955. ASSERT_TRUE(detail::parse_url("", uc));
  17956. EXPECT_TRUE(uc.host.empty());
  17957. EXPECT_TRUE(uc.path.empty());
  17958. }
  17959. {
  17960. detail::UrlComponents uc;
  17961. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17962. }
  17963. {
  17964. detail::UrlComponents uc;
  17965. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17966. }
  17967. {
  17968. // Accepted by parse_url; callers restrict to http/https
  17969. detail::UrlComponents uc;
  17970. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17971. EXPECT_EQ("ftp", uc.scheme);
  17972. }
  17973. {
  17974. detail::UrlComponents uc;
  17975. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17976. }
  17977. {
  17978. detail::UrlComponents uc;
  17979. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17980. }
  17981. }
  17982. TEST(ParseUrlTest, FragmentHandling) {
  17983. {
  17984. detail::UrlComponents uc;
  17985. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17986. EXPECT_EQ("/path", uc.path);
  17987. EXPECT_TRUE(uc.query.empty());
  17988. }
  17989. {
  17990. detail::UrlComponents uc;
  17991. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17992. EXPECT_TRUE(uc.path.empty());
  17993. EXPECT_TRUE(uc.query.empty());
  17994. }
  17995. }
  17996. TEST(ParseUrlTest, UserinfoHandling) {
  17997. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17998. // parsers would see evil.com as the host.
  17999. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18000. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18001. for (auto url : urls) {
  18002. detail::UrlComponents uc;
  18003. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18004. }
  18005. }
  18006. TEST(ParseUrlTest, IPv6EdgeCases) {
  18007. {
  18008. detail::UrlComponents uc;
  18009. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18010. EXPECT_TRUE(uc.scheme.empty());
  18011. EXPECT_EQ("::1", uc.host);
  18012. EXPECT_EQ("8080", uc.port);
  18013. }
  18014. {
  18015. // Zone ID '%25' is not in [a-fA-F0-9:]
  18016. detail::UrlComponents uc;
  18017. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18018. }
  18019. }
  18020. TEST(ParseUrlTest, SchemeEdgeCases) {
  18021. {
  18022. detail::UrlComponents uc;
  18023. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18024. }
  18025. {
  18026. detail::UrlComponents uc;
  18027. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18028. }
  18029. {
  18030. detail::UrlComponents uc;
  18031. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18032. }
  18033. }
  18034. TEST(ParseUrlTest, PortEdgeCases) {
  18035. {
  18036. detail::UrlComponents uc;
  18037. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18038. EXPECT_TRUE(uc.port.empty());
  18039. EXPECT_EQ("/path", uc.path);
  18040. }
  18041. {
  18042. // parse_url accepts any port string; validation is done by parse_port
  18043. detail::UrlComponents uc;
  18044. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18045. EXPECT_EQ("abc", uc.port);
  18046. }
  18047. }
  18048. TEST(ParseUrlTest, WebSocketPatterns) {
  18049. {
  18050. detail::UrlComponents uc;
  18051. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18052. EXPECT_EQ("ws", uc.scheme);
  18053. EXPECT_EQ("echo.example.com", uc.host);
  18054. EXPECT_EQ("8080", uc.port);
  18055. EXPECT_EQ("/ws", uc.path);
  18056. }
  18057. {
  18058. detail::UrlComponents uc;
  18059. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18060. EXPECT_EQ("wss", uc.scheme);
  18061. EXPECT_EQ("echo.example.com", uc.host);
  18062. EXPECT_TRUE(uc.port.empty());
  18063. EXPECT_EQ("/ws", uc.path);
  18064. }
  18065. }
  18066. TEST(ParseUrlTest, QueryOnly) {
  18067. detail::UrlComponents uc;
  18068. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18069. EXPECT_TRUE(uc.host.empty());
  18070. EXPECT_TRUE(uc.path.empty());
  18071. EXPECT_EQ("?q=1&r=2", uc.query);
  18072. }
  18073. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18074. detail::UrlComponents uc;
  18075. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18076. EXPECT_TRUE(uc.scheme.empty());
  18077. EXPECT_EQ("example.com", uc.host);
  18078. EXPECT_EQ("443", uc.port);
  18079. EXPECT_EQ("/path", uc.path);
  18080. }
  18081. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18082. // If ipv6 regex working, regex match codepath is taken.
  18083. // else port will default to 80 in Client impl
  18084. int clientImplMagicPort = 80;
  18085. int port = 4321;
  18086. // above ports must be different to avoid false negative
  18087. EXPECT_NE(clientImplMagicPort, port);
  18088. std::string ipV6TestURL = "http://[ff06::c3]";
  18089. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18090. CLIENT_PRIVATE_KEY_FILE);
  18091. EXPECT_EQ(cli.port(), port);
  18092. }
  18093. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18094. auto file_path = "./www/dir/index.html";
  18095. auto dir_path = "./www/dir";
  18096. detail::FileStat stat_file(file_path);
  18097. EXPECT_TRUE(stat_file.is_file());
  18098. EXPECT_FALSE(stat_file.is_dir());
  18099. detail::FileStat stat_dir(dir_path);
  18100. EXPECT_FALSE(stat_dir.is_file());
  18101. EXPECT_TRUE(stat_dir.is_dir());
  18102. }
  18103. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18104. // IPv4 with default HTTP port (80)
  18105. EXPECT_EQ("example.com",
  18106. detail::make_host_and_port_string("example.com", 80, false));
  18107. // IPv4 with default HTTPS port (443)
  18108. EXPECT_EQ("example.com",
  18109. detail::make_host_and_port_string("example.com", 443, true));
  18110. // IPv4 with non-default HTTP port
  18111. EXPECT_EQ("example.com:8080",
  18112. detail::make_host_and_port_string("example.com", 8080, false));
  18113. // IPv4 with non-default HTTPS port
  18114. EXPECT_EQ("example.com:8443",
  18115. detail::make_host_and_port_string("example.com", 8443, true));
  18116. // IPv6 with default HTTP port (80)
  18117. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18118. // IPv6 with default HTTPS port (443)
  18119. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18120. // IPv6 with non-default HTTP port
  18121. EXPECT_EQ("[::1]:8080",
  18122. detail::make_host_and_port_string("::1", 8080, false));
  18123. // IPv6 with non-default HTTPS port
  18124. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18125. // IPv6 full address with default port
  18126. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18127. detail::make_host_and_port_string(
  18128. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18129. // IPv6 full address with non-default port
  18130. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18131. detail::make_host_and_port_string(
  18132. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18133. // IPv6 localhost with non-default port
  18134. EXPECT_EQ("[::1]:3000",
  18135. detail::make_host_and_port_string("::1", 3000, false));
  18136. // IPv6 with zone ID (link-local address) with default port
  18137. EXPECT_EQ("[fe80::1%eth0]",
  18138. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18139. // IPv6 with zone ID (link-local address) with non-default port
  18140. EXPECT_EQ("[fe80::1%eth0]:8080",
  18141. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18142. // Edge case: Port 443 with is_ssl=false (should add port)
  18143. EXPECT_EQ("example.com:443",
  18144. detail::make_host_and_port_string("example.com", 443, false));
  18145. // Edge case: Port 80 with is_ssl=true (should add port)
  18146. EXPECT_EQ("example.com:80",
  18147. detail::make_host_and_port_string("example.com", 80, true));
  18148. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18149. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18150. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18151. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18152. // Security fix: Already bracketed IPv6 should not get double brackets
  18153. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18154. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18155. EXPECT_EQ("[::1]:8080",
  18156. detail::make_host_and_port_string("[::1]", 8080, false));
  18157. EXPECT_EQ("[2001:db8::1]:8080",
  18158. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18159. EXPECT_EQ("[fe80::1%eth0]",
  18160. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18161. EXPECT_EQ("[fe80::1%eth0]:8080",
  18162. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18163. // Edge case: Empty host (should return as-is)
  18164. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18165. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18166. // This is a known limitation but shouldn't crash
  18167. EXPECT_EQ("[host:name]",
  18168. detail::make_host_and_port_string("host:name", 80, false));
  18169. // Port number edge cases (no validation, but should not crash)
  18170. EXPECT_EQ("example.com:0",
  18171. detail::make_host_and_port_string("example.com", 0, false));
  18172. EXPECT_EQ("example.com:-1",
  18173. detail::make_host_and_port_string("example.com", -1, false));
  18174. EXPECT_EQ("example.com:65535",
  18175. detail::make_host_and_port_string("example.com", 65535, false));
  18176. EXPECT_EQ("example.com:65536",
  18177. detail::make_host_and_port_string("example.com", 65536, false));
  18178. }
  18179. namespace httplib {
  18180. namespace detail {
  18181. std::string
  18182. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18183. const std::string &host, int port);
  18184. } // namespace detail
  18185. } // namespace httplib
  18186. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18187. std::map<std::string, std::string> addr_map = {
  18188. {"ipv4.example", "192.0.2.10"},
  18189. {"ipv6.example", "2001:db8::1"},
  18190. {"name.example", "internal.example.lan"},
  18191. {"empty.example", ""}};
  18192. EXPECT_EQ("192.0.2.10:443",
  18193. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18194. EXPECT_EQ("[2001:db8::1]:443",
  18195. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18196. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18197. addr_map, "name.example", 8443));
  18198. // An empty or absent mapping keeps the hostname as the target
  18199. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18200. addr_map, "empty.example", 443));
  18201. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18202. addr_map, "other.example", 443));
  18203. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18204. }
  18205. #ifdef CPPHTTPLIB_SSL_ENABLED
  18206. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18207. httplib::SSLClient cli("roblox.com", 443);
  18208. cli.set_follow_location(true);
  18209. auto res = cli.Get("/");
  18210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18211. EXPECT_EQ(StatusCode::OK_200, res->status);
  18212. }
  18213. #endif
  18214. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18215. Server svr;
  18216. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18217. EXPECT_EQ(res.status, 400);
  18218. });
  18219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18220. auto se = detail::scope_exit([&] {
  18221. svr.stop();
  18222. thread.join();
  18223. ASSERT_FALSE(svr.is_running());
  18224. });
  18225. svr.wait_until_ready();
  18226. Client cli(HOST, PORT);
  18227. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18228. }
  18229. TEST(InvalidHeaderCharsTest, is_field_name) {
  18230. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18231. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18232. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18233. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18234. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18235. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18236. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18237. EXPECT_FALSE(detail::fields::is_field_name(""));
  18238. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18239. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18240. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18241. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18242. }
  18243. TEST(InvalidHeaderCharsTest, is_field_value) {
  18244. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18245. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18246. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18247. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18248. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18249. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18250. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18251. EXPECT_TRUE(detail::fields::is_field_value(""));
  18252. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18253. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18254. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18255. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18256. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18257. }
  18258. TEST(InvalidHeaderCharsTest, OnServer) {
  18259. Server svr;
  18260. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18261. std::string header = "Not Set";
  18262. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18263. res.set_header(header, "value");
  18264. res.set_content("Page Content Page Content", "text/plain");
  18265. });
  18266. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18267. std::string header = "Not Set";
  18268. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18269. res.set_header("X-Test", header);
  18270. res.set_content("Page Content Page Content", "text/plain");
  18271. });
  18272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18273. auto se = detail::scope_exit([&] {
  18274. svr.stop();
  18275. thread.join();
  18276. ASSERT_FALSE(svr.is_running());
  18277. });
  18278. svr.wait_until_ready();
  18279. Client cli(HOST, PORT);
  18280. {
  18281. auto res = cli.Get(
  18282. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18284. EXPECT_EQ("Page Content Page Content", res->body);
  18285. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18286. }
  18287. {
  18288. auto res = cli.Get(
  18289. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18291. EXPECT_EQ("Page Content Page Content", res->body);
  18292. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18293. }
  18294. }
  18295. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18296. auto handled = false;
  18297. Server svr;
  18298. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18299. thread t = thread([&] { svr.listen(HOST, PORT); });
  18300. auto se = detail::scope_exit([&] {
  18301. svr.stop();
  18302. t.join();
  18303. ASSERT_FALSE(svr.is_running());
  18304. ASSERT_FALSE(handled);
  18305. });
  18306. svr.wait_until_ready();
  18307. auto req = "POST /test HTTP/1.1\r\n"
  18308. "Content-Length: x\r\n"
  18309. "\r\n";
  18310. std::string response;
  18311. ASSERT_TRUE(send_request(1, req, &response));
  18312. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18313. response.substr(0, response.find("\r\n")));
  18314. }
  18315. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18316. // case-insensitive, and a server that receives a 100-continue expectation in
  18317. // an HTTP/1.0 request MUST ignore it.
  18318. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18319. std::string response;
  18320. ASSERT_TRUE(send_request(1, req, &response, port));
  18321. *got_100 = response.find("100 Continue") != std::string::npos;
  18322. }
  18323. class ExpectTokenTest : public ::testing::Test {
  18324. protected:
  18325. void SetUp() override {
  18326. svr_.Post("/p", [](const Request &, Response &res) {
  18327. res.set_content("ok", "text/plain");
  18328. });
  18329. port_ = svr_.bind_to_any_port(HOST);
  18330. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18331. svr_.wait_until_ready();
  18332. }
  18333. void TearDown() override {
  18334. svr_.stop();
  18335. if (thread_.joinable()) { thread_.join(); }
  18336. }
  18337. std::string request(const char *version, const char *expect_value) const {
  18338. return std::string("POST /p ") + version +
  18339. "\r\n"
  18340. "Host: localhost\r\n"
  18341. "Content-Length: 2\r\n"
  18342. "Connection: close\r\n"
  18343. "Expect: " +
  18344. expect_value +
  18345. "\r\n"
  18346. "\r\n"
  18347. "hi";
  18348. }
  18349. Server svr_;
  18350. int port_ = 0;
  18351. thread thread_;
  18352. };
  18353. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18354. bool got_100 = false;
  18355. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18356. EXPECT_TRUE(got_100);
  18357. }
  18358. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18359. bool got_100 = true;
  18360. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18361. EXPECT_FALSE(got_100);
  18362. }
  18363. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18364. bool got_100 = false;
  18365. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18366. EXPECT_TRUE(got_100);
  18367. }
  18368. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18369. bool got_100 = false;
  18370. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18371. EXPECT_TRUE(got_100);
  18372. }
  18373. // `100 Continue` is sent only when the server starts reading the body, so a
  18374. // request rejected before that never invites the client to send it. The
  18375. // requests below carry the expectation but withhold the body, as a client
  18376. // waiting for `100 Continue` would.
  18377. // A POST that expects `100 Continue` and withholds its two-byte body.
  18378. static std::string expect_headers_only(const std::string &path) {
  18379. return "POST " + path +
  18380. " HTTP/1.1\r\n"
  18381. "Host: localhost\r\n"
  18382. "Content-Length: 2\r\n"
  18383. "Expect: 100-continue\r\n"
  18384. "\r\n";
  18385. }
  18386. class ExpectLazyContinueTest : public ::testing::Test {
  18387. protected:
  18388. void SetUp() override {
  18389. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18390. if (req.path == "/pre-routing") {
  18391. res.status = StatusCode::Unauthorized_401;
  18392. return Server::HandlerResponse::Handled;
  18393. }
  18394. return Server::HandlerResponse::Unhandled;
  18395. });
  18396. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18397. if (req.matched_route == "/pre-request") {
  18398. res.status = StatusCode::Forbidden_403;
  18399. return Server::HandlerResponse::Handled;
  18400. }
  18401. return Server::HandlerResponse::Unhandled;
  18402. });
  18403. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18404. res.set_content("ok", "text/plain");
  18405. });
  18406. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18407. res.set_content("ok", "text/plain");
  18408. });
  18409. svr_.Post("/reader-used", [](const Request &, Response &res,
  18410. const ContentReader &content_reader) {
  18411. std::string body;
  18412. content_reader([&](const char *data, size_t len) {
  18413. body.append(data, len);
  18414. return true;
  18415. });
  18416. res.set_content(body, "text/plain");
  18417. });
  18418. svr_.Post("/reader-unused",
  18419. [](const Request &, Response &res, const ContentReader &) {
  18420. res.set_content("ignored", "text/plain");
  18421. });
  18422. port_ = svr_.bind_to_any_port(HOST);
  18423. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18424. svr_.wait_until_ready();
  18425. }
  18426. void TearDown() override {
  18427. svr_.stop();
  18428. if (thread_.joinable()) { thread_.join(); }
  18429. }
  18430. // Sends `req` and reads until the server closes the connection. Returns
  18431. // false if the read had to wait for the client-side timeout instead.
  18432. bool send_until_closed(const std::string &req, std::string *resp) const {
  18433. auto start = std::chrono::steady_clock::now();
  18434. if (!send_request(3, req, resp, port_)) { return false; }
  18435. auto elapsed = std::chrono::steady_clock::now() - start;
  18436. return elapsed < std::chrono::seconds(2);
  18437. }
  18438. // The final response comes without `100 Continue`, and the server closes
  18439. // the connection since the body may or may not follow.
  18440. void expect_final_without_interim(const std::string &path,
  18441. const char *status_line) const {
  18442. std::string resp;
  18443. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18444. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18445. EXPECT_EQ(0u, resp.find(status_line));
  18446. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18447. }
  18448. Server svr_;
  18449. int port_ = 0;
  18450. thread thread_;
  18451. };
  18452. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18453. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18454. }
  18455. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18456. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18457. }
  18458. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18459. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18460. }
  18461. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18462. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18463. }
  18464. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18465. // The body follows once `100 Continue` has had time to arrive.
  18466. auto req = expect_headers_only("/reader-used");
  18467. req.insert(req.size() - 2, "Connection: close\r\n");
  18468. std::string resp;
  18469. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18470. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18471. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18472. EXPECT_NE(std::string::npos, resp.find("hi"));
  18473. }
  18474. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18475. // Large enough for the client to add `Expect: 100-continue` itself.
  18476. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18477. std::atomic<bool> body_sent{false};
  18478. Client cli(HOST, port_);
  18479. auto res = cli.Post(
  18480. "/pre-request", length,
  18481. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18482. body_sent = true;
  18483. std::string chunk(len, 'x');
  18484. sink.write(chunk.data(), chunk.size());
  18485. return true;
  18486. },
  18487. "application/octet-stream");
  18488. ASSERT_TRUE(res);
  18489. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18490. EXPECT_FALSE(body_sent);
  18491. }
  18492. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18493. Server svr;
  18494. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18495. return StatusCode::ExpectationFailed_417;
  18496. });
  18497. svr.Post("/p", [](const Request &, Response &res) {
  18498. res.set_content("ok", "text/plain");
  18499. });
  18500. auto port = svr.bind_to_any_port(HOST);
  18501. thread t = thread([&] { svr.listen_after_bind(); });
  18502. auto se = detail::scope_exit([&] {
  18503. svr.stop();
  18504. t.join();
  18505. });
  18506. svr.wait_until_ready();
  18507. std::string resp;
  18508. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18509. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18510. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18511. // Exactly one response: the route handler must not run after the 417.
  18512. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18513. }
  18514. #ifndef _WIN32
  18515. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18516. static constexpr char reject[] = "Unauthorized";
  18517. static constexpr char accept[] = "Upload accepted";
  18518. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18519. Server svr;
  18520. svr.set_expect_100_continue_handler(
  18521. [](const Request & /*req*/, Response &res) {
  18522. res.status = StatusCode::Unauthorized_401;
  18523. res.set_content(reject, "text/plain");
  18524. return res.status;
  18525. });
  18526. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18527. res.set_content(accept, "text/plain");
  18528. });
  18529. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18530. auto se = detail::scope_exit([&] {
  18531. svr.stop();
  18532. thread.join();
  18533. ASSERT_FALSE(svr.is_running());
  18534. });
  18535. svr.wait_until_ready();
  18536. {
  18537. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18538. curl_easy_init(), &curl_easy_cleanup};
  18539. ASSERT_NE(curl, nullptr);
  18540. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18541. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18542. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18543. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18544. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18545. &curl_slist_free_all};
  18546. ASSERT_NE(list, nullptr);
  18547. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18548. struct read_data {
  18549. uint64_t read_size;
  18550. uint64_t total_size;
  18551. } data = {0, total_size};
  18552. using read_callback_t =
  18553. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18554. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18555. void *userdata) -> size_t {
  18556. read_data *d = (read_data *)userdata;
  18557. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18558. std::fill_n(ptr, size * nmemb, 'A');
  18559. d->read_size += size * nmemb;
  18560. return size * nmemb;
  18561. };
  18562. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18563. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18564. std::vector<char> buffer;
  18565. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18566. using write_callback_t =
  18567. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18568. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18569. void *userdata) -> size_t {
  18570. std::vector<char> *buf = (std::vector<char> *)userdata;
  18571. buf->reserve(buf->size() + size * nmemb + 1);
  18572. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18573. return size * nmemb;
  18574. };
  18575. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18576. {
  18577. const auto res = curl_easy_perform(curl.get());
  18578. ASSERT_EQ(res, CURLE_OK);
  18579. }
  18580. {
  18581. auto response_code = long{};
  18582. const auto res =
  18583. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18584. ASSERT_EQ(res, CURLE_OK);
  18585. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18586. }
  18587. {
  18588. auto dl = curl_off_t{};
  18589. const auto res =
  18590. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18591. ASSERT_EQ(res, CURLE_OK);
  18592. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18593. }
  18594. {
  18595. buffer.push_back('\0');
  18596. ASSERT_STRCASEEQ(buffer.data(), reject);
  18597. }
  18598. }
  18599. }
  18600. #endif
  18601. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18602. // Regression test for #2458.
  18603. //
  18604. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18605. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18606. // ticket can make the client socket spuriously readable during the
  18607. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18608. // the client withholds the body and then blocks reading a response that never
  18609. // comes, failing with `Failed to read connection`.
  18610. //
  18611. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18612. // within the timeout. This raw OpenSSL server deliberately never sends
  18613. // `100 Continue`; the client must still deliver the body and receive 200.
  18614. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18615. signal(SIGPIPE, SIG_IGN);
  18616. const auto port = PORT + 4;
  18617. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18618. ASSERT_NE(srv, INVALID_SOCKET);
  18619. int opt = 1;
  18620. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18621. sockaddr_in addr{};
  18622. addr.sin_family = AF_INET;
  18623. addr.sin_port = htons(static_cast<uint16_t>(port));
  18624. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18625. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18626. ASSERT_EQ(0, ::listen(srv, 1));
  18627. std::atomic<size_t> server_body_bytes{0};
  18628. auto server_thread = std::thread([&] {
  18629. sockaddr_in cli_addr{};
  18630. socklen_t cli_len = sizeof(cli_addr);
  18631. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18632. if (cli == INVALID_SOCKET) { return; }
  18633. // Bound the lifetime of the server side so a buggy client (which never
  18634. // sends the body) cannot make this thread block forever on join.
  18635. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18636. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18637. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18638. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18639. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18640. SSL *ssl = SSL_new(ctx);
  18641. SSL_set_fd(ssl, static_cast<int>(cli));
  18642. if (SSL_accept(ssl) > 0) {
  18643. // Read the request headers. Reading here also flushes the TLS 1.3
  18644. // session tickets to the client. Deliberately do NOT send
  18645. // `100 Continue`.
  18646. std::string buf;
  18647. char tmp[1024];
  18648. while (buf.find("\r\n\r\n") == std::string::npos) {
  18649. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18650. if (n <= 0) { break; }
  18651. buf.append(tmp, static_cast<size_t>(n));
  18652. }
  18653. // A correct client sends the body now; count what arrives.
  18654. auto pos = buf.find("\r\n\r\n");
  18655. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18656. while (body < 4096) {
  18657. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18658. if (n <= 0) { break; }
  18659. body += static_cast<size_t>(n);
  18660. }
  18661. server_body_bytes = body;
  18662. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18663. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18664. SSL_shutdown(ssl);
  18665. }
  18666. SSL_free(ssl);
  18667. detail::close_socket(cli);
  18668. SSL_CTX_free(ctx);
  18669. });
  18670. auto se = detail::scope_exit([&] {
  18671. server_thread.join();
  18672. detail::close_socket(srv);
  18673. });
  18674. SSLClient cli("127.0.0.1", port);
  18675. cli.enable_server_certificate_verification(false);
  18676. cli.set_connection_timeout(5, 0);
  18677. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18678. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18679. std::string body(4096, 'A');
  18680. auto res = cli.Put("/api/test", body, "application/json");
  18681. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18682. EXPECT_EQ(StatusCode::OK_200, res->status);
  18683. EXPECT_EQ(body.size(), server_body_bytes.load());
  18684. }
  18685. #endif
  18686. template <typename S, typename C>
  18687. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18688. svr.Get("/stream", [&](const Request &, Response &res) {
  18689. auto data = new std::string("01234567890123456789");
  18690. res.set_content_provider(
  18691. data->size(), "text/plain",
  18692. [&, data](size_t offset, size_t length, DataSink &sink) {
  18693. const size_t DATA_CHUNK_SIZE = 4;
  18694. const auto &d = *data;
  18695. std::this_thread::sleep_for(std::chrono::seconds(1));
  18696. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18697. return true;
  18698. },
  18699. [data](bool success) {
  18700. EXPECT_FALSE(success);
  18701. delete data;
  18702. });
  18703. });
  18704. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18705. auto i = new size_t(0);
  18706. res.set_content_provider(
  18707. "text/plain",
  18708. [i](size_t, DataSink &sink) {
  18709. if (*i < 5) {
  18710. std::this_thread::sleep_for(std::chrono::seconds(1));
  18711. sink.write("abcd", 4);
  18712. (*i)++;
  18713. } else {
  18714. sink.done();
  18715. }
  18716. return true;
  18717. },
  18718. [i](bool success) {
  18719. EXPECT_FALSE(success);
  18720. delete i;
  18721. });
  18722. });
  18723. svr.Get("/chunked", [&](const Request &, Response &res) {
  18724. auto i = new size_t(0);
  18725. res.set_chunked_content_provider(
  18726. "text/plain",
  18727. [i](size_t, DataSink &sink) {
  18728. if (*i < 5) {
  18729. std::this_thread::sleep_for(std::chrono::seconds(1));
  18730. sink.os << "abcd";
  18731. (*i)++;
  18732. } else {
  18733. sink.done();
  18734. }
  18735. return true;
  18736. },
  18737. [i](bool success) {
  18738. EXPECT_FALSE(success);
  18739. delete i;
  18740. });
  18741. });
  18742. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18743. auto se = detail::scope_exit([&] {
  18744. svr.stop();
  18745. listen_thread.join();
  18746. ASSERT_FALSE(svr.is_running());
  18747. });
  18748. svr.wait_until_ready();
  18749. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18750. {
  18751. auto start = std::chrono::steady_clock::now();
  18752. auto res = cli.Get("/stream");
  18753. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18754. std::chrono::steady_clock::now() - start)
  18755. .count();
  18756. ASSERT_FALSE(res);
  18757. EXPECT_EQ(Error::Read, res.error());
  18758. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18759. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18760. }
  18761. {
  18762. auto start = std::chrono::steady_clock::now();
  18763. auto res = cli.Get("/stream_without_length");
  18764. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18765. std::chrono::steady_clock::now() - start)
  18766. .count();
  18767. ASSERT_FALSE(res);
  18768. EXPECT_EQ(Error::Read, res.error());
  18769. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18770. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18771. }
  18772. {
  18773. auto start = std::chrono::steady_clock::now();
  18774. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18775. EXPECT_EQ("abcd", string(data, data_length));
  18776. return true;
  18777. });
  18778. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18779. std::chrono::steady_clock::now() - start)
  18780. .count();
  18781. ASSERT_FALSE(res);
  18782. EXPECT_EQ(Error::Read, res.error());
  18783. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18784. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18785. }
  18786. }
  18787. TEST(MaxTimeoutTest, ContentStream) {
  18788. time_t timeout = 2000;
  18789. time_t threshold = 200;
  18790. Server svr;
  18791. Client cli("localhost", PORT);
  18792. max_timeout_test(svr, cli, timeout, threshold);
  18793. }
  18794. #ifdef CPPHTTPLIB_SSL_ENABLED
  18795. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18796. time_t timeout = 2000;
  18797. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18799. SSLClient cli("localhost", PORT);
  18800. cli.enable_server_certificate_verification(false);
  18801. max_timeout_test(svr, cli, timeout, threshold);
  18802. }
  18803. #endif
  18804. class EventDispatcher {
  18805. public:
  18806. EventDispatcher() {}
  18807. bool wait_event(DataSink *sink) {
  18808. unique_lock<mutex> lk(m_);
  18809. int id = id_;
  18810. // Wait with timeout to prevent hanging if client disconnects
  18811. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18812. [&] { return cid_ == id; })) {
  18813. return false; // Timeout occurred
  18814. }
  18815. sink->write(message_.data(), message_.size());
  18816. return true;
  18817. }
  18818. void send_event(const string &message) {
  18819. lock_guard<mutex> lk(m_);
  18820. cid_ = id_++;
  18821. message_ = message;
  18822. cv_.notify_all();
  18823. }
  18824. private:
  18825. mutex m_;
  18826. condition_variable cv_;
  18827. atomic_int id_{0};
  18828. atomic_int cid_{-1};
  18829. string message_;
  18830. };
  18831. TEST(ClientInThreadTest, Issue2068) {
  18832. EventDispatcher ed;
  18833. Server svr;
  18834. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18835. res.set_chunked_content_provider("text/event-stream",
  18836. [&](size_t /*offset*/, DataSink &sink) {
  18837. return ed.wait_event(&sink);
  18838. });
  18839. });
  18840. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18841. svr.wait_until_ready();
  18842. thread event_thread([&] {
  18843. int id = 0;
  18844. while (svr.is_running()) {
  18845. this_thread::sleep_for(chrono::milliseconds(500));
  18846. std::stringstream ss;
  18847. ss << "data: " << id << "\n\n";
  18848. ed.send_event(ss.str());
  18849. id++;
  18850. }
  18851. });
  18852. auto se = detail::scope_exit([&] {
  18853. svr.stop();
  18854. listen_thread.join();
  18855. event_thread.join();
  18856. ASSERT_FALSE(svr.is_running());
  18857. });
  18858. {
  18859. auto client = detail::make_unique<Client>(HOST, PORT);
  18860. client->set_read_timeout(std::chrono::minutes(10));
  18861. std::atomic<bool> stop{false};
  18862. std::thread t([&] {
  18863. client->Get("/event1",
  18864. [&](const char *, size_t) -> bool { return !stop; });
  18865. });
  18866. std::this_thread::sleep_for(std::chrono::seconds(2));
  18867. stop = true;
  18868. client->stop();
  18869. t.join();
  18870. // Reset client after thread has finished
  18871. client.reset();
  18872. }
  18873. }
  18874. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18875. auto handled = false;
  18876. Server svr;
  18877. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18878. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18879. auto se = detail::scope_exit([&] {
  18880. svr.stop();
  18881. t.join();
  18882. ASSERT_FALSE(svr.is_running());
  18883. ASSERT_FALSE(handled);
  18884. });
  18885. svr.wait_until_ready();
  18886. // Two Content-Length headers with different values — must be rejected
  18887. auto req = "POST /test HTTP/1.1\r\n"
  18888. "Content-Length: 5\r\n"
  18889. "Content-Length: 10\r\n"
  18890. "\r\n"
  18891. "hello";
  18892. std::string response;
  18893. ASSERT_TRUE(send_request(1, req, &response));
  18894. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18895. response.substr(0, response.find("\r\n")));
  18896. }
  18897. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18898. auto handled = false;
  18899. Server svr;
  18900. svr.Post("/test", [&](const Request &, Response &res) {
  18901. handled = true;
  18902. res.set_content("ok", "text/plain");
  18903. });
  18904. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18905. auto se = detail::scope_exit([&] {
  18906. svr.stop();
  18907. t.join();
  18908. ASSERT_FALSE(svr.is_running());
  18909. ASSERT_TRUE(handled);
  18910. });
  18911. svr.wait_until_ready();
  18912. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18913. auto req = "POST /test HTTP/1.1\r\n"
  18914. "Host: localhost\r\n"
  18915. "Content-Length: 5\r\n"
  18916. "Content-Length: 5\r\n"
  18917. "\r\n"
  18918. "hello";
  18919. std::string response;
  18920. ASSERT_TRUE(send_request(1, req, &response));
  18921. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18922. }
  18923. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18924. Server svr;
  18925. svr.Get("/test", [](const Request &, Response &res) {
  18926. res.set_content("ok", "text/plain");
  18927. });
  18928. auto port = svr.bind_to_any_port(HOST);
  18929. thread t = thread([&] { svr.listen_after_bind(); });
  18930. auto se = detail::scope_exit([&] {
  18931. svr.stop();
  18932. t.join();
  18933. ASSERT_FALSE(svr.is_running());
  18934. });
  18935. svr.wait_until_ready();
  18936. auto status_line = [&](const std::string &host_lines) {
  18937. std::string res;
  18938. send_request(
  18939. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18940. &res, port);
  18941. return res.substr(0, res.find("\r\n"));
  18942. };
  18943. const char *accepted[] = {
  18944. "Host: localhost\r\n",
  18945. "Host: a.example:8080\r\n",
  18946. "Host: my_service\r\n",
  18947. "Host: [::1]:8080\r\n",
  18948. "Host: [fe80::1%25eth0]\r\n",
  18949. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18950. };
  18951. for (auto host_lines : accepted) {
  18952. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18953. }
  18954. const char *rejected[] = {
  18955. "Host: a.example\r\nHost: b.example\r\n",
  18956. "Host: a.example\r\nHost: a.example\r\n",
  18957. "Host: a@b.example\r\n",
  18958. "Host: a.example/b\r\n",
  18959. "Host: a.example\\b\r\n",
  18960. "Host: a.example?b\r\n",
  18961. "Host: a.example#b\r\n",
  18962. "Host: a.example b.example\r\n",
  18963. };
  18964. for (auto host_lines : rejected) {
  18965. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18966. << host_lines;
  18967. }
  18968. }
  18969. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18970. Server svr;
  18971. svr.Get("/", [](const Request &req, Response &res) {
  18972. EXPECT_EQ(2U, req.trailers.size());
  18973. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18974. // Denied
  18975. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18976. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18977. // Accepted
  18978. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18979. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18980. EXPECT_TRUE(req.has_trailer("X-World"));
  18981. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18982. res.set_content("ok", "text/plain");
  18983. });
  18984. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18985. auto se = detail::scope_exit([&] {
  18986. svr.stop();
  18987. t.join();
  18988. ASSERT_FALSE(svr.is_running());
  18989. });
  18990. svr.wait_until_ready();
  18991. const std::string req = "GET / HTTP/1.1\r\n"
  18992. "Transfer-Encoding: chunked\r\n"
  18993. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18994. "\r\n"
  18995. "0\r\n"
  18996. "Content-Length: 10\r\n"
  18997. "Host: internal.local\r\n"
  18998. "Content-Type: malicious/content\r\n"
  18999. "Cookie: any\r\n"
  19000. "Set-Cookie: any\r\n"
  19001. "X-Forwarded-For: attacker.com\r\n"
  19002. "X-Real-Ip: 1.1.1.1\r\n"
  19003. "X-Hello: hello\r\n"
  19004. "X-World: world\r\n"
  19005. "\r\n";
  19006. std::string res;
  19007. ASSERT_TRUE(send_request(1, req, &res));
  19008. }
  19009. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19010. // several field lines, and the combined value is what has to be parsed. A
  19011. // Trailer field split across lines therefore declares every name it lists;
  19012. // reading only the first line silently drops the trailers the later lines
  19013. // declare. The prohibited-trailer filter still applies to every line.
  19014. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19015. Server svr;
  19016. size_t observed_trailer_count = 0;
  19017. std::string observed_hello;
  19018. std::string observed_world;
  19019. bool observed_content_length = true;
  19020. svr.Get("/", [&](const Request &req, Response &res) {
  19021. observed_trailer_count = req.trailers.size();
  19022. observed_hello = req.get_trailer_value("X-Hello");
  19023. observed_world = req.get_trailer_value("X-World");
  19024. observed_content_length = req.has_trailer("Content-Length");
  19025. res.set_content("ok", "text/plain");
  19026. });
  19027. auto port = svr.bind_to_any_port(HOST);
  19028. thread t = thread([&]() { svr.listen_after_bind(); });
  19029. auto se = detail::scope_exit([&] {
  19030. svr.stop();
  19031. t.join();
  19032. ASSERT_FALSE(svr.is_running());
  19033. });
  19034. svr.wait_until_ready();
  19035. const std::string req = "GET / HTTP/1.1\r\n"
  19036. "Host: localhost\r\n"
  19037. "Transfer-Encoding: chunked\r\n"
  19038. "Trailer: X-Hello\r\n"
  19039. "Trailer: X-World, Content-Length\r\n"
  19040. "\r\n"
  19041. "0\r\n"
  19042. "X-Hello: hello\r\n"
  19043. "X-World: world\r\n"
  19044. "Content-Length: 10\r\n"
  19045. "\r\n";
  19046. std::string res;
  19047. ASSERT_TRUE(send_request(1, req, &res, port));
  19048. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19049. // Accepted: both field lines contribute to the declared set
  19050. EXPECT_EQ(2U, observed_trailer_count);
  19051. EXPECT_EQ(observed_hello, "hello");
  19052. EXPECT_EQ(observed_world, "world");
  19053. // Denied: a prohibited name stays prohibited on a later field line
  19054. EXPECT_FALSE(observed_content_length);
  19055. }
  19056. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19057. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19058. // unbounded run of fields that are never declared, because the counter would
  19059. // only advance for declared fields.
  19060. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19061. Server svr;
  19062. bool handler_called = false;
  19063. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19064. handler_called = true;
  19065. res.set_content("ok", "text/plain");
  19066. });
  19067. auto port = svr.bind_to_any_port(HOST);
  19068. thread t = thread([&]() { svr.listen_after_bind(); });
  19069. auto se = detail::scope_exit([&] {
  19070. svr.stop();
  19071. t.join();
  19072. ASSERT_FALSE(svr.is_running());
  19073. });
  19074. svr.wait_until_ready();
  19075. // Declare nothing, then send far more undeclared trailer fields than the
  19076. // header-count limit. Parsing must stop and reject the request rather than
  19077. // read every line.
  19078. std::string req = "GET / HTTP/1.1\r\n"
  19079. "Transfer-Encoding: chunked\r\n"
  19080. "\r\n"
  19081. "0\r\n";
  19082. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19083. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19084. }
  19085. req += "\r\n";
  19086. std::string res;
  19087. ASSERT_TRUE(send_request(1, req, &res, port));
  19088. // The request is rejected before the handler runs.
  19089. EXPECT_FALSE(handler_called);
  19090. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19091. }
  19092. // The set of declared trailer names is capped so a peer cannot grow it without
  19093. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19094. // declared past the cap is not honored, even if the field is actually sent.
  19095. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19096. Server svr;
  19097. // One name inside the cap and one past it, so the test tracks the cap rather
  19098. // than a fixed count.
  19099. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19100. const std::string within_cap_name = "X-T-0";
  19101. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19102. bool observed_within_cap = false;
  19103. bool observed_past_cap = false;
  19104. svr.Get("/", [&](const Request &req, Response &res) {
  19105. observed_within_cap = req.has_trailer(within_cap_name);
  19106. observed_past_cap = req.has_trailer(past_cap_name);
  19107. res.set_content("ok", "text/plain");
  19108. });
  19109. auto port = svr.bind_to_any_port(HOST);
  19110. thread t = thread([&]() { svr.listen_after_bind(); });
  19111. auto se = detail::scope_exit([&] {
  19112. svr.stop();
  19113. t.join();
  19114. ASSERT_FALSE(svr.is_running());
  19115. });
  19116. svr.wait_until_ready();
  19117. // Declare more trailer names than the cap in a single Trailer field, then
  19118. // actually send the first (within the cap) and the last (past it).
  19119. std::string trailer_decl = "Trailer: ";
  19120. for (int i = 0; i < declared_count; i++) {
  19121. if (i != 0) { trailer_decl += ", "; }
  19122. trailer_decl += "X-T-" + std::to_string(i);
  19123. }
  19124. trailer_decl += "\r\n";
  19125. const std::string req = "GET / HTTP/1.1\r\n"
  19126. "Host: localhost\r\n"
  19127. "Transfer-Encoding: chunked\r\n" +
  19128. trailer_decl +
  19129. "\r\n"
  19130. "0\r\n" +
  19131. within_cap_name + ": a\r\n" + past_cap_name +
  19132. ": b\r\n"
  19133. "\r\n";
  19134. std::string res;
  19135. ASSERT_TRUE(send_request(1, req, &res, port));
  19136. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19137. // A name within the cap is honored; one declared past the cap is dropped.
  19138. EXPECT_TRUE(observed_within_cap);
  19139. EXPECT_FALSE(observed_past_cap);
  19140. }
  19141. // A direct client that is not listed in trusted_proxies must not be able to
  19142. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19143. // the peer address on the actual TCP connection determines whether the
  19144. // header is honored.
  19145. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19146. Server svr;
  19147. // Deliberately does NOT include the loopback address the test client
  19148. // actually connects from, so the direct connection is not a trusted proxy.
  19149. svr.set_trusted_proxies({"203.0.113.66"});
  19150. std::string observed_remote_addr;
  19151. svr.Get("/ip", [&](const Request &req, Response &res) {
  19152. observed_remote_addr = req.remote_addr;
  19153. res.set_content("ok", "text/plain");
  19154. });
  19155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19156. auto se = detail::scope_exit([&] {
  19157. svr.stop();
  19158. t.join();
  19159. ASSERT_FALSE(svr.is_running());
  19160. });
  19161. svr.wait_until_ready();
  19162. Client cli(HOST, PORT);
  19163. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19165. EXPECT_EQ(StatusCode::OK_200, res->status);
  19166. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19167. // ignored entirely and the real connection-level address retained.
  19168. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19169. observed_remote_addr == "127.0.0.1");
  19170. }
  19171. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19172. Server svr;
  19173. std::string observed_remote_addr;
  19174. std::string observed_xff;
  19175. svr.Get("/ip", [&](const Request &req, Response &res) {
  19176. observed_remote_addr = req.remote_addr;
  19177. observed_xff = req.get_header_value("X-Forwarded-For");
  19178. res.set_content("ok", "text/plain");
  19179. });
  19180. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19181. auto se = detail::scope_exit([&] {
  19182. svr.stop();
  19183. t.join();
  19184. ASSERT_FALSE(svr.is_running());
  19185. });
  19186. svr.wait_until_ready();
  19187. Client cli(HOST, PORT);
  19188. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19190. EXPECT_EQ(StatusCode::OK_200, res->status);
  19191. EXPECT_EQ(observed_xff, "203.0.113.66");
  19192. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19193. observed_remote_addr == "127.0.0.1");
  19194. }
  19195. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19196. Server svr;
  19197. svr.set_trusted_proxies({"203.0.113.66"});
  19198. std::string observed_remote_addr;
  19199. std::string observed_xff;
  19200. svr.Get("/ip", [&](const Request &req, Response &res) {
  19201. observed_remote_addr = req.remote_addr;
  19202. observed_xff = req.get_header_value("X-Forwarded-For");
  19203. res.set_content("ok", "text/plain");
  19204. });
  19205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19206. auto se = detail::scope_exit([&] {
  19207. svr.stop();
  19208. t.join();
  19209. ASSERT_FALSE(svr.is_running());
  19210. });
  19211. svr.wait_until_ready();
  19212. Client cli(HOST, PORT);
  19213. auto res = cli.Get("/ip");
  19214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19215. EXPECT_EQ(StatusCode::OK_200, res->status);
  19216. EXPECT_EQ(observed_xff, "");
  19217. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19218. observed_remote_addr == "127.0.0.1");
  19219. }
  19220. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19221. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19222. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19223. Server svr;
  19224. svr.set_trusted_proxies({"127.0.0.1"});
  19225. svr.Get("/ip", [](const Request &req, Response &res) {
  19226. res.set_content(req.remote_addr, "text/plain");
  19227. });
  19228. auto port = svr.bind_to_any_port("::");
  19229. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19230. thread t = thread([&] { svr.listen_after_bind(); });
  19231. auto se = detail::scope_exit([&] {
  19232. svr.stop();
  19233. t.join();
  19234. ASSERT_FALSE(svr.is_running());
  19235. });
  19236. svr.wait_until_ready();
  19237. Client cli("127.0.0.1", port);
  19238. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19240. EXPECT_EQ("198.51.100.23", res->body);
  19241. }
  19242. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19243. Server svr;
  19244. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19245. svr.Get("/ip", [](const Request &req, Response &res) {
  19246. res.set_content(req.remote_addr, "text/plain");
  19247. });
  19248. auto port = svr.bind_to_any_port(HOST);
  19249. ASSERT_GT(port, 0);
  19250. thread t = thread([&] { svr.listen_after_bind(); });
  19251. auto se = detail::scope_exit([&] {
  19252. svr.stop();
  19253. t.join();
  19254. ASSERT_FALSE(svr.is_running());
  19255. });
  19256. svr.wait_until_ready();
  19257. Client cli(HOST, port);
  19258. auto res = cli.Get(
  19259. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19261. EXPECT_EQ("198.51.100.23", res->body);
  19262. }
  19263. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19264. Server svr;
  19265. // Include the loopback address the test client actually connects from, so
  19266. // the direct connection itself is recognized as the trusted proxy hop.
  19267. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19268. std::string observed_remote_addr;
  19269. std::string observed_xff;
  19270. svr.Get("/ip", [&](const Request &req, Response &res) {
  19271. observed_remote_addr = req.remote_addr;
  19272. observed_xff = req.get_header_value("X-Forwarded-For");
  19273. res.set_content("ok", "text/plain");
  19274. });
  19275. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19276. auto se = detail::scope_exit([&] {
  19277. svr.stop();
  19278. t.join();
  19279. ASSERT_FALSE(svr.is_running());
  19280. });
  19281. svr.wait_until_ready();
  19282. Client cli(HOST, PORT);
  19283. auto res = cli.Get(
  19284. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19286. EXPECT_EQ(StatusCode::OK_200, res->status);
  19287. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19288. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19289. }
  19290. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19291. Server svr;
  19292. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19293. std::string observed_remote_addr;
  19294. std::string observed_xff;
  19295. svr.Get("/ip", [&](const Request &req, Response &res) {
  19296. observed_remote_addr = req.remote_addr;
  19297. observed_xff = req.get_header_value("X-Forwarded-For");
  19298. res.set_content("ok", "text/plain");
  19299. });
  19300. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19301. auto se = detail::scope_exit([&] {
  19302. svr.stop();
  19303. t.join();
  19304. ASSERT_FALSE(svr.is_running());
  19305. });
  19306. svr.wait_until_ready();
  19307. Client cli(HOST, PORT);
  19308. auto res = cli.Get(
  19309. "/ip",
  19310. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19312. EXPECT_EQ(StatusCode::OK_200, res->status);
  19313. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19314. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19315. }
  19316. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19317. Server svr;
  19318. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19319. std::string observed_remote_addr;
  19320. std::string observed_xff;
  19321. svr.Get("/ip", [&](const Request &req, Response &res) {
  19322. observed_remote_addr = req.remote_addr;
  19323. observed_xff = req.get_header_value("X-Forwarded-For");
  19324. res.set_content("ok", "text/plain");
  19325. });
  19326. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19327. auto se = detail::scope_exit([&] {
  19328. svr.stop();
  19329. t.join();
  19330. ASSERT_FALSE(svr.is_running());
  19331. });
  19332. svr.wait_until_ready();
  19333. Client cli(HOST, PORT);
  19334. auto res = cli.Get(
  19335. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19337. EXPECT_EQ(StatusCode::OK_200, res->status);
  19338. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19339. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19340. // and must not be selected.
  19341. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19342. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19343. }
  19344. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19345. Server svr;
  19346. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19347. std::string observed_remote_addr;
  19348. svr.Get("/ip", [&](const Request &req, Response &res) {
  19349. observed_remote_addr = req.remote_addr;
  19350. res.set_content("ok", "text/plain");
  19351. });
  19352. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19353. auto se = detail::scope_exit([&] {
  19354. svr.stop();
  19355. t.join();
  19356. ASSERT_FALSE(svr.is_running());
  19357. });
  19358. svr.wait_until_ready();
  19359. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19360. // a forged address and the trusted proxy's own address; the forged value must
  19361. // not win over the address the trusted proxy actually recorded.
  19362. Client cli(HOST, PORT);
  19363. auto res = cli.Get(
  19364. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19366. EXPECT_EQ(StatusCode::OK_200, res->status);
  19367. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19368. }
  19369. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19370. Server svr;
  19371. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19372. std::string observed_remote_addr;
  19373. std::string observed_xff;
  19374. svr.Get("/ip", [&](const Request &req, Response &res) {
  19375. observed_remote_addr = req.remote_addr;
  19376. observed_xff = req.get_header_value("X-Forwarded-For");
  19377. res.set_content("ok", "text/plain");
  19378. });
  19379. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19380. auto se = detail::scope_exit([&] {
  19381. svr.stop();
  19382. t.join();
  19383. ASSERT_FALSE(svr.is_running());
  19384. });
  19385. svr.wait_until_ready();
  19386. Client cli(HOST, PORT);
  19387. auto res = cli.Get(
  19388. "/ip",
  19389. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19391. EXPECT_EQ(StatusCode::OK_200, res->status);
  19392. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19393. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19394. }
  19395. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19396. Server svr;
  19397. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19398. std::string observed_remote_addr;
  19399. std::string observed_xff;
  19400. svr.Get("/ip", [&](const Request &req, Response &res) {
  19401. observed_remote_addr = req.remote_addr;
  19402. observed_xff = req.get_header_value("X-Forwarded-For");
  19403. res.set_content("ok", "text/plain");
  19404. });
  19405. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19406. auto se = detail::scope_exit([&] {
  19407. svr.stop();
  19408. t.join();
  19409. ASSERT_FALSE(svr.is_running());
  19410. });
  19411. svr.wait_until_ready();
  19412. std::string raw_req =
  19413. "GET /ip HTTP/1.1\r\n"
  19414. "Host: localhost\r\n"
  19415. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19416. "Connection: close\r\n"
  19417. "\r\n";
  19418. std::string out;
  19419. ASSERT_TRUE(send_request(5, raw_req, &out));
  19420. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19421. // Header parser trims surrounding whitespace of the header value
  19422. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19423. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19424. }
  19425. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19426. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19427. // their own X-Forwarded-For as a separate field line rather than extending the
  19428. // one the client sent, so every occurrence has to be taken into account.
  19429. // Reading only the first one hands back the address the client chose.
  19430. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19431. Server svr;
  19432. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19433. std::string observed_remote_addr;
  19434. size_t observed_xff_count = 0;
  19435. svr.Get("/ip", [&](const Request &req, Response &res) {
  19436. observed_remote_addr = req.remote_addr;
  19437. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19438. res.set_content("ok", "text/plain");
  19439. });
  19440. auto port = svr.bind_to_any_port(HOST);
  19441. thread t = thread([&]() { svr.listen_after_bind(); });
  19442. auto se = detail::scope_exit([&] {
  19443. svr.stop();
  19444. t.join();
  19445. ASSERT_FALSE(svr.is_running());
  19446. });
  19447. svr.wait_until_ready();
  19448. // The client supplies the first field line; the trusted proxy appends the
  19449. // address it observed as a second one.
  19450. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19451. "Host: localhost\r\n"
  19452. "X-Forwarded-For: 1.2.3.4\r\n"
  19453. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19454. "Connection: close\r\n"
  19455. "\r\n";
  19456. std::string out;
  19457. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19458. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19459. EXPECT_EQ(observed_xff_count, 2U);
  19460. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19461. // The same chain spread over one field line per hop derives the same client
  19462. // address, i.e. the split and the comma-joined representations agree.
  19463. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19464. "Host: localhost\r\n"
  19465. "X-Forwarded-For: 1.2.3.4\r\n"
  19466. "X-Forwarded-For: 198.51.100.23\r\n"
  19467. "X-Forwarded-For: 192.0.2.45\r\n"
  19468. "Connection: close\r\n"
  19469. "\r\n";
  19470. out.clear();
  19471. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19472. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19473. EXPECT_EQ(observed_xff_count, 3U);
  19474. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19475. }
  19476. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19477. // crash the server (it used to call front() on an empty vector inside
  19478. // get_client_ip). The connection-level remote address must be retained instead.
  19479. static void run_malformed_xff_test(const std::string &xff_value) {
  19480. Server svr;
  19481. svr.set_trusted_proxies({"192.0.2.45"});
  19482. std::string observed_remote_addr;
  19483. svr.Get("/ip", [&](const Request &req, Response &res) {
  19484. observed_remote_addr = req.remote_addr;
  19485. res.set_content("ok", "text/plain");
  19486. });
  19487. int port = 0;
  19488. thread t = thread([&]() {
  19489. port = svr.bind_to_any_port(HOST);
  19490. svr.listen_after_bind();
  19491. });
  19492. auto se = detail::scope_exit([&] {
  19493. svr.stop();
  19494. t.join();
  19495. ASSERT_FALSE(svr.is_running());
  19496. });
  19497. svr.wait_until_ready();
  19498. Client cli(HOST, port);
  19499. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19501. EXPECT_EQ(StatusCode::OK_200, res->status);
  19502. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19503. observed_remote_addr == "127.0.0.1");
  19504. }
  19505. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19506. run_malformed_xff_test("");
  19507. }
  19508. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19509. run_malformed_xff_test(",");
  19510. }
  19511. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19512. run_malformed_xff_test(", , ,");
  19513. }
  19514. // The same rule applies to Accept: a request whose acceptable types are spread
  19515. // over several field lines must be negotiated against all of them.
  19516. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19517. // case-insensitive connection options. Comparing the whole field value against
  19518. // one option misses a client that sends several of them, and misses every
  19519. // casing but the one written in the comparison.
  19520. //
  19521. // Sends req, reads the response, then reuses the same socket for a second
  19522. // request to find out whether the server kept the connection.
  19523. static void probe_connection_reuse(int port, const std::string &req,
  19524. bool *announced_close, bool *reusable) {
  19525. auto error = Error::Success;
  19526. auto sock = detail::create_client_socket(
  19527. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19528. /*connection_timeout_sec=*/5, 0,
  19529. /*read_timeout_sec=*/1, 0,
  19530. /*write_timeout_sec=*/5, 0, std::string(), error);
  19531. ASSERT_NE(sock, INVALID_SOCKET);
  19532. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19533. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19534. "Host: localhost\r\n"
  19535. "Connection: close\r\n"
  19536. "\r\n";
  19537. std::string first_response;
  19538. std::string second_response;
  19539. detail::process_client_socket(
  19540. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19541. [&](Stream &strm) {
  19542. if (strm.write(req.data(), req.size()) !=
  19543. static_cast<ssize_t>(req.size())) {
  19544. return false;
  19545. }
  19546. char buf[512];
  19547. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19548. // Headers plus the two-byte body of the handler below
  19549. while (reader.getline()) {
  19550. first_response += reader.ptr();
  19551. if (first_response.find("ok") != std::string::npos) { break; }
  19552. }
  19553. if (strm.write(second.data(), second.size()) !=
  19554. static_cast<ssize_t>(second.size())) {
  19555. return true;
  19556. }
  19557. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19558. while (reader2.getline()) {
  19559. second_response += reader2.ptr();
  19560. if (second_response.find("ok") != std::string::npos) { break; }
  19561. }
  19562. return true;
  19563. });
  19564. *announced_close =
  19565. first_response.find("Connection: close") != std::string::npos;
  19566. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19567. }
  19568. class ConnectionTokenTest : public ::testing::Test {
  19569. protected:
  19570. void SetUp() override {
  19571. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19572. res.set_content("ok", "text/plain");
  19573. });
  19574. port_ = svr_.bind_to_any_port(HOST);
  19575. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19576. svr_.wait_until_ready();
  19577. }
  19578. void TearDown() override {
  19579. svr_.stop();
  19580. if (thread_.joinable()) { thread_.join(); }
  19581. }
  19582. Server svr_;
  19583. int port_ = 0;
  19584. thread thread_;
  19585. };
  19586. // "close" alongside another option still closes the connection, and the
  19587. // response says so rather than leaving the peer to discover it.
  19588. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19589. bool announced_close = false;
  19590. bool reusable = true;
  19591. probe_connection_reuse(port_,
  19592. "GET /keepalive HTTP/1.1\r\n"
  19593. "Host: localhost\r\n"
  19594. "Connection: keep-alive, close\r\n"
  19595. "\r\n",
  19596. &announced_close, &reusable);
  19597. EXPECT_TRUE(announced_close);
  19598. EXPECT_FALSE(reusable);
  19599. }
  19600. // "close" split over two field lines is the same list, so it is honored too.
  19601. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19602. bool announced_close = false;
  19603. bool reusable = true;
  19604. probe_connection_reuse(port_,
  19605. "GET /keepalive HTTP/1.1\r\n"
  19606. "Host: localhost\r\n"
  19607. "Connection: keep-alive\r\n"
  19608. "Connection: close\r\n"
  19609. "\r\n",
  19610. &announced_close, &reusable);
  19611. EXPECT_TRUE(announced_close);
  19612. EXPECT_FALSE(reusable);
  19613. }
  19614. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19615. // keep-alive in the spelling everyone actually sends keeps its connection.
  19616. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19617. bool announced_close = false;
  19618. bool reusable = false;
  19619. probe_connection_reuse(port_,
  19620. "GET /keepalive HTTP/1.0\r\n"
  19621. "Host: localhost\r\n"
  19622. "Connection: keep-alive\r\n"
  19623. "\r\n",
  19624. &announced_close, &reusable);
  19625. EXPECT_FALSE(announced_close);
  19626. EXPECT_TRUE(reusable);
  19627. }
  19628. // A token the value merely contains is not the token itself.
  19629. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19630. bool announced_close = false;
  19631. bool reusable = false;
  19632. probe_connection_reuse(port_,
  19633. "GET /keepalive HTTP/1.1\r\n"
  19634. "Host: localhost\r\n"
  19635. "Connection: notclose\r\n"
  19636. "\r\n",
  19637. &announced_close, &reusable);
  19638. EXPECT_FALSE(announced_close);
  19639. EXPECT_TRUE(reusable);
  19640. }
  19641. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19642. Server svr;
  19643. std::vector<std::string> observed_types;
  19644. svr.Get("/", [&](const Request &req, Response &res) {
  19645. observed_types = req.accept_content_types;
  19646. res.set_content("ok", "text/plain");
  19647. });
  19648. auto port = svr.bind_to_any_port(HOST);
  19649. thread t = thread([&]() { svr.listen_after_bind(); });
  19650. auto se = detail::scope_exit([&] {
  19651. svr.stop();
  19652. t.join();
  19653. ASSERT_FALSE(svr.is_running());
  19654. });
  19655. svr.wait_until_ready();
  19656. Client cli(HOST, port);
  19657. Headers headers;
  19658. headers.emplace("Accept", "text/plain;q=0.5");
  19659. headers.emplace("Accept", "application/json");
  19660. auto res = cli.Get("/", headers);
  19661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19662. EXPECT_EQ(StatusCode::OK_200, res->status);
  19663. // Sorted by q-value, so the second field line's type comes first
  19664. ASSERT_EQ(2U, observed_types.size());
  19665. EXPECT_EQ("application/json", observed_types[0]);
  19666. EXPECT_EQ("text/plain", observed_types[1]);
  19667. }
  19668. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19669. // empty field line must not contribute a bare comma to the combined value.
  19670. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19671. Server svr;
  19672. std::vector<std::string> observed_types;
  19673. svr.Get("/", [&](const Request &req, Response &res) {
  19674. observed_types = req.accept_content_types;
  19675. res.set_content("ok", "text/plain");
  19676. });
  19677. auto port = svr.bind_to_any_port(HOST);
  19678. thread t = thread([&]() { svr.listen_after_bind(); });
  19679. auto se = detail::scope_exit([&] {
  19680. svr.stop();
  19681. t.join();
  19682. ASSERT_FALSE(svr.is_running());
  19683. });
  19684. svr.wait_until_ready();
  19685. // Empty first field line, then a real one
  19686. std::string raw_req = "GET / HTTP/1.1\r\n"
  19687. "Host: localhost\r\n"
  19688. "Accept:\r\n"
  19689. "Accept: application/json\r\n"
  19690. "Connection: close\r\n"
  19691. "\r\n";
  19692. std::string out;
  19693. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19694. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19695. ASSERT_EQ(1U, observed_types.size());
  19696. EXPECT_EQ("application/json", observed_types[0]);
  19697. }
  19698. // The skip in get_combined_header_value() is what keeps an empty field line
  19699. // from contributing a bare comma. Only a trailing empty field line exercises
  19700. // it: a leading one is already covered by the "combined is still empty" check,
  19701. // and parse_accept_header() now ignores the empty element either way, so the
  19702. // request-level test above can no longer tell the two apart.
  19703. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19704. Headers headers;
  19705. headers.emplace("Accept", "text/html");
  19706. headers.emplace("Accept", "");
  19707. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19708. headers.clear();
  19709. headers.emplace("Accept", "");
  19710. headers.emplace("Accept", "application/json");
  19711. EXPECT_EQ("application/json",
  19712. detail::get_combined_header_value(headers, "Accept"));
  19713. }
  19714. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19715. // An encoding offered on a later Accept-Encoding field line is still offered.
  19716. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19717. Server svr;
  19718. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19719. res.set_content(std::string(1024, 'x'), "text/plain");
  19720. });
  19721. auto port = svr.bind_to_any_port(HOST);
  19722. thread t = thread([&]() { svr.listen_after_bind(); });
  19723. auto se = detail::scope_exit([&] {
  19724. svr.stop();
  19725. t.join();
  19726. ASSERT_FALSE(svr.is_running());
  19727. });
  19728. svr.wait_until_ready();
  19729. Client cli(HOST, port);
  19730. cli.set_decompress(false);
  19731. Headers headers;
  19732. headers.emplace("Accept-Encoding", "identity");
  19733. headers.emplace("Accept-Encoding", "gzip");
  19734. auto res = cli.Get("/", headers);
  19735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19736. EXPECT_EQ(StatusCode::OK_200, res->status);
  19737. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19738. }
  19739. #endif
  19740. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19741. // Transfer-Encoding is not its body.
  19742. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19743. Server svr;
  19744. svr.set_payload_max_length(8);
  19745. svr.Post("/test", [](const Request &, Response &res) {
  19746. res.set_content("ok", "text/plain");
  19747. });
  19748. auto port = svr.bind_to_any_port(HOST);
  19749. ASSERT_GT(port, 0);
  19750. thread t = thread([&] { svr.listen_after_bind(); });
  19751. auto se = detail::scope_exit([&] {
  19752. svr.stop();
  19753. t.join();
  19754. ASSERT_FALSE(svr.is_running());
  19755. });
  19756. svr.wait_until_ready();
  19757. std::string resp;
  19758. ASSERT_TRUE(send_request(1,
  19759. "POST /test HTTP/1.1\r\n"
  19760. "Host: localhost\r\n"
  19761. "Connection: close\r\n"
  19762. "\r\n" +
  19763. std::string(16, 'X'),
  19764. &resp, port));
  19765. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19766. }
  19767. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19768. Server svr;
  19769. svr.Post("/post", [&](const Request &req, Response &res) {
  19770. res.set_content(req.body, "text/plain");
  19771. });
  19772. svr.Put("/put", [&](const Request &req, Response &res) {
  19773. res.set_content(req.body, "text/plain");
  19774. });
  19775. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19776. res.set_content(req.body, "text/plain");
  19777. });
  19778. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19779. res.set_content(req.body, "text/plain");
  19780. });
  19781. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19782. auto se = detail::scope_exit([&] {
  19783. svr.stop();
  19784. t.join();
  19785. ASSERT_FALSE(svr.is_running());
  19786. });
  19787. svr.wait_until_ready();
  19788. std::string resp;
  19789. // POST without Content-Length
  19790. ASSERT_TRUE(send_request(5,
  19791. "POST /post HTTP/1.1\r\n"
  19792. "Host: localhost\r\n"
  19793. "Connection: close\r\n"
  19794. "\r\n",
  19795. &resp));
  19796. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19797. // PUT without Content-Length
  19798. resp.clear();
  19799. ASSERT_TRUE(send_request(5,
  19800. "PUT /put HTTP/1.1\r\n"
  19801. "Host: localhost\r\n"
  19802. "Connection: close\r\n"
  19803. "\r\n",
  19804. &resp));
  19805. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19806. // PATCH without Content-Length
  19807. resp.clear();
  19808. ASSERT_TRUE(send_request(5,
  19809. "PATCH /patch HTTP/1.1\r\n"
  19810. "Host: localhost\r\n"
  19811. "Connection: close\r\n"
  19812. "\r\n",
  19813. &resp));
  19814. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19815. // DELETE without Content-Length
  19816. resp.clear();
  19817. ASSERT_TRUE(send_request(5,
  19818. "DELETE /delete HTTP/1.1\r\n"
  19819. "Host: localhost\r\n"
  19820. "Connection: close\r\n"
  19821. "\r\n",
  19822. &resp));
  19823. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19824. }
  19825. //==============================================================================
  19826. // open_stream() Tests
  19827. //==============================================================================
  19828. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19829. std::string result;
  19830. char buf[8192];
  19831. ssize_t n;
  19832. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19833. result.append(buf, static_cast<size_t>(n));
  19834. }
  19835. return result;
  19836. }
  19837. // Mock stream for unit tests
  19838. class MockStream : public Stream {
  19839. public:
  19840. std::string data;
  19841. size_t pos = 0;
  19842. ssize_t error_after = -1; // -1 = no error
  19843. explicit MockStream(const std::string &d, ssize_t err = -1)
  19844. : data(d), error_after(err) {}
  19845. bool is_readable() const override { return true; }
  19846. bool wait_readable() const override { return true; }
  19847. bool wait_writable() const override { return true; }
  19848. ssize_t read(char *ptr, size_t size) override {
  19849. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19850. if (pos >= data.size()) return 0;
  19851. size_t limit =
  19852. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19853. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19854. std::memcpy(ptr, data.data() + pos, to_read);
  19855. pos += to_read;
  19856. return static_cast<ssize_t>(to_read);
  19857. }
  19858. ssize_t write(const char *, size_t) override { return -1; }
  19859. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19860. ip = "127.0.0.1";
  19861. port = 0;
  19862. }
  19863. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19864. ip = "127.0.0.1";
  19865. port = 0;
  19866. }
  19867. socket_t socket() const override { return INVALID_SOCKET; }
  19868. time_t duration() const override { return 0; }
  19869. };
  19870. TEST(StreamHandleTest, Basic) {
  19871. ClientImpl::StreamHandle handle;
  19872. EXPECT_FALSE(handle.is_valid());
  19873. handle.response = detail::make_unique<Response>();
  19874. handle.error = Error::Connection;
  19875. EXPECT_FALSE(handle.is_valid());
  19876. handle.error = Error::Success;
  19877. EXPECT_TRUE(handle.is_valid());
  19878. }
  19879. TEST(BodyReaderTest, Basic) {
  19880. MockStream stream("Hello, World!");
  19881. detail::BodyReader reader;
  19882. reader.stream = &stream;
  19883. reader.content_length = 13;
  19884. char buf[32];
  19885. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19886. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19887. EXPECT_TRUE(reader.eof);
  19888. }
  19889. TEST(BodyReaderTest, NoStream) {
  19890. detail::BodyReader reader;
  19891. char buf[32];
  19892. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19893. EXPECT_EQ(Error::Connection, reader.last_error);
  19894. }
  19895. TEST(BodyReaderTest, Error) {
  19896. MockStream stream("Hello, World!", 5);
  19897. detail::BodyReader reader;
  19898. reader.stream = &stream;
  19899. reader.content_length = 13;
  19900. char buf[32];
  19901. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19902. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19903. EXPECT_EQ(Error::Read, reader.last_error);
  19904. }
  19905. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19906. // Mock-based StreamHandle tests relying on private internals are removed.
  19907. class OpenStreamTest : public ::testing::Test {
  19908. protected:
  19909. void SetUp() override {
  19910. svr_.Get("/hello", [](const Request &, Response &res) {
  19911. res.set_content("Hello World!", "text/plain");
  19912. });
  19913. svr_.Get("/large", [](const Request &, Response &res) {
  19914. res.set_content(std::string(10000, 'X'), "text/plain");
  19915. });
  19916. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19917. res.set_content("Hello World!", "image/jpeg");
  19918. res.set_header("Content-Encoding", "UTF-8");
  19919. });
  19920. svr_.Get("/chunked", [](const Request &, Response &res) {
  19921. res.set_chunked_content_provider("text/plain",
  19922. [](size_t offset, DataSink &sink) {
  19923. if (offset < 15) {
  19924. sink.write("chunk", 5);
  19925. return true;
  19926. }
  19927. sink.done();
  19928. return true;
  19929. });
  19930. });
  19931. svr_.Get("/compressible", [](const Request &, Response &res) {
  19932. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19933. DataSink &sink) {
  19934. if (offset < 100 * 1024) {
  19935. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19936. sink.write(chunk.data(), chunk.size());
  19937. return true;
  19938. }
  19939. sink.done();
  19940. return true;
  19941. });
  19942. });
  19943. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19944. [](const Request & /*req*/, Response &res) {
  19945. auto i = new int(0);
  19946. res.set_header("Trailer", "Content-Length, X-Allowed");
  19947. res.set_chunked_content_provider(
  19948. "text/plain",
  19949. [i](size_t /*offset*/, DataSink &sink) {
  19950. switch (*i) {
  19951. case 0: sink.os << "123"; break;
  19952. case 1: sink.os << "456"; break;
  19953. case 2: sink.os << "789"; break;
  19954. case 3: {
  19955. sink.done_with_trailer(
  19956. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19957. } break;
  19958. }
  19959. (*i)++;
  19960. return true;
  19961. },
  19962. [i](bool success) {
  19963. EXPECT_TRUE(success);
  19964. delete i;
  19965. });
  19966. });
  19967. // Echo headers endpoint for header-related tests
  19968. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19969. std::string body;
  19970. for (const auto &h : req.headers) {
  19971. body.append(h.first);
  19972. body.push_back(':');
  19973. body.append(h.second);
  19974. body.push_back('\n');
  19975. }
  19976. res.set_content(body, "text/plain");
  19977. });
  19978. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19979. std::string body;
  19980. for (const auto &h : req.headers) {
  19981. body.append(h.first);
  19982. body.push_back(':');
  19983. body.append(h.second);
  19984. body.push_back('\n');
  19985. }
  19986. res.set_content(body, "text/plain");
  19987. });
  19988. port_ = svr_.bind_to_any_port("127.0.0.1");
  19989. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19990. svr_.wait_until_ready();
  19991. }
  19992. void TearDown() override {
  19993. svr_.stop();
  19994. if (thread_.joinable()) thread_.join();
  19995. }
  19996. Server svr_;
  19997. std::thread thread_;
  19998. int port_ = 0;
  19999. };
  20000. TEST_F(OpenStreamTest, Basic) {
  20001. Client cli("127.0.0.1", port_);
  20002. auto handle = cli.open_stream("GET", "/hello");
  20003. EXPECT_TRUE(handle.is_valid());
  20004. EXPECT_EQ("Hello World!", read_all(handle));
  20005. }
  20006. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20007. Client cli("127.0.0.1", port_);
  20008. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20009. ASSERT_TRUE(handle.is_valid());
  20010. EXPECT_EQ("Hello World!", read_all(handle));
  20011. }
  20012. TEST_F(OpenStreamTest, SmallBuffer) {
  20013. Client cli("127.0.0.1", port_);
  20014. auto handle = cli.open_stream("GET", "/hello");
  20015. std::string result;
  20016. char buf[4];
  20017. ssize_t n;
  20018. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20019. result.append(buf, static_cast<size_t>(n));
  20020. EXPECT_EQ("Hello World!", result);
  20021. }
  20022. TEST_F(OpenStreamTest, DefaultHeaders) {
  20023. Client cli("127.0.0.1", port_);
  20024. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20025. {
  20026. auto handle = cli.open_stream("GET", "/echo-headers");
  20027. ASSERT_TRUE(handle.is_valid());
  20028. auto body = read_all(handle);
  20029. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20030. std::string::npos);
  20031. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20032. std::string::npos);
  20033. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20034. }
  20035. // open_stream POST with body and no explicit content_type should NOT add
  20036. // text/plain Content-Type (behavior differs from non-streaming path), but
  20037. // should include Content-Length
  20038. {
  20039. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20040. ASSERT_TRUE(handle.is_valid());
  20041. auto body = read_all(handle);
  20042. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20043. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20044. }
  20045. // open_stream POST with explicit Content-Type should preserve it
  20046. {
  20047. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20048. {{"Content-Type", "application/custom"}},
  20049. "{}", "application/custom");
  20050. ASSERT_TRUE(handle.is_valid());
  20051. auto body = read_all(handle);
  20052. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20053. }
  20054. // User-specified User-Agent must not be overwritten for stream API
  20055. {
  20056. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20057. {{"User-Agent", "MyAgent/1.2"}});
  20058. ASSERT_TRUE(handle.is_valid());
  20059. auto body = read_all(handle);
  20060. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20061. }
  20062. }
  20063. TEST_F(OpenStreamTest, Large) {
  20064. Client cli("127.0.0.1", port_);
  20065. auto handle = cli.open_stream("GET", "/large");
  20066. EXPECT_EQ(10000u, read_all(handle).size());
  20067. }
  20068. TEST_F(OpenStreamTest, ConnectionError) {
  20069. Client cli("127.0.0.1", 9999);
  20070. auto handle = cli.open_stream("GET", "/hello");
  20071. EXPECT_FALSE(handle.is_valid());
  20072. }
  20073. TEST_F(OpenStreamTest, Chunked) {
  20074. Client cli("127.0.0.1", port_);
  20075. auto handle = cli.open_stream("GET", "/chunked");
  20076. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20077. "Transfer-Encoding") == "chunked");
  20078. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20079. }
  20080. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20081. Client cli("127.0.0.1", port_);
  20082. auto handle =
  20083. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20084. ASSERT_TRUE(handle.is_valid());
  20085. // Consume body to allow trailers to be received/parsed
  20086. auto body = read_all(handle);
  20087. // Explicitly parse trailers (ensure trailers are available for assertion)
  20088. handle.parse_trailers_if_needed();
  20089. EXPECT_EQ(std::string("123456789"), body);
  20090. // The response should include a Trailer header declaring both names
  20091. ASSERT_TRUE(handle.response);
  20092. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20093. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20094. handle.response->get_header_value("Trailer"));
  20095. // Prohibited trailer must not be present
  20096. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20097. // Allowed trailer should be present
  20098. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20099. EXPECT_EQ(std::string("yes"),
  20100. handle.response->get_trailer_value("X-Allowed"));
  20101. // Verify trailers are NOT present as regular headers
  20102. EXPECT_EQ(std::string(""),
  20103. handle.response->get_header_value("Content-Length"));
  20104. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20105. }
  20106. // Accepts one connection on an OS-assigned port, which it hands over through
  20107. // port_promise, reads the request head and sends back response. after_send,
  20108. // if given, runs on the connection before it is closed.
  20109. static std::thread
  20110. serve_single_response(std::promise<int> &port_promise,
  20111. const std::string &response,
  20112. std::function<void(socket_t)> after_send = nullptr) {
  20113. return std::thread([&port_promise, response, after_send] {
  20114. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20115. default_socket_options(srv);
  20116. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20117. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20118. sockaddr_in addr{};
  20119. addr.sin_family = AF_INET;
  20120. addr.sin_port = htons(0); // Let OS assign a free port
  20121. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20122. int opt = 1;
  20123. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20124. #ifdef _WIN32
  20125. reinterpret_cast<const char *>(&opt),
  20126. #else
  20127. &opt,
  20128. #endif
  20129. sizeof(opt));
  20130. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20131. ::listen(srv, 1) != 0) {
  20132. port_promise.set_value(-1);
  20133. detail::close_socket(srv);
  20134. return;
  20135. }
  20136. socklen_t addr_len = sizeof(addr);
  20137. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20138. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20139. sockaddr_in cli_addr{};
  20140. socklen_t cli_len = sizeof(cli_addr);
  20141. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20142. if (cli != INVALID_SOCKET) {
  20143. // Read the complete HTTP request (until the blank line that terminates
  20144. // headers) before sending the response. If the server closes the socket
  20145. // while the client's request data is still unread in the kernel receive
  20146. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20147. // connection on both sides: it discards the client's receive buffer
  20148. // (which already holds our response) and causes any in-progress write on
  20149. // the client to fail with ECONNRESET. Reading all request data first
  20150. // ensures close() emits a graceful FIN.
  20151. {
  20152. char rbuf[256];
  20153. std::string req;
  20154. while (req.find("\r\n\r\n") == std::string::npos) {
  20155. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20156. if (n <= 0) { break; }
  20157. req.append(rbuf, static_cast<size_t>(n));
  20158. }
  20159. }
  20160. ::send(cli,
  20161. #ifdef _WIN32
  20162. static_cast<const char *>(response.c_str()),
  20163. static_cast<int>(response.size()),
  20164. #else
  20165. response.c_str(), response.size(),
  20166. #endif
  20167. 0);
  20168. if (after_send) { after_send(cli); }
  20169. detail::close_socket(cli);
  20170. }
  20171. detail::close_socket(srv);
  20172. });
  20173. }
  20174. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20175. #ifndef _WIN32
  20176. signal(SIGPIPE, SIG_IGN);
  20177. #endif
  20178. std::promise<int> port_promise;
  20179. auto port_future = port_promise.get_future();
  20180. auto server_thread =
  20181. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20182. "Content-Type: text/plain\r\n"
  20183. "Content-Length: not-a-number\r\n"
  20184. "Connection: close\r\n"
  20185. "\r\n"
  20186. "hello");
  20187. auto port = port_future.get();
  20188. ASSERT_GT(port, 0);
  20189. Client cli("127.0.0.1", port);
  20190. auto handle = cli.open_stream("GET", "/");
  20191. EXPECT_FALSE(handle.is_valid());
  20192. server_thread.join();
  20193. }
  20194. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20195. #ifndef _WIN32
  20196. signal(SIGPIPE, SIG_IGN);
  20197. #endif
  20198. std::promise<int> port_promise;
  20199. auto port_future = port_promise.get_future();
  20200. auto server_thread = serve_single_response(
  20201. port_promise, "HTTP/1.1 200 OK\r\n"
  20202. "Content-Type: text/plain\r\n"
  20203. "Content-Length: 99999999999999999999999999\r\n"
  20204. "Connection: close\r\n"
  20205. "\r\n"
  20206. "hello");
  20207. auto port = port_future.get();
  20208. ASSERT_GT(port, 0);
  20209. // Historically std::stoull would throw std::out_of_range here and crash
  20210. // the process, then parsing silently clamped to a bogus framing length and
  20211. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20212. // so the stream fails to open, matching the not-a-number case above. The
  20213. // process still must NOT terminate.
  20214. Client cli("127.0.0.1", port);
  20215. auto handle = cli.open_stream("GET", "/");
  20216. EXPECT_FALSE(handle.is_valid());
  20217. server_thread.join();
  20218. }
  20219. #ifndef _WIN32
  20220. // As above for the body of a streamed request: a send() cut short by the write
  20221. // timeout must not leave the rest of the body unsent.
  20222. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20223. signal(SIGPIPE, SIG_IGN);
  20224. Server svr;
  20225. svr.set_socket_options([](socket_t sock) {
  20226. int size = 8192;
  20227. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20228. reinterpret_cast<const char *>(&size), sizeof(size));
  20229. });
  20230. svr.Post("/size", [](const Request &, Response &res,
  20231. const ContentReader &content_reader) {
  20232. // Outlast the client's write timeout before reading the body.
  20233. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20234. size_t received = 0;
  20235. content_reader([&](const char *, size_t len) {
  20236. received += len;
  20237. return true;
  20238. });
  20239. res.set_content(std::to_string(received), "text/plain");
  20240. });
  20241. auto port = svr.bind_to_any_port(HOST);
  20242. std::thread t([&]() { svr.listen_after_bind(); });
  20243. auto se = detail::scope_exit([&] {
  20244. svr.stop();
  20245. t.join();
  20246. });
  20247. svr.wait_until_ready();
  20248. Client cli(HOST, port);
  20249. cli.set_write_timeout(0, 500000);
  20250. cli.set_socket_options([](socket_t sock) {
  20251. int size = 8192;
  20252. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20253. reinterpret_cast<const char *>(&size), sizeof(size));
  20254. });
  20255. const std::string body(4 * 1024 * 1024, 'A');
  20256. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20257. "application/octet-stream");
  20258. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20259. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20260. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20261. }
  20262. #endif
  20263. // Serves `response` to the single request `fn` makes with a fresh client.
  20264. template <typename Fn>
  20265. static void with_single_response(const std::string &response, Fn fn) {
  20266. #ifndef _WIN32
  20267. signal(SIGPIPE, SIG_IGN);
  20268. #endif
  20269. std::promise<int> port_promise;
  20270. auto port_future = port_promise.get_future();
  20271. auto server_thread = serve_single_response(port_promise, response);
  20272. auto se = detail::scope_exit([&] { server_thread.join(); });
  20273. auto port = port_future.get();
  20274. ASSERT_GT(port, 0);
  20275. Client cli("127.0.0.1", port);
  20276. fn(cli);
  20277. }
  20278. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20279. // too, also in a build without the decoder for the advertised coding.
  20280. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20281. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20282. const auto response = "HTTP/1.1 200 OK\r\n"
  20283. "Content-Encoding: gzip\r\n"
  20284. "Content-Length: " +
  20285. std::to_string(gzipped.size()) +
  20286. "\r\n"
  20287. "Connection: close\r\n\r\n" +
  20288. gzipped;
  20289. with_single_response(response, [&](Client &cli) {
  20290. cli.set_decompress(false);
  20291. auto handle = cli.open_stream("GET", "/");
  20292. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20293. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20294. EXPECT_EQ(gzipped, read_all(handle));
  20295. EXPECT_FALSE(handle.has_read_error());
  20296. });
  20297. with_single_response(response, [&](Client &cli) {
  20298. cli.set_decompress(false);
  20299. auto res = stream::Get(cli, "/", 7);
  20300. ASSERT_TRUE(res) << to_string(res.error());
  20301. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20302. EXPECT_EQ(gzipped, res.read_all());
  20303. EXPECT_FALSE(res.has_read_error());
  20304. });
  20305. }
  20306. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20307. // Neither Content-Length nor chunked: the body ends at the close
  20308. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20309. "Connection: close\r\n"
  20310. "\r\n"
  20311. "hello";
  20312. with_single_response(close_delimited, [](Client &cli) {
  20313. auto handle = cli.open_stream("GET", "/");
  20314. ASSERT_TRUE(handle.is_valid());
  20315. EXPECT_EQ("hello", read_all(handle));
  20316. EXPECT_FALSE(handle.has_read_error());
  20317. });
  20318. // A close before the end of the Content-Length is still an error
  20319. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20320. "Content-Length: 10\r\n"
  20321. "\r\n"
  20322. "hello";
  20323. with_single_response(short_content_length, [](Client &cli) {
  20324. auto handle = cli.open_stream("GET", "/");
  20325. ASSERT_TRUE(handle.is_valid());
  20326. read_all(handle);
  20327. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20328. });
  20329. // So is a close before the last chunk
  20330. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20331. "Transfer-Encoding: chunked\r\n"
  20332. "\r\n"
  20333. "5\r\nhello\r\n";
  20334. with_single_response(short_chunked, [](Client &cli) {
  20335. auto handle = cli.open_stream("GET", "/");
  20336. ASSERT_TRUE(handle.is_valid());
  20337. read_all(handle);
  20338. EXPECT_TRUE(handle.has_read_error());
  20339. });
  20340. }
  20341. #ifdef CPPHTTPLIB_SSL_ENABLED
  20342. // Serves `response` to one request, then closes with or without a close_notify
  20343. template <typename Fn>
  20344. static void with_single_tls_response(const std::string &response,
  20345. bool close_notify, Fn fn) {
  20346. #ifndef _WIN32
  20347. signal(SIGPIPE, SIG_IGN);
  20348. #endif
  20349. std::promise<int> port_promise;
  20350. auto port_future = port_promise.get_future();
  20351. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20352. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20353. default_socket_options(srv);
  20354. sockaddr_in addr{};
  20355. addr.sin_family = AF_INET;
  20356. addr.sin_port = htons(0);
  20357. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20358. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20359. ::listen(srv, 1) != 0) {
  20360. port_promise.set_value(-1);
  20361. detail::close_socket(srv);
  20362. return;
  20363. }
  20364. socklen_t addr_len = sizeof(addr);
  20365. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20366. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20367. auto cli = ::accept(srv, nullptr, nullptr);
  20368. if (cli != INVALID_SOCKET) {
  20369. auto ctx = tls::create_server_context();
  20370. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20371. nullptr);
  20372. auto session = tls::create_session(ctx, cli);
  20373. tls::TlsError err;
  20374. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20375. // The request head first, so that closing the socket sends a FIN
  20376. // rather than an RST for the unread bytes.
  20377. std::string req;
  20378. char buf[256];
  20379. while (req.find("\r\n\r\n") == std::string::npos) {
  20380. auto n = tls::read(session, buf, sizeof(buf), err);
  20381. if (n <= 0) { break; }
  20382. req.append(buf, static_cast<size_t>(n));
  20383. }
  20384. size_t sent = 0;
  20385. while (sent < response.size()) {
  20386. auto n = tls::write(session, response.data() + sent,
  20387. response.size() - sent, err);
  20388. if (n <= 0) { break; }
  20389. sent += static_cast<size_t>(n);
  20390. }
  20391. if (close_notify) { tls::shutdown(session, true); }
  20392. }
  20393. tls::free_session(session);
  20394. detail::close_socket(cli);
  20395. tls::free_context(ctx);
  20396. }
  20397. detail::close_socket(srv);
  20398. });
  20399. auto se = detail::scope_exit([&] { server_thread.join(); });
  20400. auto port = port_future.get();
  20401. ASSERT_GT(port, 0);
  20402. SSLClient cli("127.0.0.1", port);
  20403. cli.enable_server_certificate_verification(false);
  20404. fn(cli);
  20405. }
  20406. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20407. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20408. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20409. "Connection: close\r\n"
  20410. "\r\n"
  20411. "hello";
  20412. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20413. auto res = cli.Get("/");
  20414. ASSERT_TRUE(res) << to_string(res.error());
  20415. EXPECT_EQ("hello", res->body);
  20416. });
  20417. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20418. auto res = cli.Get("/");
  20419. ASSERT_FALSE(res);
  20420. EXPECT_EQ(Error::Read, res.error());
  20421. });
  20422. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20423. auto handle = cli.open_stream("GET", "/");
  20424. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20425. read_all(handle);
  20426. EXPECT_TRUE(handle.has_read_error());
  20427. });
  20428. // A framed body ends where its framing says, with or without the alert
  20429. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20430. "Content-Length: 5\r\n"
  20431. "Connection: close\r\n"
  20432. "\r\n"
  20433. "hello";
  20434. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20435. auto res = cli.Get("/");
  20436. ASSERT_TRUE(res) << to_string(res.error());
  20437. EXPECT_EQ("hello", res->body);
  20438. });
  20439. }
  20440. #endif
  20441. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20442. const char *responses[] = {
  20443. "HTTP/1.1 103 Early Hints\r\n"
  20444. "Link: </style.css>; rel=preload\r\n"
  20445. "\r\n"
  20446. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20447. "HTTP/1.1 100 Continue\r\n"
  20448. "X-Note: interim\r\n"
  20449. "\r\n"
  20450. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20451. };
  20452. for (auto response : responses) {
  20453. with_single_response(response, [](Client &cli) {
  20454. auto res = cli.Get("/");
  20455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20456. EXPECT_EQ(StatusCode::OK_200, res->status);
  20457. EXPECT_EQ("ok", res->body);
  20458. });
  20459. }
  20460. }
  20461. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20462. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20463. const std::string final_response =
  20464. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20465. std::string interims;
  20466. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20467. interims += interim;
  20468. }
  20469. with_single_response(interims + final_response, [](Client &cli) {
  20470. auto res = cli.Get("/");
  20471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20472. EXPECT_EQ("ok", res->body);
  20473. });
  20474. with_single_response(interims + interim + final_response, [](Client &cli) {
  20475. auto res = cli.Get("/");
  20476. ASSERT_FALSE(res);
  20477. EXPECT_EQ(Error::Read, res.error());
  20478. });
  20479. }
  20480. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20481. #ifndef _WIN32
  20482. signal(SIGPIPE, SIG_IGN);
  20483. #endif
  20484. // The server answers the head without asking for the body. Bytes it then
  20485. // reads on the connection would be taken for the body the request declared.
  20486. auto closed_by_client = false;
  20487. std::promise<int> port_promise;
  20488. auto server_thread = serve_single_response(
  20489. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20490. [&](socket_t sock) {
  20491. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20492. char buf[256];
  20493. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20494. });
  20495. Client cli("127.0.0.1", port_promise.get_future().get());
  20496. cli.set_keep_alive(true);
  20497. cli.set_read_timeout(1, 0);
  20498. // Long enough for the client to send Expect: 100-continue.
  20499. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20501. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20502. cli.Get("/second");
  20503. server_thread.join();
  20504. EXPECT_TRUE(closed_by_client);
  20505. }
  20506. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20507. // Long enough for the client to send Expect: 100-continue
  20508. with_single_response(
  20509. "HTTP/1.1 103 Early Hints\r\n"
  20510. "Link: </style.css>; rel=preload\r\n"
  20511. "\r\n"
  20512. "HTTP/1.1 401 Unauthorized\r\n"
  20513. "Content-Length: 0\r\n\r\n",
  20514. [](Client &cli) {
  20515. cli.set_read_timeout(2, 0);
  20516. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20518. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20519. });
  20520. }
  20521. #ifdef CPPHTTPLIB_SSL_ENABLED
  20522. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20523. #ifndef _WIN32
  20524. signal(SIGPIPE, SIG_IGN);
  20525. #endif
  20526. auto reused = false;
  20527. std::promise<int> port_promise;
  20528. auto server_thread = serve_single_response(
  20529. port_promise,
  20530. "HTTP/1.1 401 Unauthorized\r\n"
  20531. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20532. "Content-Length: 0\r\n\r\n",
  20533. [&](socket_t sock) {
  20534. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20535. char buf[256];
  20536. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20537. });
  20538. Client cli("127.0.0.1", port_promise.get_future().get());
  20539. cli.set_keep_alive(true);
  20540. cli.set_digest_auth("user", "pass");
  20541. cli.set_read_timeout(1, 0);
  20542. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20543. server_thread.join();
  20544. EXPECT_FALSE(reused);
  20545. }
  20546. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20547. // Any other answer to CONNECT would read as the origin's response.
  20548. struct {
  20549. const char *response;
  20550. bool passed_on;
  20551. } cases[] = {
  20552. {"HTTP/1.1 201 Created\r\n"
  20553. "Set-Cookie: session=from-proxy\r\n"
  20554. "Content-Length: 0\r\n\r\n",
  20555. false},
  20556. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20557. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20558. "Content-Length: 0\r\n\r\n",
  20559. true},
  20560. };
  20561. for (const auto &c : cases) {
  20562. std::promise<int> port_promise;
  20563. auto server_thread = serve_single_response(port_promise, c.response);
  20564. SSLClient cli("example.com", 443);
  20565. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20566. auto res = cli.Get("/");
  20567. server_thread.join();
  20568. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20569. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20570. if (res) {
  20571. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20572. }
  20573. }
  20574. }
  20575. #endif
  20576. // Records the client's error logger calls as "error METHOD path", or
  20577. // "error null" for a call without a request
  20578. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20579. return [&log](const Error &err, const Request *req) {
  20580. log.push_back(to_string(err) + " " +
  20581. (req ? req->method + " " + req->path : "null"));
  20582. };
  20583. }
  20584. // A failed request is reported once, with the request the caller made
  20585. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20586. Server svr;
  20587. svr.Get("/big", [](const Request &, Response &res) {
  20588. res.set_content(std::string(100000, 'b'), "text/plain");
  20589. });
  20590. auto port = svr.bind_to_any_port(HOST);
  20591. std::thread t([&]() { svr.listen_after_bind(); });
  20592. auto se = detail::scope_exit([&] {
  20593. svr.stop();
  20594. t.join();
  20595. });
  20596. svr.wait_until_ready();
  20597. Client cli(HOST, port);
  20598. std::vector<std::string> log;
  20599. cli.set_error_logger(record_errors(log));
  20600. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20601. cli.Get("/big", [](const char *, size_t) { return false; });
  20602. EXPECT_EQ(expected, log);
  20603. log.clear();
  20604. cli.Get("/big", [](size_t, size_t) { return false; });
  20605. EXPECT_EQ(expected, log);
  20606. }
  20607. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20608. // Fails while the body is read
  20609. auto broken = [](const Request &, Response &res) {
  20610. res.set_content_provider(10, "text/plain",
  20611. [](size_t, size_t, DataSink &) { return false; });
  20612. };
  20613. Server other;
  20614. other.Get("/broken", broken);
  20615. auto other_port = other.bind_to_any_port(HOST);
  20616. std::thread other_t([&]() { other.listen_after_bind(); });
  20617. auto other_se = detail::scope_exit([&] {
  20618. other.stop();
  20619. other_t.join();
  20620. });
  20621. other.wait_until_ready();
  20622. Server svr;
  20623. svr.Get("/broken", broken);
  20624. svr.Get("/same-origin",
  20625. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20626. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20627. res.set_redirect("http://" + std::string(HOST) + ":" +
  20628. std::to_string(other_port) + "/broken");
  20629. });
  20630. auto port = svr.bind_to_any_port(HOST);
  20631. std::thread t([&]() { svr.listen_after_bind(); });
  20632. auto se = detail::scope_exit([&] {
  20633. svr.stop();
  20634. t.join();
  20635. });
  20636. svr.wait_until_ready();
  20637. Client cli(HOST, port);
  20638. cli.set_follow_location(true);
  20639. std::vector<std::string> log;
  20640. cli.set_error_logger(record_errors(log));
  20641. for (auto path : {"/same-origin", "/cross-origin"}) {
  20642. log.clear();
  20643. auto res = cli.Get(path);
  20644. ASSERT_FALSE(res);
  20645. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20646. log);
  20647. }
  20648. }
  20649. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20650. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20651. std::vector<std::string> log;
  20652. cli.set_error_logger(record_errors(log));
  20653. auto handle = cli.open_stream("GET", "/x");
  20654. EXPECT_FALSE(handle.is_valid());
  20655. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20656. log);
  20657. });
  20658. }
  20659. #ifdef CPPHTTPLIB_SSL_ENABLED
  20660. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20661. // Not a TLS server, so the handshake fails. It waits for a request line in
  20662. // the handshake bytes, so a short read timeout lets it close quickly.
  20663. Server svr;
  20664. svr.set_read_timeout(0, 100000);
  20665. svr.Get("/x", [](const Request &, Response &res) {
  20666. res.set_content("x", "text/plain");
  20667. });
  20668. auto port = svr.bind_to_any_port(HOST);
  20669. std::thread t([&]() { svr.listen_after_bind(); });
  20670. auto se = detail::scope_exit([&] {
  20671. svr.stop();
  20672. t.join();
  20673. });
  20674. svr.wait_until_ready();
  20675. std::vector<std::string> log;
  20676. SSLClient cli(HOST, port);
  20677. cli.enable_server_certificate_verification(false);
  20678. cli.set_error_logger(record_errors(log));
  20679. auto res = cli.Get("/x");
  20680. ASSERT_FALSE(res);
  20681. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20682. log.clear();
  20683. auto handle = cli.open_stream("GET", "/x");
  20684. EXPECT_FALSE(handle.is_valid());
  20685. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20686. log.clear();
  20687. SSLClient no_ca(HOST, port);
  20688. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20689. no_ca.set_error_logger(record_errors(log));
  20690. res = no_ca.Get("/x");
  20691. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20692. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20693. }
  20694. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20695. #ifndef _WIN32
  20696. signal(SIGPIPE, SIG_IGN);
  20697. #endif
  20698. // Refused, answered with a challenge, or closed without an answer
  20699. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20700. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20701. "Content-Length: 0\r\n\r\n",
  20702. ""}) {
  20703. std::promise<int> port_promise;
  20704. auto server_thread = serve_single_response(port_promise, response);
  20705. SSLClient cli("example.com", 443);
  20706. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20707. std::vector<std::string> log;
  20708. cli.set_error_logger(record_errors(log));
  20709. auto res = cli.Get("/");
  20710. server_thread.join();
  20711. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20712. << response;
  20713. }
  20714. }
  20715. #endif
  20716. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20717. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20718. // the chunked coding and drop Content-Length, so a front-end that trusts
  20719. // Content-Length would disagree about where the body ends (response
  20720. // smuggling). The client must reject such a response.
  20721. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20722. for (const char *te : {"chunked", "gzip, chunked"}) {
  20723. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20724. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20725. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20726. "5\r\nhello\r\n0\r\n\r\n";
  20727. with_single_response(response, [&](Client &cli) {
  20728. auto res = cli.Get("/");
  20729. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20730. EXPECT_EQ(Error::Read, res.error()) << te;
  20731. });
  20732. with_single_response(response, [&](Client &cli) {
  20733. auto handle = cli.open_stream("GET", "/");
  20734. EXPECT_FALSE(handle.is_valid()) << te;
  20735. EXPECT_EQ(Error::Read, handle.error) << te;
  20736. });
  20737. }
  20738. }
  20739. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20740. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20741. // closing the connection (unlike a request, which must be rejected).
  20742. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20743. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20744. "Transfer-Encoding: chunked\r\n"
  20745. "Connection: close\r\n"
  20746. "\r\n"
  20747. "5\r\nhello\r\n0\r\n\r\n",
  20748. "HTTP/1.1 200 OK\r\n"
  20749. "Transfer-Encoding: gzip\r\n"
  20750. "Connection: close\r\n"
  20751. "\r\n"
  20752. "hello"}) {
  20753. with_single_response(response, [&](Client &cli) {
  20754. auto res = cli.Get("/");
  20755. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20756. EXPECT_EQ("hello", res->body);
  20757. });
  20758. with_single_response(response, [&](Client &cli) {
  20759. auto handle = cli.open_stream("GET", "/");
  20760. ASSERT_TRUE(handle.is_valid()) << response;
  20761. EXPECT_EQ("hello", read_all(handle));
  20762. });
  20763. }
  20764. }
  20765. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20766. // framing headers describe nothing to read and must not be rejected.
  20767. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20768. const std::string framing = "Content-Length: 5\r\n"
  20769. "Transfer-Encoding: chunked\r\n"
  20770. "Connection: close\r\n"
  20771. "\r\n";
  20772. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20773. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20774. });
  20775. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20776. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20777. });
  20778. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20779. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20780. with_single_response(response, [&](Client &cli) {
  20781. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20782. });
  20783. with_single_response(response, [&](Client &cli) {
  20784. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20785. });
  20786. }
  20787. }
  20788. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20789. // header section, so a stream opened on one has nothing to read, whatever
  20790. // framing or coding headers it carries.
  20791. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20792. struct Case {
  20793. const char *method;
  20794. const char *status;
  20795. };
  20796. // A reader of the declared body reports an early close when nothing
  20797. // follows, and hands back what does.
  20798. struct Framing {
  20799. const char *headers;
  20800. const char *after;
  20801. };
  20802. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20803. Case{"GET", "304 Not Modified"}}) {
  20804. for (const auto &f :
  20805. {Framing{"Content-Length: 5\r\n", ""},
  20806. Framing{"Content-Length: 5\r\n", "hello"},
  20807. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20808. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20809. // Not decoded, so a build without Brotli opens it too
  20810. Framing{"Content-Encoding: br\r\n", ""}}) {
  20811. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20812. "Connection: close\r\n"
  20813. "\r\n" +
  20814. f.after;
  20815. with_single_response(response, [&](Client &cli) {
  20816. auto handle = cli.open_stream(c.method, "/");
  20817. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20818. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20819. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20820. });
  20821. }
  20822. }
  20823. }
  20824. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20825. // response, is faulty framing, so the connection is not reused after it.
  20826. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20827. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20828. "Content-Length: 0\r\n"
  20829. "Transfer-Encoding: chunked\r\n"
  20830. "\r\n"
  20831. "5\r\nhello\r\n0\r\n\r\n",
  20832. "HTTP/1.0 200 Connection established\r\n"
  20833. "Connection: keep-alive\r\n"
  20834. "Transfer-Encoding: chunked\r\n"
  20835. "\r\n"
  20836. "5\r\nhello\r\n0\r\n\r\n"}) {
  20837. with_single_response(response, [&](Client &cli) {
  20838. cli.set_keep_alive(true);
  20839. auto res = cli.Get("/");
  20840. ASSERT_TRUE(res) << response;
  20841. EXPECT_EQ("hello", res->body);
  20842. EXPECT_FALSE(cli.is_socket_open()) << response;
  20843. });
  20844. }
  20845. }
  20846. // A payload max length of 0 means no limit, however the body is framed.
  20847. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20848. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20849. "Transfer-Encoding: chunked\r\n"
  20850. "\r\n"
  20851. "5\r\nhello\r\n0\r\n\r\n",
  20852. "HTTP/1.1 200 OK\r\n"
  20853. "Connection: close\r\n"
  20854. "\r\n"
  20855. "hello"}) {
  20856. with_single_response(response, [&](Client &cli) {
  20857. cli.set_payload_max_length(0);
  20858. auto res = cli.Get("/");
  20859. ASSERT_TRUE(res) << response;
  20860. EXPECT_EQ("hello", res->body) << response;
  20861. });
  20862. }
  20863. }
  20864. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20865. Server svr;
  20866. svr.set_payload_max_length(0);
  20867. svr.Post("/echo", [](const Request &req, Response &res) {
  20868. res.set_content(req.body, "text/plain");
  20869. });
  20870. auto port = svr.bind_to_any_port(HOST);
  20871. thread t = thread([&] { svr.listen_after_bind(); });
  20872. auto se = detail::scope_exit([&] {
  20873. svr.stop();
  20874. t.join();
  20875. ASSERT_FALSE(svr.is_running());
  20876. });
  20877. svr.wait_until_ready();
  20878. Client cli(HOST, port);
  20879. auto res = cli.Post(
  20880. "/echo",
  20881. [](size_t /*offset*/, DataSink &sink) {
  20882. sink.write("hello", 5);
  20883. sink.done();
  20884. return true;
  20885. },
  20886. "text/plain");
  20887. ASSERT_TRUE(res);
  20888. EXPECT_EQ(StatusCode::OK_200, res->status);
  20889. EXPECT_EQ("hello", res->body);
  20890. }
  20891. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20892. TEST_F(OpenStreamTest, Gzip) {
  20893. Client cli("127.0.0.1", port_);
  20894. auto handle = cli.open_stream("GET", "/compressible", {},
  20895. {{"Accept-Encoding", "gzip"}});
  20896. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20897. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20898. }
  20899. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20900. Client cli("127.0.0.1", port_);
  20901. auto handle =
  20902. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20903. {{"Accept-Encoding", "gzip"}});
  20904. ASSERT_TRUE(handle.is_valid());
  20905. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20906. EXPECT_EQ("123456789", read_all(handle));
  20907. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20908. }
  20909. #endif
  20910. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20911. TEST_F(OpenStreamTest, Brotli) {
  20912. Client cli("127.0.0.1", port_);
  20913. auto handle =
  20914. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20915. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20916. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20917. }
  20918. #endif
  20919. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20920. TEST_F(OpenStreamTest, Zstd) {
  20921. Client cli("127.0.0.1", port_);
  20922. auto handle = cli.open_stream("GET", "/compressible", {},
  20923. {{"Accept-Encoding", "zstd"}});
  20924. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20925. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20926. }
  20927. #endif
  20928. #ifdef CPPHTTPLIB_SSL_ENABLED
  20929. class SSLOpenStreamTest : public ::testing::Test {
  20930. protected:
  20931. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20932. void SetUp() override {
  20933. svr_.Get("/hello", [](const Request &, Response &res) {
  20934. res.set_content("Hello SSL World!", "text/plain");
  20935. });
  20936. svr_.Get("/chunked", [](const Request &, Response &res) {
  20937. res.set_chunked_content_provider("text/plain",
  20938. [](size_t offset, DataSink &sink) {
  20939. if (offset < 15) {
  20940. sink.write("chunk", 5);
  20941. return true;
  20942. }
  20943. sink.done();
  20944. return true;
  20945. });
  20946. });
  20947. svr_.Post("/echo", [](const Request &req, Response &res) {
  20948. res.set_content(req.body, req.get_header_value("Content-Type"));
  20949. });
  20950. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20951. std::string body = req.body;
  20952. res.set_chunked_content_provider(
  20953. "text/plain", [body](size_t offset, DataSink &sink) {
  20954. if (offset < body.size()) {
  20955. sink.write(body.data() + offset, body.size() - offset);
  20956. }
  20957. sink.done();
  20958. return true;
  20959. });
  20960. });
  20961. port_ = svr_.bind_to_any_port("127.0.0.1");
  20962. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20963. svr_.wait_until_ready();
  20964. }
  20965. void TearDown() override {
  20966. svr_.stop();
  20967. if (thread_.joinable()) thread_.join();
  20968. }
  20969. SSLServer svr_;
  20970. std::thread thread_;
  20971. int port_ = 0;
  20972. };
  20973. TEST_F(SSLOpenStreamTest, Basic) {
  20974. SSLClient cli("127.0.0.1", port_);
  20975. cli.enable_server_certificate_verification(false);
  20976. auto handle = cli.open_stream("GET", "/hello");
  20977. ASSERT_TRUE(handle.is_valid());
  20978. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20979. }
  20980. TEST_F(SSLOpenStreamTest, Chunked) {
  20981. SSLClient cli("127.0.0.1", port_);
  20982. cli.enable_server_certificate_verification(false);
  20983. auto handle = cli.open_stream("GET", "/chunked");
  20984. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20985. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20986. "Transfer-Encoding") == "chunked");
  20987. auto body = read_all(handle);
  20988. EXPECT_EQ("chunkchunkchunk", body);
  20989. }
  20990. TEST_F(SSLOpenStreamTest, Post) {
  20991. SSLClient cli("127.0.0.1", port_);
  20992. cli.enable_server_certificate_verification(false);
  20993. auto handle =
  20994. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20995. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20996. EXPECT_EQ(200, handle.response->status);
  20997. auto body = read_all(handle);
  20998. EXPECT_EQ("Hello SSL POST", body);
  20999. }
  21000. TEST_F(SSLOpenStreamTest, PostChunked) {
  21001. SSLClient cli("127.0.0.1", port_);
  21002. cli.enable_server_certificate_verification(false);
  21003. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21004. "Chunked SSL Data", "text/plain");
  21005. ASSERT_TRUE(handle.is_valid());
  21006. EXPECT_EQ(200, handle.response->status);
  21007. auto body = read_all(handle);
  21008. EXPECT_EQ("Chunked SSL Data", body);
  21009. }
  21010. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21011. // Content-Length is terminated by the server closing the connection. When the
  21012. // SSL peer sends a close_notify after the body, the client must treat it as a
  21013. // clean EOF and return a successful response rather than an error.
  21014. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21015. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21016. ASSERT_TRUE(svr.is_valid());
  21017. svr.set_keep_alive_max_count(1);
  21018. const std::string expected_body = "Hello from connection-close response!";
  21019. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21020. res.set_content_provider("text/plain",
  21021. [&](size_t offset, DataSink &sink) -> bool {
  21022. if (offset < expected_body.size()) {
  21023. sink.write(expected_body.data() + offset,
  21024. expected_body.size() - offset);
  21025. }
  21026. sink.done();
  21027. return true;
  21028. });
  21029. });
  21030. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21031. auto se = detail::scope_exit([&] {
  21032. svr.stop();
  21033. listen_thread.join();
  21034. ASSERT_FALSE(svr.is_running());
  21035. });
  21036. svr.wait_until_ready();
  21037. SSLClient cli(HOST, PORT);
  21038. cli.enable_server_certificate_verification(false);
  21039. auto res = cli.Get("/no-content-length");
  21040. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21041. EXPECT_EQ(StatusCode::OK_200, res->status);
  21042. EXPECT_EQ(expected_body, res->body);
  21043. }
  21044. #endif // CPPHTTPLIB_SSL_ENABLED
  21045. //==============================================================================
  21046. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21047. // results for various scenarios.
  21048. //==============================================================================
  21049. TEST(ParityTest, GetVsOpenStream) {
  21050. Server svr;
  21051. const std::string path = "/parity";
  21052. const std::string content = "Parity test content: hello world";
  21053. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21054. res.set_content(content, "text/plain");
  21055. });
  21056. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21057. auto se = detail::scope_exit([&] {
  21058. svr.stop();
  21059. t.join();
  21060. ASSERT_FALSE(svr.is_running());
  21061. });
  21062. svr.wait_until_ready();
  21063. Client cli(HOST, PORT);
  21064. // Non-stream path
  21065. auto r1 = cli.Get(path);
  21066. ASSERT_TRUE(r1);
  21067. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21068. // Stream path
  21069. auto h = cli.open_stream("GET", path);
  21070. ASSERT_TRUE(h.is_valid());
  21071. EXPECT_EQ(r1->body, read_all(h));
  21072. }
  21073. // Helper to compress data with provided compressor type T
  21074. template <typename Compressor>
  21075. static std::string compress_payload_for_parity(const std::string &in) {
  21076. std::string out;
  21077. Compressor compressor;
  21078. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21079. [&](const char *data, size_t n) {
  21080. out.append(data, n);
  21081. return true;
  21082. });
  21083. EXPECT_TRUE(ok);
  21084. return out;
  21085. }
  21086. // Helper function for compression parity tests
  21087. template <typename Compressor>
  21088. static void test_compression_parity(const std::string &original,
  21089. const std::string &path,
  21090. const std::string &encoding) {
  21091. const std::string compressed =
  21092. compress_payload_for_parity<Compressor>(original);
  21093. Server svr;
  21094. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21095. res.set_content(compressed, "application/octet-stream");
  21096. res.set_header("Content-Encoding", encoding);
  21097. });
  21098. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21099. auto se = detail::scope_exit([&] {
  21100. svr.stop();
  21101. t.join();
  21102. ASSERT_FALSE(svr.is_running());
  21103. });
  21104. svr.wait_until_ready();
  21105. Client cli(HOST, PORT);
  21106. // Non-streaming
  21107. {
  21108. auto res = cli.Get(path);
  21109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21110. EXPECT_EQ(StatusCode::OK_200, res->status);
  21111. EXPECT_EQ(original, res->body);
  21112. }
  21113. // Streaming
  21114. {
  21115. auto h = cli.open_stream("GET", path);
  21116. ASSERT_TRUE(h.is_valid());
  21117. EXPECT_EQ(original, read_all(h));
  21118. }
  21119. }
  21120. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21121. TEST(ParityTest, Gzip) {
  21122. test_compression_parity<detail::gzip_compressor>(
  21123. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21124. }
  21125. #endif
  21126. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21127. TEST(ParityTest, Brotli) {
  21128. test_compression_parity<detail::brotli_compressor>(
  21129. "Hello, brotli parity test payload", "/parity-br", "br");
  21130. }
  21131. #endif
  21132. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21133. TEST(ParityTest, Zstd) {
  21134. test_compression_parity<detail::zstd_compressor>(
  21135. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21136. }
  21137. #endif
  21138. //==============================================================================
  21139. // New Stream API Tests
  21140. //==============================================================================
  21141. inline std::string read_body(httplib::stream::Result &result) {
  21142. std::string body;
  21143. while (result.next()) {
  21144. body.append(result.data(), result.size());
  21145. }
  21146. return body;
  21147. }
  21148. TEST(ClientConnectionTest, Basic) {
  21149. httplib::ClientConnection conn;
  21150. EXPECT_FALSE(conn.is_open());
  21151. conn.sock = 1;
  21152. EXPECT_TRUE(conn.is_open());
  21153. httplib::ClientConnection conn2(std::move(conn));
  21154. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21155. conn2.sock = INVALID_SOCKET;
  21156. }
  21157. // Unified test server for all stream::* tests
  21158. class StreamApiTest : public ::testing::Test {
  21159. protected:
  21160. void SetUp() override {
  21161. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21162. res.set_content("Hello World!", "text/plain");
  21163. });
  21164. svr_.Get("/echo-params",
  21165. [](const httplib::Request &req, httplib::Response &res) {
  21166. std::string r;
  21167. for (const auto &p : req.params) {
  21168. if (!r.empty()) r += "&";
  21169. r += p.first + "=" + p.second;
  21170. }
  21171. res.set_content(r, "text/plain");
  21172. });
  21173. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21174. res.set_content(req.body, req.get_header_value("Content-Type"));
  21175. });
  21176. svr_.Post("/echo-headers",
  21177. [](const httplib::Request &req, httplib::Response &res) {
  21178. std::string r;
  21179. for (const auto &h : req.headers)
  21180. r += h.first + ": " + h.second + "\n";
  21181. res.set_content(r, "text/plain");
  21182. });
  21183. svr_.Post("/echo-params",
  21184. [](const httplib::Request &req, httplib::Response &res) {
  21185. std::string r = "params:";
  21186. for (const auto &p : req.params)
  21187. r += p.first + "=" + p.second + ";";
  21188. res.set_content(r + " body:" + req.body, "text/plain");
  21189. });
  21190. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21191. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21192. });
  21193. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21194. res.set_content("PUT:" + req.body, "text/plain");
  21195. });
  21196. svr_.Patch("/echo",
  21197. [](const httplib::Request &req, httplib::Response &res) {
  21198. res.set_content("PATCH:" + req.body, "text/plain");
  21199. });
  21200. svr_.Delete(
  21201. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21202. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21203. "text/plain");
  21204. });
  21205. svr_.Get("/head-test",
  21206. [](const httplib::Request &, httplib::Response &res) {
  21207. res.set_content("body for HEAD", "text/plain");
  21208. });
  21209. svr_.Options("/options",
  21210. [](const httplib::Request &, httplib::Response &res) {
  21211. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21212. });
  21213. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21214. svr_.wait_until_ready();
  21215. }
  21216. void TearDown() override {
  21217. svr_.stop();
  21218. if (thread_.joinable()) thread_.join();
  21219. }
  21220. httplib::Server svr_;
  21221. std::thread thread_;
  21222. };
  21223. // stream::Get tests
  21224. TEST_F(StreamApiTest, GetBasic) {
  21225. httplib::Client cli(HOST, PORT);
  21226. auto result = httplib::stream::Get(cli, "/hello");
  21227. ASSERT_TRUE(result.is_valid());
  21228. EXPECT_EQ(200, result.status());
  21229. EXPECT_EQ("Hello World!", read_body(result));
  21230. }
  21231. TEST_F(StreamApiTest, GetWithParams) {
  21232. httplib::Client cli(HOST, PORT);
  21233. httplib::Params params{{"foo", "bar"}};
  21234. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21235. ASSERT_TRUE(result.is_valid());
  21236. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21237. }
  21238. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21239. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21240. httplib::Client cli(HOST, PORT);
  21241. cli.set_payload_max_length(0);
  21242. auto result = httplib::stream::Get(cli, "/hello");
  21243. ASSERT_TRUE(result.is_valid());
  21244. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21245. EXPECT_EQ("Hello World!", read_body(result));
  21246. }
  21247. #endif
  21248. TEST_F(StreamApiTest, GetConnectionError) {
  21249. httplib::Client cli(HOST, 9999);
  21250. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21251. }
  21252. TEST_F(StreamApiTest, Get404) {
  21253. httplib::Client cli(HOST, PORT);
  21254. auto result = httplib::stream::Get(cli, "/nonexistent");
  21255. EXPECT_TRUE(result.is_valid());
  21256. EXPECT_EQ(404, result.status());
  21257. }
  21258. // stream::Post tests
  21259. TEST_F(StreamApiTest, PostBasic) {
  21260. httplib::Client cli(HOST, PORT);
  21261. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21262. "application/json");
  21263. ASSERT_TRUE(result.is_valid());
  21264. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21265. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21266. }
  21267. TEST_F(StreamApiTest, PostWithHeaders) {
  21268. httplib::Client cli(HOST, PORT);
  21269. httplib::Headers headers{{"X-Custom", "value"}};
  21270. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21271. "text/plain");
  21272. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21273. }
  21274. TEST_F(StreamApiTest, PostWithParams) {
  21275. httplib::Client cli(HOST, PORT);
  21276. httplib::Params params{{"k", "v"}};
  21277. auto result =
  21278. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21279. auto body = read_body(result);
  21280. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21281. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21282. }
  21283. TEST_F(StreamApiTest, PostLarge) {
  21284. httplib::Client cli(HOST, PORT);
  21285. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21286. size_t total = 0;
  21287. while (result.next()) {
  21288. total += result.size();
  21289. }
  21290. EXPECT_EQ(100u * 1024u, total);
  21291. }
  21292. // stream::Put/Patch tests
  21293. TEST_F(StreamApiTest, PutAndPatch) {
  21294. httplib::Client cli(HOST, PORT);
  21295. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21296. EXPECT_EQ("PUT:test", read_body(put));
  21297. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21298. EXPECT_EQ("PATCH:test", read_body(patch));
  21299. }
  21300. // stream::Delete tests
  21301. TEST_F(StreamApiTest, Delete) {
  21302. httplib::Client cli(HOST, PORT);
  21303. auto del1 = httplib::stream::Delete(cli, "/resource");
  21304. EXPECT_EQ("Deleted", read_body(del1));
  21305. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21306. EXPECT_EQ("Deleted:data", read_body(del2));
  21307. }
  21308. // stream::Head/Options tests
  21309. TEST_F(StreamApiTest, HeadAndOptions) {
  21310. httplib::Client cli(HOST, PORT);
  21311. auto head = httplib::stream::Head(cli, "/head-test");
  21312. EXPECT_TRUE(head.is_valid());
  21313. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21314. auto opts = httplib::stream::Options(cli, "/options");
  21315. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21316. }
  21317. // SSL stream::* tests
  21318. #ifdef CPPHTTPLIB_SSL_ENABLED
  21319. class SSLStreamApiTest : public ::testing::Test {
  21320. protected:
  21321. void SetUp() override {
  21322. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21323. res.set_content("Hello SSL!", "text/plain");
  21324. });
  21325. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21326. res.set_content(req.body, "text/plain");
  21327. });
  21328. port_ = svr_.bind_to_any_port("127.0.0.1");
  21329. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21330. svr_.wait_until_ready();
  21331. }
  21332. void TearDown() override {
  21333. svr_.stop();
  21334. if (thread_.joinable()) thread_.join();
  21335. }
  21336. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21337. std::thread thread_;
  21338. int port_ = 0;
  21339. };
  21340. TEST_F(SSLStreamApiTest, GetAndPost) {
  21341. httplib::SSLClient cli("127.0.0.1", port_);
  21342. cli.enable_server_certificate_verification(false);
  21343. auto get = httplib::stream::Get(cli, "/hello");
  21344. EXPECT_EQ("Hello SSL!", read_body(get));
  21345. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21346. EXPECT_EQ("test", read_body(post));
  21347. }
  21348. #endif
  21349. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21350. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21351. // BodyReader
  21352. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21353. // Test that read timeout during streaming is detected
  21354. // Use a large content-length response where server delays mid-stream
  21355. Server svr;
  21356. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21357. // Send a large response with delay in the middle
  21358. res.set_content_provider(
  21359. 1000, // content_length
  21360. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21361. if (offset < 100) {
  21362. // Send first 100 bytes immediately
  21363. std::string data(100, 'A');
  21364. sink.write(data.c_str(), data.size());
  21365. return true;
  21366. }
  21367. // Then delay longer than client timeout
  21368. std::this_thread::sleep_for(std::chrono::seconds(3));
  21369. std::string data(900, 'B');
  21370. sink.write(data.c_str(), data.size());
  21371. return true;
  21372. });
  21373. });
  21374. auto port = 8091;
  21375. std::thread t([&]() { svr.listen("localhost", port); });
  21376. svr.wait_until_ready();
  21377. Client cli("localhost", port);
  21378. cli.set_read_timeout(1, 0); // 1 second timeout
  21379. auto handle = cli.open_stream("GET", "/slow-stream");
  21380. ASSERT_TRUE(handle.is_valid());
  21381. char buf[256];
  21382. ssize_t total = 0;
  21383. ssize_t n;
  21384. bool got_error = false;
  21385. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21386. total += n;
  21387. }
  21388. if (n < 0) {
  21389. got_error = true;
  21390. // Should be timeout or read error
  21391. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21392. handle.get_read_error() == Error::Read)
  21393. << "Actual error: " << to_string(handle.get_read_error());
  21394. }
  21395. // Either we got an error, or we got less data than expected
  21396. EXPECT_TRUE(got_error || total < 1000)
  21397. << "Expected timeout but got all " << total << " bytes";
  21398. svr.stop();
  21399. t.join();
  21400. }
  21401. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21402. // Test connection closed detection via BodyReader
  21403. Server svr;
  21404. std::atomic<bool> close_now{false};
  21405. svr.Get("/will-close", [&](const Request &, Response &res) {
  21406. res.set_content_provider(
  21407. 10000, // Large content_length that we won't fully send
  21408. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21409. if (offset < 100) {
  21410. std::string data(100, 'X');
  21411. sink.write(data.c_str(), data.size());
  21412. return true;
  21413. }
  21414. // Wait for signal then abort
  21415. while (!close_now) {
  21416. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21417. }
  21418. return false; // Abort - server will close connection
  21419. });
  21420. });
  21421. auto port = 8092;
  21422. std::thread t([&]() { svr.listen("localhost", port); });
  21423. svr.wait_until_ready();
  21424. Client cli("localhost", port);
  21425. auto handle = cli.open_stream("GET", "/will-close");
  21426. ASSERT_TRUE(handle.is_valid());
  21427. char buf[256];
  21428. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21429. EXPECT_GT(n, 0) << "First read should succeed";
  21430. // Signal server to close
  21431. close_now = true;
  21432. // Keep reading until error or EOF
  21433. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21434. // Keep reading
  21435. }
  21436. // Should get an error since content_length wasn't satisfied
  21437. if (n < 0) {
  21438. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21439. handle.get_read_error() == Error::Read)
  21440. << "Actual error: " << to_string(handle.get_read_error());
  21441. }
  21442. svr.stop();
  21443. t.join();
  21444. }
  21445. #ifdef CPPHTTPLIB_SSL_ENABLED
  21446. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21447. // Test that read timeout during SSL streaming is detected
  21448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21449. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21450. res.set_content_provider(
  21451. 1000, "text/plain",
  21452. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21453. if (offset < 100) {
  21454. std::string data(100, 'A');
  21455. sink.write(data.c_str(), data.size());
  21456. return true;
  21457. }
  21458. std::this_thread::sleep_for(std::chrono::seconds(3));
  21459. std::string data(900, 'B');
  21460. sink.write(data.c_str(), data.size());
  21461. return true;
  21462. });
  21463. });
  21464. auto port = 8093;
  21465. std::thread t([&]() { svr.listen("localhost", port); });
  21466. svr.wait_until_ready();
  21467. SSLClient cli("localhost", port);
  21468. cli.enable_server_certificate_verification(false);
  21469. cli.set_read_timeout(1, 0); // 1 second timeout
  21470. auto handle = cli.open_stream("GET", "/slow-stream");
  21471. ASSERT_TRUE(handle.is_valid());
  21472. char buf[256];
  21473. ssize_t total = 0;
  21474. ssize_t n;
  21475. bool got_error = false;
  21476. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21477. total += n;
  21478. }
  21479. if (n < 0) {
  21480. got_error = true;
  21481. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21482. handle.get_read_error() == Error::Read)
  21483. << "Actual error: " << to_string(handle.get_read_error());
  21484. }
  21485. EXPECT_TRUE(got_error || total < 1000)
  21486. << "Expected timeout but got all " << total << " bytes";
  21487. svr.stop();
  21488. t.join();
  21489. }
  21490. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21491. // Test SSL connection closed detection
  21492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21493. std::atomic<bool> close_now{false};
  21494. svr.Get("/will-close", [&](const Request &, Response &res) {
  21495. res.set_content_provider(
  21496. 10000, "text/plain",
  21497. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21498. if (offset < 100) {
  21499. std::string data(100, 'X');
  21500. sink.write(data.c_str(), data.size());
  21501. return true;
  21502. }
  21503. while (!close_now) {
  21504. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21505. }
  21506. return false;
  21507. });
  21508. });
  21509. auto port = 8094;
  21510. std::thread t([&]() { svr.listen("localhost", port); });
  21511. svr.wait_until_ready();
  21512. SSLClient cli("localhost", port);
  21513. cli.enable_server_certificate_verification(false);
  21514. auto handle = cli.open_stream("GET", "/will-close");
  21515. ASSERT_TRUE(handle.is_valid());
  21516. char buf[256];
  21517. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21518. EXPECT_GT(n, 0);
  21519. // Signal server to close
  21520. close_now = true;
  21521. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21522. // Keep reading
  21523. }
  21524. if (n < 0) {
  21525. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21526. handle.get_read_error() == Error::Read)
  21527. << "Actual error: " << to_string(handle.get_read_error());
  21528. }
  21529. svr.stop();
  21530. t.join();
  21531. }
  21532. #endif
  21533. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21534. using namespace httplib;
  21535. // Create a test file
  21536. const char *fname = "etag_testfile.txt";
  21537. const char *content = "etag-content";
  21538. {
  21539. std::ofstream ofs(fname);
  21540. ofs << content;
  21541. ASSERT_TRUE(ofs.good());
  21542. }
  21543. Server svr;
  21544. svr.set_mount_point("/static", ".");
  21545. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21546. svr.wait_until_ready();
  21547. Client cli(HOST, PORT);
  21548. // First request: should get 200 with ETag header
  21549. auto res1 = cli.Get("/static/etag_testfile.txt");
  21550. ASSERT_TRUE(res1);
  21551. ASSERT_EQ(200, res1->status);
  21552. ASSERT_TRUE(res1->has_header("ETag"));
  21553. std::string etag = res1->get_header_value("ETag");
  21554. EXPECT_FALSE(etag.empty());
  21555. // Verify ETag format: W/"hex-hex"
  21556. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21557. EXPECT_EQ('W', etag[0]);
  21558. EXPECT_EQ('/', etag[1]);
  21559. EXPECT_EQ('"', etag[2]);
  21560. EXPECT_EQ('"', etag.back());
  21561. // Exact match: expect 304 Not Modified
  21562. Headers h2 = {{"If-None-Match", etag}};
  21563. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21564. ASSERT_TRUE(res2);
  21565. EXPECT_EQ(304, res2->status);
  21566. // Wildcard match: expect 304 Not Modified
  21567. Headers h3 = {{"If-None-Match", "*"}};
  21568. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21569. ASSERT_TRUE(res3);
  21570. EXPECT_EQ(304, res3->status);
  21571. // Non-matching ETag: expect 200
  21572. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21573. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21574. ASSERT_TRUE(res4);
  21575. EXPECT_EQ(200, res4->status);
  21576. // Multiple ETags with one matching: expect 304
  21577. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21578. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21579. ASSERT_TRUE(res5);
  21580. EXPECT_EQ(304, res5->status);
  21581. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21582. // that equivalent to the single comma-separated list above, so the match on
  21583. // the second line must still be found.
  21584. Headers h6;
  21585. h6.emplace("If-None-Match", "W/\"other\"");
  21586. h6.emplace("If-None-Match", etag);
  21587. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21588. ASSERT_TRUE(res6);
  21589. EXPECT_EQ(304, res6->status);
  21590. svr.stop();
  21591. t.join();
  21592. std::remove(fname);
  21593. }
  21594. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21595. using namespace httplib;
  21596. Server svr;
  21597. svr.set_mount_point("/static", ".");
  21598. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21599. svr.wait_until_ready();
  21600. Client cli(HOST, PORT);
  21601. // Send If-None-Match: * to a non-existent file
  21602. Headers h = {{"If-None-Match", "*"}};
  21603. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21605. EXPECT_EQ(404, res->status);
  21606. svr.stop();
  21607. t.join();
  21608. }
  21609. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21610. using namespace httplib;
  21611. // Create a test file
  21612. const char *fname = "etag_boundary_testfile.txt";
  21613. const char *content = "boundary-test";
  21614. {
  21615. std::ofstream ofs(fname);
  21616. ofs << content;
  21617. ASSERT_TRUE(ofs.good());
  21618. }
  21619. Server svr;
  21620. svr.set_mount_point("/static", ".");
  21621. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21622. svr.wait_until_ready();
  21623. Client cli(HOST, PORT);
  21624. // Get the actual ETag
  21625. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21626. ASSERT_TRUE(res1);
  21627. ASSERT_EQ(200, res1->status);
  21628. ASSERT_TRUE(res1->has_header("ETag"));
  21629. std::string etag = res1->get_header_value("ETag");
  21630. // Test 1: Very long ETag value (longer than actual ETag)
  21631. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21632. Headers h1 = {{"If-None-Match", "W/"
  21633. "\"very-long-etag-value-that-is-much-longer-"
  21634. "than-the-actual-etag-value\""}};
  21635. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21636. ASSERT_TRUE(res2);
  21637. EXPECT_EQ(200, res2->status); // Should not match
  21638. // Test 2: Long string followed by wildcard
  21639. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21640. // string)
  21641. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21642. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21643. ASSERT_TRUE(res3);
  21644. EXPECT_EQ(304, res3->status); // Should match on "*"
  21645. // Test 3: Wildcard followed by long string
  21646. // Should match on "*" immediately and return 304
  21647. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21648. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21649. ASSERT_TRUE(res4);
  21650. EXPECT_EQ(304, res4->status); // Should match on "*"
  21651. // Test 4: Multiple long non-matching values
  21652. // Should NOT match and return 200 (test that all comparisons are safe)
  21653. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21654. "W/\"second-long-non-matching-value\", "
  21655. "W/\"third-long-non-matching-value\""}};
  21656. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21657. ASSERT_TRUE(res5);
  21658. EXPECT_EQ(200, res5->status); // Should not match
  21659. // Test 5: Single character that is not "*" (edge case)
  21660. Headers h5 = {{"If-None-Match", "X"}};
  21661. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21662. ASSERT_TRUE(res6);
  21663. EXPECT_EQ(200, res6->status); // Should not match
  21664. svr.stop();
  21665. t.join();
  21666. std::remove(fname);
  21667. }
  21668. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21669. using namespace httplib;
  21670. // Create a test file
  21671. const char *fname = "ims_testfile.txt";
  21672. const char *content = "if-modified-since-test";
  21673. {
  21674. std::ofstream ofs(fname);
  21675. ofs << content;
  21676. ASSERT_TRUE(ofs.good());
  21677. }
  21678. Server svr;
  21679. svr.set_mount_point("/static", ".");
  21680. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21681. svr.wait_until_ready();
  21682. Client cli(HOST, PORT);
  21683. // First request: should get 200 with Last-Modified header
  21684. auto res1 = cli.Get("/static/ims_testfile.txt");
  21685. ASSERT_TRUE(res1);
  21686. ASSERT_EQ(200, res1->status);
  21687. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21688. std::string last_modified = res1->get_header_value("Last-Modified");
  21689. EXPECT_FALSE(last_modified.empty());
  21690. // If-Modified-Since with same time: expect 304
  21691. Headers h2 = {{"If-Modified-Since", last_modified}};
  21692. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21693. ASSERT_TRUE(res2);
  21694. EXPECT_EQ(304, res2->status);
  21695. // If-Modified-Since with future time: expect 304
  21696. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21697. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21698. ASSERT_TRUE(res3);
  21699. EXPECT_EQ(304, res3->status);
  21700. // If-Modified-Since with past time: expect 200
  21701. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21702. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21703. ASSERT_TRUE(res4);
  21704. EXPECT_EQ(200, res4->status);
  21705. // If-None-Match takes precedence over If-Modified-Since
  21706. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21707. ASSERT_TRUE(res1->has_header("ETag"));
  21708. std::string etag = res1->get_header_value("ETag");
  21709. Headers h5 = {{"If-None-Match", etag},
  21710. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21711. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21712. ASSERT_TRUE(res5);
  21713. EXPECT_EQ(304, res5->status);
  21714. svr.stop();
  21715. t.join();
  21716. std::remove(fname);
  21717. }
  21718. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21719. using namespace httplib;
  21720. Server svr;
  21721. // Endpoint that returns compressible content
  21722. svr.Get("/compressible", [](const Request &, Response &res) {
  21723. // Return a large enough body to trigger compression
  21724. std::string body(1000, 'a');
  21725. res.set_content(body, "text/plain");
  21726. });
  21727. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21728. svr.wait_until_ready();
  21729. Client cli(HOST, PORT);
  21730. // Request with gzip support: should get Vary header when compressed
  21731. cli.set_compress(true);
  21732. auto res1 = cli.Get("/compressible");
  21733. ASSERT_TRUE(res1);
  21734. EXPECT_EQ(200, res1->status);
  21735. // If Content-Encoding is set, Vary should also be set
  21736. if (res1->has_header("Content-Encoding")) {
  21737. EXPECT_TRUE(res1->has_header("Vary"));
  21738. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21739. }
  21740. // Request without Accept-Encoding header: should not have compression
  21741. Headers h_no_compress;
  21742. auto res2 = cli.Get("/compressible", h_no_compress);
  21743. ASSERT_TRUE(res2);
  21744. EXPECT_EQ(200, res2->status);
  21745. // Verify Vary header is present when compression is applied
  21746. // (the exact behavior depends on server configuration)
  21747. svr.stop();
  21748. t.join();
  21749. }
  21750. TEST(ETagTest, IfRangeWithETag) {
  21751. using namespace httplib;
  21752. // Create a test file with known content
  21753. const char *fname = "if_range_testfile.txt";
  21754. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21755. {
  21756. std::ofstream ofs(fname);
  21757. ofs << content;
  21758. ASSERT_TRUE(ofs.good());
  21759. }
  21760. Server svr;
  21761. svr.set_mount_point("/static", ".");
  21762. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21763. svr.wait_until_ready();
  21764. Client cli(HOST, PORT);
  21765. // First request: get ETag
  21766. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21767. ASSERT_TRUE(res1);
  21768. ASSERT_EQ(200, res1->status);
  21769. ASSERT_TRUE(res1->has_header("ETag"));
  21770. std::string etag = res1->get_header_value("ETag");
  21771. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21772. // Since our server generates weak ETags (W/"..."), If-Range with our
  21773. // ETag should NOT result in partial content - it should return full content.
  21774. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21775. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21776. ASSERT_TRUE(res2);
  21777. // Weak ETag in If-Range -> full content (200), not partial (206)
  21778. EXPECT_EQ(200, res2->status);
  21779. EXPECT_EQ(content, res2->body);
  21780. EXPECT_FALSE(res2->has_header("Content-Range"));
  21781. // Range request with non-matching If-Range (ETag): should get 200 (full
  21782. // content)
  21783. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21784. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21785. ASSERT_TRUE(res3);
  21786. EXPECT_EQ(200, res3->status);
  21787. EXPECT_EQ(content, res3->body);
  21788. EXPECT_FALSE(res3->has_header("Content-Range"));
  21789. // Range request with strong ETag (hypothetical - our server doesn't generate
  21790. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21791. // should return full content)
  21792. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21793. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21794. ASSERT_TRUE(res4);
  21795. EXPECT_EQ(200, res4->status);
  21796. EXPECT_EQ(content, res4->body);
  21797. EXPECT_FALSE(res4->has_header("Content-Range"));
  21798. svr.stop();
  21799. t.join();
  21800. std::remove(fname);
  21801. }
  21802. TEST(ETagTest, IfRangeWithDate) {
  21803. using namespace httplib;
  21804. // Create a test file
  21805. const char *fname = "if_range_date_testfile.txt";
  21806. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21807. {
  21808. std::ofstream ofs(fname);
  21809. ofs << content;
  21810. ASSERT_TRUE(ofs.good());
  21811. }
  21812. Server svr;
  21813. svr.set_mount_point("/static", ".");
  21814. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21815. svr.wait_until_ready();
  21816. Client cli(HOST, PORT);
  21817. // First request: get Last-Modified
  21818. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21819. ASSERT_TRUE(res1);
  21820. ASSERT_EQ(200, res1->status);
  21821. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21822. std::string last_modified = res1->get_header_value("Last-Modified");
  21823. // Range request with matching If-Range (date): should get 206
  21824. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21825. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21826. ASSERT_TRUE(res2);
  21827. EXPECT_EQ(206, res2->status);
  21828. EXPECT_EQ("FGHIJ", res2->body);
  21829. // Range request with old If-Range date: should get 200 (full content)
  21830. Headers h3 = {{"Range", "bytes=5-9"},
  21831. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21832. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21833. ASSERT_TRUE(res3);
  21834. EXPECT_EQ(200, res3->status);
  21835. EXPECT_EQ(content, res3->body);
  21836. // Range request with future If-Range date: should get 206
  21837. Headers h4 = {{"Range", "bytes=0-4"},
  21838. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21839. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21840. ASSERT_TRUE(res4);
  21841. EXPECT_EQ(206, res4->status);
  21842. EXPECT_EQ("ABCDE", res4->body);
  21843. svr.stop();
  21844. t.join();
  21845. std::remove(fname);
  21846. }
  21847. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21848. using namespace httplib;
  21849. const char *fname = "etag_malformed.txt";
  21850. const char *content = "malformed-etag";
  21851. {
  21852. std::ofstream ofs(fname);
  21853. ofs << content;
  21854. ASSERT_TRUE(ofs.good());
  21855. }
  21856. Server svr;
  21857. svr.set_mount_point("/static", ".");
  21858. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21859. svr.wait_until_ready();
  21860. Client cli(HOST, PORT);
  21861. // baseline: should get 200 and an ETag
  21862. auto res1 = cli.Get("/static/etag_malformed.txt");
  21863. ASSERT_TRUE(res1);
  21864. ASSERT_EQ(200, res1->status);
  21865. ASSERT_TRUE(res1->has_header("ETag"));
  21866. // Malformed ETag value (missing quotes) should be treated as non-matching
  21867. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21868. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21869. ASSERT_TRUE(res_bad);
  21870. EXPECT_EQ(200, res_bad->status);
  21871. // Whitespace-only header value should be considered invalid / non-matching
  21872. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21873. "Host: localhost\r\n"
  21874. "If-None-Match: \r\n"
  21875. "Connection: close\r\n"
  21876. "\r\n";
  21877. std::string out;
  21878. ASSERT_TRUE(send_request(5, raw_req, &out));
  21879. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21880. svr.stop();
  21881. t.join();
  21882. std::remove(fname);
  21883. }
  21884. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21885. using namespace httplib;
  21886. const char *fname = "ims_invalid_format.txt";
  21887. const char *content = "ims-bad-format";
  21888. {
  21889. std::ofstream ofs(fname);
  21890. ofs << content;
  21891. ASSERT_TRUE(ofs.good());
  21892. }
  21893. Server svr;
  21894. svr.set_mount_point("/static", ".");
  21895. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21896. svr.wait_until_ready();
  21897. Client cli(HOST, PORT);
  21898. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21899. ASSERT_TRUE(res1);
  21900. ASSERT_EQ(200, res1->status);
  21901. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21902. // If-Modified-Since with invalid format should not result in 304
  21903. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21904. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21905. ASSERT_TRUE(res_bad);
  21906. EXPECT_EQ(200, res_bad->status);
  21907. // If-Range with invalid date format should be treated as mismatch -> full
  21908. // content (200)
  21909. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21910. {"If-Range", "invalid-date"}};
  21911. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21912. ASSERT_TRUE(res_ifrange);
  21913. EXPECT_EQ(200, res_ifrange->status);
  21914. svr.stop();
  21915. t.join();
  21916. std::remove(fname);
  21917. }
  21918. TEST(ETagTest, IfRangeWithMalformedETag) {
  21919. using namespace httplib;
  21920. const char *fname = "ifrange_malformed.txt";
  21921. const std::string content = "0123456789";
  21922. {
  21923. std::ofstream ofs(fname);
  21924. ofs << content;
  21925. ASSERT_TRUE(ofs.good());
  21926. }
  21927. Server svr;
  21928. svr.set_mount_point("/static", ".");
  21929. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21930. svr.wait_until_ready();
  21931. Client cli(HOST, PORT);
  21932. // First request: get ETag
  21933. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21934. ASSERT_TRUE(res1);
  21935. ASSERT_EQ(200, res1->status);
  21936. ASSERT_TRUE(res1->has_header("ETag"));
  21937. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21938. // full content (200)
  21939. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21940. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21941. ASSERT_TRUE(res2);
  21942. EXPECT_EQ(200, res2->status);
  21943. EXPECT_EQ(content, res2->body);
  21944. svr.stop();
  21945. t.join();
  21946. std::remove(fname);
  21947. }
  21948. TEST(ETagTest, ExtremeLargeDateValues) {
  21949. using namespace httplib;
  21950. const char *fname = "ims_extreme_date.txt";
  21951. const char *content = "ims-extreme-date";
  21952. {
  21953. std::ofstream ofs(fname);
  21954. ofs << content;
  21955. ASSERT_TRUE(ofs.good());
  21956. }
  21957. Server svr;
  21958. svr.set_mount_point("/static", ".");
  21959. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21960. svr.wait_until_ready();
  21961. Client cli(HOST, PORT);
  21962. auto res1 = cli.Get(std::string("/static/") + fname);
  21963. ASSERT_TRUE(res1);
  21964. ASSERT_EQ(200, res1->status);
  21965. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21966. // Extremely large year that may overflow date parsing routines.
  21967. Headers h_large_date = {
  21968. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21969. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21970. ASSERT_TRUE(res_bad);
  21971. // Expect server to treat this as invalid/mismatch and return full content
  21972. EXPECT_EQ(200, res_bad->status);
  21973. // If-Range with extremely large date should be treated as mismatch -> full
  21974. // content (200)
  21975. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21976. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21977. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21978. ASSERT_TRUE(res_ifrange);
  21979. EXPECT_EQ(200, res_ifrange->status);
  21980. svr.stop();
  21981. t.join();
  21982. std::remove(fname);
  21983. }
  21984. TEST(ETagTest, NegativeFileModificationTime) {
  21985. using namespace httplib;
  21986. const char *fname = "ims_negative_mtime.txt";
  21987. const std::string content = "negative-mtime";
  21988. {
  21989. std::ofstream ofs(fname);
  21990. ofs << content;
  21991. ASSERT_TRUE(ofs.good());
  21992. }
  21993. // Try to set file mtime to a negative value. This may fail on some
  21994. // platforms/filesystems; if it fails, the test will still verify server
  21995. // behaves safely by performing a regular conditional request.
  21996. #if defined(__APPLE__) || defined(__linux__)
  21997. bool set_negative = false;
  21998. do {
  21999. struct timeval times[2];
  22000. // access time: now
  22001. times[0].tv_sec = time(nullptr);
  22002. times[0].tv_usec = 0;
  22003. // modification time: negative (e.g., -1)
  22004. times[1].tv_sec = -1;
  22005. times[1].tv_usec = 0;
  22006. if (utimes(fname, times) == 0) { set_negative = true; }
  22007. } while (0);
  22008. #else
  22009. bool set_negative = false;
  22010. #endif
  22011. Server svr;
  22012. svr.set_mount_point("/static", ".");
  22013. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22014. svr.wait_until_ready();
  22015. Client cli(HOST, PORT);
  22016. auto res1 = cli.Get(std::string("/static/") + fname);
  22017. ASSERT_TRUE(res1);
  22018. ASSERT_EQ(200, res1->status);
  22019. bool has_last_modified = res1->has_header("Last-Modified");
  22020. std::string last_modified;
  22021. if (has_last_modified) {
  22022. last_modified = res1->get_header_value("Last-Modified");
  22023. }
  22024. if (set_negative) {
  22025. // If we successfully set a negative mtime, ensure server returns a
  22026. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22027. // with an old date and ensure server handles it without crash.
  22028. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22029. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22030. ASSERT_TRUE(res2);
  22031. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22032. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22033. } else {
  22034. // Could not set negative mtime on this platform; fall back to verifying
  22035. // that normal invalid/malformed dates are treated safely (non-304).
  22036. Headers h_bad_date = {
  22037. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22038. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22039. ASSERT_TRUE(res_bad);
  22040. EXPECT_EQ(200, res_bad->status);
  22041. }
  22042. svr.stop();
  22043. t.join();
  22044. std::remove(fname);
  22045. }
  22046. //==============================================================================
  22047. // Integration Tests with Server
  22048. //==============================================================================
  22049. class SSEIntegrationTest : public ::testing::Test {
  22050. protected:
  22051. void SetUp() override {
  22052. stop_server_.store(false);
  22053. events_.clear();
  22054. server_ = httplib::detail::make_unique<Server>();
  22055. setup_server();
  22056. start_server();
  22057. }
  22058. void TearDown() override {
  22059. stop_server_.store(true);
  22060. event_cv_.notify_all();
  22061. server_->stop();
  22062. if (server_thread_.joinable()) { server_thread_.join(); }
  22063. }
  22064. void setup_server() {
  22065. // Simple SSE endpoint
  22066. server_->Get("/events", [this](const Request &req, Response &res) {
  22067. auto last_id = req.get_header_value("Last-Event-ID");
  22068. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22069. res.set_chunked_content_provider(
  22070. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22071. std::unique_lock<std::mutex> lock(event_mutex_);
  22072. if (event_cv_.wait_for(
  22073. lock, std::chrono::milliseconds(200), [this] {
  22074. return !events_.empty() || stop_server_.load();
  22075. })) {
  22076. if (stop_server_.load()) { return false; }
  22077. if (!events_.empty()) {
  22078. std::string event = events_.front();
  22079. events_.erase(events_.begin());
  22080. sink.write(event.data(), event.size());
  22081. return true;
  22082. }
  22083. }
  22084. return !stop_server_.load();
  22085. });
  22086. });
  22087. // Endpoint that returns error
  22088. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22089. res.status = 500;
  22090. res.set_content("Internal Server Error", "text/plain");
  22091. });
  22092. // Endpoint for custom event types
  22093. server_->Get("/custom-events", [](const Request &, Response &res) {
  22094. res.set_chunked_content_provider(
  22095. "text/event-stream", [](size_t offset, DataSink &sink) {
  22096. if (offset == 0) {
  22097. std::string event = "event: update\ndata: updated\n\n"
  22098. "event: delete\ndata: deleted\n\n";
  22099. sink.write(event.data(), event.size());
  22100. }
  22101. return false; // End stream after sending
  22102. });
  22103. });
  22104. }
  22105. void start_server() {
  22106. port_ = server_->bind_to_any_port(HOST);
  22107. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22108. // Wait for server to start
  22109. while (!server_->is_running()) {
  22110. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22111. }
  22112. }
  22113. int get_port() const { return port_; }
  22114. void send_event(const std::string &event) {
  22115. std::lock_guard<std::mutex> lock(event_mutex_);
  22116. events_.push_back(event);
  22117. event_cv_.notify_all();
  22118. }
  22119. std::unique_ptr<Server> server_;
  22120. std::thread server_thread_;
  22121. std::mutex event_mutex_;
  22122. std::condition_variable event_cv_;
  22123. std::vector<std::string> events_;
  22124. std::atomic<bool> stop_server_{false};
  22125. std::string last_received_event_id_;
  22126. int port_ = 0;
  22127. };
  22128. //==============================================================================
  22129. // SSE Parsing Tests
  22130. //==============================================================================
  22131. class SSEParsingTest : public SSEIntegrationTest {
  22132. protected:
  22133. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22134. // A trailing sentinel event tells when the whole stream has been parsed.
  22135. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22136. auto body = stream + "event: end\ndata: end\n\n";
  22137. server_->Get("/parse", [body](const Request &, Response &res) {
  22138. res.set_content(body, "text/event-stream");
  22139. });
  22140. return collect("/parse");
  22141. }
  22142. // Runs SSEClient against path until an "end" event arrives and returns the
  22143. // messages dispatched before it
  22144. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22145. Client client(HOST, get_port());
  22146. sse::SSEClient sse(client, path);
  22147. std::mutex mutex;
  22148. std::condition_variable cv;
  22149. std::vector<sse::SSEMessage> messages;
  22150. auto done = false;
  22151. sse.on_message([&](const sse::SSEMessage &msg) {
  22152. std::lock_guard<std::mutex> lock(mutex);
  22153. // Ignore a replay from a reconnect that races with stop()
  22154. if (!done) { messages.push_back(msg); }
  22155. });
  22156. sse.on_event("end", [&](const sse::SSEMessage &) {
  22157. std::lock_guard<std::mutex> lock(mutex);
  22158. done = true;
  22159. cv.notify_all();
  22160. });
  22161. sse.set_reconnect_interval(100);
  22162. sse.start_async();
  22163. {
  22164. std::unique_lock<std::mutex> lock(mutex);
  22165. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22166. }
  22167. sse.stop();
  22168. EXPECT_TRUE(done);
  22169. return messages;
  22170. }
  22171. };
  22172. TEST_F(SSEParsingTest, SingleLineData) {
  22173. auto msgs = parse("data: hello\n\n");
  22174. ASSERT_EQ(msgs.size(), 1u);
  22175. EXPECT_EQ(msgs[0].data, "hello");
  22176. EXPECT_EQ(msgs[0].event, "message");
  22177. }
  22178. TEST_F(SSEParsingTest, MultiLineData) {
  22179. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22180. ASSERT_EQ(msgs.size(), 1u);
  22181. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22182. }
  22183. TEST_F(SSEParsingTest, CustomEventType) {
  22184. auto msgs = parse("event: update\ndata: payload\n\n");
  22185. ASSERT_EQ(msgs.size(), 1u);
  22186. EXPECT_EQ(msgs[0].event, "update");
  22187. EXPECT_EQ(msgs[0].data, "payload");
  22188. }
  22189. TEST_F(SSEParsingTest, EventIdHandling) {
  22190. auto msgs = parse("id: 12345\ndata: test\n\n");
  22191. ASSERT_EQ(msgs.size(), 1u);
  22192. EXPECT_EQ(msgs[0].id, "12345");
  22193. }
  22194. TEST_F(SSEParsingTest, EmptyEventId) {
  22195. auto msgs = parse("id:\ndata: test\n\n");
  22196. ASSERT_EQ(msgs.size(), 1u);
  22197. EXPECT_EQ(msgs[0].id, "");
  22198. }
  22199. TEST_F(SSEParsingTest, CommentsIgnored) {
  22200. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22201. ASSERT_EQ(msgs.size(), 1u);
  22202. EXPECT_EQ(msgs[0].data, "hello");
  22203. EXPECT_EQ(msgs[0].event, "message");
  22204. }
  22205. TEST_F(SSEParsingTest, ColonInValue) {
  22206. auto msgs = parse("data: hello:world:test\n\n");
  22207. ASSERT_EQ(msgs.size(), 1u);
  22208. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22209. }
  22210. TEST_F(SSEParsingTest, FieldNameOnly) {
  22211. // A line without a colon is a field name with an empty value
  22212. auto msgs = parse("data\n\n");
  22213. ASSERT_EQ(msgs.size(), 1u);
  22214. EXPECT_EQ(msgs[0].data, "");
  22215. }
  22216. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22217. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22218. ASSERT_EQ(msgs.size(), 1u);
  22219. EXPECT_EQ(msgs[0].event, "update");
  22220. EXPECT_EQ(msgs[0].data, "hello");
  22221. }
  22222. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22223. auto msgs = parse("data\r\n\r\n");
  22224. ASSERT_EQ(msgs.size(), 1u);
  22225. EXPECT_EQ(msgs[0].data, "");
  22226. }
  22227. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22228. auto msgs = parse("event: update\rdata: hello\r\r");
  22229. ASSERT_EQ(msgs.size(), 1u);
  22230. EXPECT_EQ(msgs[0].event, "update");
  22231. EXPECT_EQ(msgs[0].data, "hello");
  22232. }
  22233. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22234. // Chunk boundaries fall inside every \r\n and right before the first one
  22235. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22236. "\n\r", "\nevent: end\ndata: end\n\n"};
  22237. server_->Get("/split", [chunks](const Request &, Response &res) {
  22238. auto i = std::make_shared<size_t>(0);
  22239. res.set_chunked_content_provider(
  22240. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22241. if (*i == chunks.size()) {
  22242. sink.done();
  22243. } else {
  22244. sink.write(chunks[*i].data(), chunks[*i].size());
  22245. (*i)++;
  22246. }
  22247. return true;
  22248. });
  22249. });
  22250. auto msgs = collect("/split");
  22251. ASSERT_EQ(msgs.size(), 1u);
  22252. EXPECT_EQ(msgs[0].event, "update");
  22253. EXPECT_EQ(msgs[0].data, "hello");
  22254. }
  22255. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22256. // Only a BOM at the start of the stream is ignored
  22257. auto msgs = parse("\xEF\xBB\xBF"
  22258. "data: first\n\n"
  22259. "\xEF\xBB\xBF"
  22260. "data: second\n\n");
  22261. ASSERT_EQ(msgs.size(), 1u);
  22262. EXPECT_EQ(msgs[0].data, "first");
  22263. }
  22264. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22265. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22266. ASSERT_EQ(msgs.size(), 1u);
  22267. EXPECT_EQ(msgs[0].data, "hello");
  22268. EXPECT_EQ(msgs[0].event, "message");
  22269. }
  22270. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22271. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22272. ASSERT_EQ(msgs.size(), 2u);
  22273. EXPECT_EQ(msgs[0].data, "hello");
  22274. EXPECT_EQ(msgs[1].data, "hello");
  22275. }
  22276. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22277. // An event without data is not dispatched, and its type must not leak
  22278. // into the next event
  22279. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22280. ASSERT_EQ(msgs.size(), 1u);
  22281. EXPECT_EQ(msgs[0].event, "message");
  22282. EXPECT_EQ(msgs[0].data, "hello");
  22283. }
  22284. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22285. // Also when the empty field replaces an earlier type
  22286. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22287. ASSERT_EQ(msgs.size(), 2u);
  22288. EXPECT_EQ(msgs[0].event, "message");
  22289. EXPECT_EQ(msgs[1].event, "message");
  22290. }
  22291. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22292. // The first connection sends only an id; the second echoes back the
  22293. // Last-Event-ID it was reconnected with
  22294. std::atomic<int> connection_count{0};
  22295. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22296. if (connection_count++ == 0) {
  22297. res.set_content("id: 42\n\n", "text/event-stream");
  22298. } else {
  22299. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22300. "\n\nevent: end\ndata: end\n\n",
  22301. "text/event-stream");
  22302. }
  22303. });
  22304. auto msgs = collect("/id-only");
  22305. ASSERT_EQ(msgs.size(), 1u);
  22306. EXPECT_EQ(msgs[0].data, "42");
  22307. }
  22308. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22309. // The first connection sets an id and then clears it with an empty one; the
  22310. // second reports whether it was reconnected with a Last-Event-ID
  22311. std::atomic<int> connection_count{0};
  22312. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22313. if (connection_count++ == 0) {
  22314. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22315. "text/event-stream");
  22316. } else {
  22317. res.set_content(
  22318. std::string("data: ") +
  22319. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22320. "\n\nevent: end\ndata: end\n\n",
  22321. "text/event-stream");
  22322. }
  22323. });
  22324. auto msgs = collect("/id-clear");
  22325. ASSERT_EQ(msgs.size(), 3u);
  22326. EXPECT_EQ(msgs[0].id, "1");
  22327. EXPECT_EQ(msgs[1].id, "");
  22328. EXPECT_EQ(msgs[2].data, "not sent");
  22329. }
  22330. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22331. // The first connection sets an id and then sends ids that cannot be carried
  22332. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22333. // with
  22334. std::atomic<int> connection_count{0};
  22335. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22336. if (connection_count++ == 0) {
  22337. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22338. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22339. "text/event-stream");
  22340. } else {
  22341. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22342. "\n\nevent: end\ndata: end\n\n",
  22343. "text/event-stream");
  22344. }
  22345. });
  22346. auto msgs = collect("/id-unsendable");
  22347. ASSERT_EQ(msgs.size(), 1u);
  22348. EXPECT_EQ(msgs[0].data, "42");
  22349. }
  22350. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22351. auto msgs = parse("event: notification\nid: evt-42\n"
  22352. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22353. ASSERT_EQ(msgs.size(), 1u);
  22354. EXPECT_EQ(msgs[0].event, "notification");
  22355. EXPECT_EQ(msgs[0].id, "evt-42");
  22356. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22357. }
  22358. TEST(SSEMessageTest, Clear) {
  22359. sse::SSEMessage msg;
  22360. msg.event = "custom";
  22361. msg.data = "some data";
  22362. msg.id = "123";
  22363. msg.clear();
  22364. EXPECT_EQ(msg.event, "message");
  22365. EXPECT_EQ(msg.data, "");
  22366. EXPECT_EQ(msg.id, "");
  22367. }
  22368. //==============================================================================
  22369. // SSE Integration Tests
  22370. //==============================================================================
  22371. // Test: Successful connection and on_open callback
  22372. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22373. // Add a simple endpoint that sends one event and closes
  22374. server_->Get("/simple-event", [](const Request &, Response &res) {
  22375. res.set_chunked_content_provider(
  22376. "text/event-stream", [](size_t offset, DataSink &sink) {
  22377. if (offset == 0) {
  22378. std::string event = "data: hello\n\n";
  22379. sink.write(event.data(), event.size());
  22380. }
  22381. return false; // Close stream after sending
  22382. });
  22383. });
  22384. Client client("localhost", get_port());
  22385. sse::SSEClient sse(client, "/simple-event");
  22386. std::atomic<bool> open_called{false};
  22387. std::atomic<bool> message_received{false};
  22388. sse.on_open([&open_called]() { open_called.store(true); });
  22389. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22390. if (msg.data == "hello") { message_received.store(true); }
  22391. });
  22392. sse.set_reconnect_interval(100);
  22393. sse.set_max_reconnect_attempts(1);
  22394. // Start async
  22395. sse.start_async();
  22396. // Wait for message to be processed
  22397. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22398. sse.stop();
  22399. EXPECT_TRUE(open_called.load());
  22400. EXPECT_TRUE(message_received.load());
  22401. }
  22402. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22403. // A data line that never ends.
  22404. server_->Get("/endless-line", [](const Request &, Response &res) {
  22405. res.set_chunked_content_provider(
  22406. "text/event-stream", [](size_t offset, DataSink &sink) {
  22407. if (offset == 0) { sink.write("data: ", 6); }
  22408. std::string chunk(64 * 1024, 'A');
  22409. return sink.write(chunk.data(), chunk.size());
  22410. });
  22411. });
  22412. Client client("localhost", get_port());
  22413. sse::SSEClient sse(client, "/endless-line");
  22414. std::atomic<bool> too_long{false};
  22415. sse.on_error([&](Error err) {
  22416. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22417. });
  22418. sse.set_max_reconnect_attempts(1);
  22419. sse.start_async();
  22420. for (int i = 0; i < 500 && !too_long; i++) {
  22421. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22422. }
  22423. sse.stop();
  22424. EXPECT_TRUE(too_long);
  22425. }
  22426. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22427. // Far more in all than the client's payload limit below.
  22428. server_->Get("/many-events", [](const Request &, Response &res) {
  22429. res.set_chunked_content_provider(
  22430. "text/event-stream", [](size_t offset, DataSink &sink) {
  22431. if (offset == 0) {
  22432. std::string events;
  22433. for (int i = 0; i < 1000; i++) {
  22434. events += "data: message\n\n";
  22435. }
  22436. sink.write(events.data(), events.size());
  22437. }
  22438. return false;
  22439. });
  22440. });
  22441. Client client("localhost", get_port());
  22442. client.set_payload_max_length(1024);
  22443. sse::SSEClient sse(client, "/many-events");
  22444. std::atomic<int> messages{0};
  22445. std::atomic<bool> too_large{false};
  22446. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22447. sse.on_error([&](Error err) {
  22448. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22449. });
  22450. sse.set_max_reconnect_attempts(1);
  22451. sse.start_async();
  22452. for (int i = 0; i < 500 && messages < 1000; i++) {
  22453. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22454. }
  22455. sse.stop();
  22456. EXPECT_GE(messages.load(), 1000);
  22457. EXPECT_FALSE(too_large);
  22458. }
  22459. // Test: on_message callback
  22460. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22461. // Endpoint that sends multiple events then closes
  22462. server_->Get("/multi-event", [](const Request &, Response &res) {
  22463. res.set_chunked_content_provider(
  22464. "text/event-stream", [](size_t offset, DataSink &sink) {
  22465. if (offset == 0) {
  22466. std::string events = "data: message1\n\ndata: message2\n\n";
  22467. sink.write(events.data(), events.size());
  22468. }
  22469. return false;
  22470. });
  22471. });
  22472. Client client("localhost", get_port());
  22473. sse::SSEClient sse(client, "/multi-event");
  22474. std::vector<std::string> received_messages;
  22475. std::mutex messages_mutex;
  22476. sse.on_message([&](const sse::SSEMessage &msg) {
  22477. std::lock_guard<std::mutex> lock(messages_mutex);
  22478. received_messages.push_back(msg.data);
  22479. });
  22480. sse.set_reconnect_interval(100);
  22481. sse.set_max_reconnect_attempts(1);
  22482. sse.start_async();
  22483. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22484. sse.stop();
  22485. std::lock_guard<std::mutex> lock(messages_mutex);
  22486. EXPECT_GE(received_messages.size(), 2u);
  22487. if (received_messages.size() >= 2) {
  22488. EXPECT_EQ(received_messages[0], "message1");
  22489. EXPECT_EQ(received_messages[1], "message2");
  22490. }
  22491. }
  22492. // Test: on_event for specific types
  22493. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22494. Client client("localhost", get_port());
  22495. sse::SSEClient sse(client, "/custom-events");
  22496. std::atomic<bool> update_received{false};
  22497. std::atomic<bool> delete_received{false};
  22498. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22499. if (msg.data == "updated") { update_received.store(true); }
  22500. });
  22501. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22502. if (msg.data == "deleted") { delete_received.store(true); }
  22503. });
  22504. sse.set_max_reconnect_attempts(1);
  22505. sse.start_async();
  22506. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22507. sse.stop();
  22508. EXPECT_TRUE(update_received.load());
  22509. EXPECT_TRUE(delete_received.load());
  22510. }
  22511. // Test: on_error callback on connection failure
  22512. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22513. // Connect to a non-existent port
  22514. Client client("localhost", 59999);
  22515. sse::SSEClient sse(client, "/events");
  22516. std::atomic<bool> error_called{false};
  22517. Error received_error = Error::Success;
  22518. sse.on_error([&](Error err) {
  22519. error_called.store(true);
  22520. received_error = err;
  22521. });
  22522. sse.set_reconnect_interval(50);
  22523. sse.set_max_reconnect_attempts(1);
  22524. sse.start_async();
  22525. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22526. sse.stop();
  22527. EXPECT_TRUE(error_called.load());
  22528. EXPECT_NE(received_error, Error::Success);
  22529. }
  22530. // Test: Last-Event-ID header sent on reconnect
  22531. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22532. // Endpoint that sends event with ID
  22533. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22534. res.set_chunked_content_provider(
  22535. "text/event-stream", [](size_t offset, DataSink &sink) {
  22536. if (offset == 0) {
  22537. std::string event = "id: evt-123\ndata: test\n\n";
  22538. sink.write(event.data(), event.size());
  22539. }
  22540. return false;
  22541. });
  22542. });
  22543. Client client("localhost", get_port());
  22544. sse::SSEClient sse(client, "/event-with-id");
  22545. std::atomic<bool> id_received{false};
  22546. sse.on_message([&](const sse::SSEMessage &msg) {
  22547. if (!msg.id.empty()) { id_received.store(true); }
  22548. });
  22549. sse.set_reconnect_interval(100);
  22550. sse.set_max_reconnect_attempts(1);
  22551. sse.start_async();
  22552. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22553. sse.stop();
  22554. EXPECT_TRUE(id_received.load());
  22555. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22556. }
  22557. // Test: last_event_id() read from another thread while start_async() runs
  22558. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22559. // Ids of every length up to 200, so the stored id keeps changing size
  22560. server_->Get("/many-ids", [](const Request &, Response &res) {
  22561. res.set_chunked_content_provider(
  22562. "text/event-stream", [](size_t offset, DataSink &sink) {
  22563. if (offset == 0) {
  22564. std::string events;
  22565. for (size_t i = 0; i < 2000; i++) {
  22566. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22567. events += "data: x\n\n";
  22568. }
  22569. events += "id: end\ndata: x\n\n";
  22570. sink.write(events.data(), events.size());
  22571. }
  22572. return false;
  22573. });
  22574. });
  22575. Client client("localhost", get_port());
  22576. sse::SSEClient sse(client, "/many-ids");
  22577. // Wait out the rest of the test rather than replay the stream
  22578. sse.set_reconnect_interval(10000);
  22579. sse.set_max_reconnect_attempts(1);
  22580. sse.start_async();
  22581. auto well_formed = true;
  22582. std::string id;
  22583. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22584. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22585. id = sse.last_event_id();
  22586. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22587. well_formed = false;
  22588. }
  22589. }
  22590. sse.stop();
  22591. EXPECT_TRUE(well_formed);
  22592. EXPECT_EQ(sse.last_event_id(), "end");
  22593. }
  22594. // Test: Manual stop
  22595. TEST_F(SSEIntegrationTest, ManualStop) {
  22596. // Endpoint that sends one event and stays open briefly. The server outlives
  22597. // this test body, so the provider uses the fixture's flag, not a local.
  22598. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22599. res.set_chunked_content_provider(
  22600. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22601. if (offset == 0) {
  22602. std::string event = "data: connected\n\n";
  22603. sink.write(event.data(), event.size());
  22604. }
  22605. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22606. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22607. }
  22608. return false;
  22609. });
  22610. });
  22611. Client client("localhost", get_port());
  22612. sse::SSEClient sse(client, "/stay-open");
  22613. std::atomic<bool> connected{false};
  22614. sse.on_open([&connected]() { connected.store(true); });
  22615. sse.set_reconnect_interval(100);
  22616. sse.set_max_reconnect_attempts(1);
  22617. sse.start_async();
  22618. // Wait for connection to establish
  22619. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22620. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22621. }
  22622. EXPECT_TRUE(connected.load());
  22623. EXPECT_TRUE(sse.is_connected());
  22624. // Signal handler to stop
  22625. stop_server_.store(true);
  22626. // Stop SSE client
  22627. sse.stop();
  22628. EXPECT_FALSE(sse.is_connected());
  22629. }
  22630. // Sends one event, then nothing until stop is set
  22631. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22632. return [&stop](const Request &, Response &res) {
  22633. res.set_chunked_content_provider(
  22634. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22635. if (offset == 0) {
  22636. std::string event = "data: hello\n\n";
  22637. sink.write(event.data(), event.size());
  22638. }
  22639. while (!stop.load()) {
  22640. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22641. }
  22642. return false;
  22643. });
  22644. };
  22645. }
  22646. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22647. static void check_stop_interrupts_blocked_read(Client &client) {
  22648. client.set_read_timeout(30, 0);
  22649. for (auto by_destructor : {false, true}) {
  22650. std::atomic<bool> received{false};
  22651. std::chrono::steady_clock::time_point start;
  22652. {
  22653. sse::SSEClient sse(client, "/idle-stream");
  22654. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22655. sse.start_async();
  22656. for (int i = 0; i < 500 && !received.load(); ++i) {
  22657. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22658. }
  22659. ASSERT_TRUE(received.load());
  22660. // Let the client block in the next read
  22661. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22662. start = std::chrono::steady_clock::now();
  22663. if (!by_destructor) { sse.stop(); }
  22664. }
  22665. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22666. std::chrono::seconds(2));
  22667. }
  22668. }
  22669. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22670. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22671. Client client("localhost", get_port());
  22672. check_stop_interrupts_blocked_read(client);
  22673. }
  22674. #ifdef CPPHTTPLIB_SSL_ENABLED
  22675. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22677. std::atomic<bool> done{false};
  22678. svr.Get("/idle-stream", idle_event_stream(done));
  22679. auto port = svr.bind_to_any_port(HOST);
  22680. std::thread t([&] { svr.listen_after_bind(); });
  22681. auto se = detail::scope_exit([&] {
  22682. done.store(true);
  22683. svr.stop();
  22684. t.join();
  22685. });
  22686. svr.wait_until_ready();
  22687. Client client("https://localhost:" + std::to_string(port));
  22688. client.enable_server_certificate_verification(false);
  22689. check_stop_interrupts_blocked_read(client);
  22690. }
  22691. #endif
  22692. // Test: SSEClient with custom headers
  22693. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22694. // Setup a server endpoint that checks for custom header
  22695. std::atomic<bool> header_received{false};
  22696. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22697. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22698. header_received.store(true);
  22699. }
  22700. res.set_chunked_content_provider("text/event-stream",
  22701. [](size_t, DataSink &) { return false; });
  22702. });
  22703. Client client("localhost", get_port());
  22704. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22705. sse::SSEClient sse(client, "/header-check", headers);
  22706. sse.set_max_reconnect_attempts(1);
  22707. sse.start_async();
  22708. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22709. sse.stop();
  22710. EXPECT_TRUE(header_received.load());
  22711. }
  22712. // Test: Reconnect interval configuration
  22713. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22714. Client client("localhost", get_port());
  22715. sse::SSEClient sse(client, "/events");
  22716. auto &result = sse.set_reconnect_interval(500);
  22717. // Builder pattern should return reference to self
  22718. EXPECT_EQ(&result, &sse);
  22719. }
  22720. // Test: Max reconnect attempts
  22721. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22722. // Connect to non-existent port to force reconnects
  22723. Client client("localhost", 59998);
  22724. sse::SSEClient sse(client, "/events");
  22725. std::atomic<int> error_count{0};
  22726. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22727. sse.set_reconnect_interval(50);
  22728. sse.set_max_reconnect_attempts(2);
  22729. auto start = std::chrono::steady_clock::now();
  22730. sse.start(); // Blocking call
  22731. auto end = std::chrono::steady_clock::now();
  22732. // Should have stopped after 2 failed attempts
  22733. EXPECT_GE(error_count.load(), 2);
  22734. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22735. auto duration =
  22736. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22737. #ifdef _WIN32
  22738. // Windows is much slower for socket connection failures
  22739. EXPECT_LT(duration.count(), 7000);
  22740. #else
  22741. EXPECT_LT(duration.count(), 1000);
  22742. #endif
  22743. }
  22744. // Test: Multi-line data in integration
  22745. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22746. // Endpoint with multi-line data
  22747. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22748. res.set_chunked_content_provider(
  22749. "text/event-stream", [](size_t offset, DataSink &sink) {
  22750. if (offset == 0) {
  22751. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22752. sink.write(event.data(), event.size());
  22753. }
  22754. return false;
  22755. });
  22756. });
  22757. Client client("localhost", get_port());
  22758. sse::SSEClient sse(client, "/multiline-data");
  22759. std::string received_data;
  22760. std::mutex data_mutex;
  22761. sse.on_message([&](const sse::SSEMessage &msg) {
  22762. std::lock_guard<std::mutex> lock(data_mutex);
  22763. received_data = msg.data;
  22764. });
  22765. sse.set_reconnect_interval(100);
  22766. sse.set_max_reconnect_attempts(1);
  22767. sse.start_async();
  22768. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22769. sse.stop();
  22770. std::lock_guard<std::mutex> lock(data_mutex);
  22771. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22772. }
  22773. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22774. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22775. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22776. DataSink &sink) {
  22777. if (offset == 0) {
  22778. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22779. sink.write(events.data(), events.size());
  22780. }
  22781. return false;
  22782. });
  22783. });
  22784. Client client("localhost", get_port());
  22785. sse::SSEClient sse(client, "/empty-data-lines");
  22786. std::mutex mutex;
  22787. std::condition_variable cv;
  22788. std::vector<std::string> received;
  22789. sse.on_message([&](const sse::SSEMessage &msg) {
  22790. std::lock_guard<std::mutex> lock(mutex);
  22791. received.push_back(msg.data);
  22792. cv.notify_all();
  22793. });
  22794. sse.set_max_reconnect_attempts(1);
  22795. sse.start_async();
  22796. {
  22797. std::unique_lock<std::mutex> lock(mutex);
  22798. cv.wait_for(lock, std::chrono::seconds(2),
  22799. [&] { return received.size() >= 3; });
  22800. }
  22801. sse.stop();
  22802. ASSERT_GE(received.size(), 3u);
  22803. EXPECT_EQ(received[0], "");
  22804. EXPECT_EQ(received[1], "\nhello");
  22805. EXPECT_EQ(received[2], "");
  22806. }
  22807. // Test: Auto-reconnect after server disconnection
  22808. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22809. std::atomic<int> connection_count{0};
  22810. std::atomic<int> message_count{0};
  22811. // Endpoint that sends one event and closes, forcing reconnect
  22812. server_->Get("/reconnect-test",
  22813. [&connection_count](const Request &, Response &res) {
  22814. connection_count.fetch_add(1);
  22815. res.set_chunked_content_provider(
  22816. "text/event-stream", [](size_t offset, DataSink &sink) {
  22817. if (offset == 0) {
  22818. std::string event = "data: hello\n\n";
  22819. sink.write(event.data(), event.size());
  22820. }
  22821. return false; // Close connection after sending
  22822. });
  22823. });
  22824. Client client("localhost", get_port());
  22825. sse::SSEClient sse(client, "/reconnect-test");
  22826. sse.on_message([&message_count](const sse::SSEMessage &) {
  22827. message_count.fetch_add(1);
  22828. });
  22829. sse.set_reconnect_interval(100);
  22830. sse.set_max_reconnect_attempts(3);
  22831. sse.start_async();
  22832. // Wait long enough for multiple reconnects
  22833. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22834. sse.stop();
  22835. // Should have connected multiple times (initial + reconnects)
  22836. EXPECT_GE(connection_count.load(), 2);
  22837. // Should have received messages from multiple connections
  22838. EXPECT_GE(message_count.load(), 2);
  22839. }
  22840. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22841. std::atomic<int> connection_count{0};
  22842. // Neither Content-Length nor chunked: the close ends the stream
  22843. server_->Get("/close-delimited",
  22844. [&connection_count](const Request &, Response &res) {
  22845. connection_count.fetch_add(1);
  22846. res.set_content_provider(
  22847. "text/event-stream", [](size_t offset, DataSink &sink) {
  22848. if (offset == 0) {
  22849. std::string event = "data: hello\n\n";
  22850. sink.write(event.data(), event.size());
  22851. } else {
  22852. sink.done();
  22853. }
  22854. return true;
  22855. });
  22856. });
  22857. Client client("localhost", get_port());
  22858. sse::SSEClient sse(client, "/close-delimited");
  22859. std::atomic<int> error_count{0};
  22860. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22861. sse.set_reconnect_interval(100);
  22862. sse.start_async();
  22863. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22864. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22865. }
  22866. sse.stop();
  22867. // Reconnects as after any end of the stream, but reports no error
  22868. EXPECT_GE(connection_count.load(), 2);
  22869. EXPECT_EQ(0, error_count.load());
  22870. }
  22871. // Test: A retry field that is not all ASCII digits is ignored
  22872. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22873. std::atomic<int> connection_count{0};
  22874. server_->Get("/bad-retry",
  22875. [&connection_count](const Request &, Response &res) {
  22876. connection_count.fetch_add(1);
  22877. res.set_chunked_content_provider(
  22878. "text/event-stream", [](size_t offset, DataSink &sink) {
  22879. if (offset == 0) {
  22880. std::string event = "retry: -1\ndata: hello\n\n";
  22881. sink.write(event.data(), event.size());
  22882. }
  22883. return false;
  22884. });
  22885. });
  22886. Client client("localhost", get_port());
  22887. sse::SSEClient sse(client, "/bad-retry");
  22888. sse.set_reconnect_interval(10000);
  22889. sse.start_async();
  22890. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22891. sse.stop();
  22892. EXPECT_EQ(connection_count.load(), 1);
  22893. }
  22894. // Test: A retry field of all ASCII digits sets the reconnection time
  22895. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22896. std::mutex mutex;
  22897. std::condition_variable cv;
  22898. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22899. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22900. {
  22901. std::lock_guard<std::mutex> lock(mutex);
  22902. connected_at.push_back(std::chrono::steady_clock::now());
  22903. cv.notify_all();
  22904. }
  22905. res.set_chunked_content_provider(
  22906. "text/event-stream", [](size_t offset, DataSink &sink) {
  22907. if (offset == 0) {
  22908. std::string event = "retry: 0\ndata: hello\n\n";
  22909. sink.write(event.data(), event.size());
  22910. }
  22911. return false;
  22912. });
  22913. });
  22914. Client client("localhost", get_port());
  22915. sse::SSEClient sse(client, "/zero-retry");
  22916. sse.set_reconnect_interval(10000);
  22917. sse.start_async();
  22918. {
  22919. std::unique_lock<std::mutex> lock(mutex);
  22920. cv.wait_for(lock, std::chrono::seconds(5),
  22921. [&] { return connected_at.size() >= 2; });
  22922. }
  22923. sse.stop();
  22924. // The server-supplied interval is applied, but never below 100ms, so
  22925. // "retry: 0" does not cause a busy reconnect loop
  22926. std::lock_guard<std::mutex> lock(mutex);
  22927. ASSERT_GE(connected_at.size(), 2u);
  22928. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22929. connected_at[1] - connected_at[0])
  22930. .count();
  22931. EXPECT_GE(interval_ms, 100);
  22932. }
  22933. // Test: Last-Event-ID sent on reconnect
  22934. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22935. std::atomic<int> connection_count{0};
  22936. std::vector<std::string> received_last_event_ids;
  22937. std::mutex id_mutex;
  22938. // Endpoint that checks Last-Event-ID header and sends event with ID
  22939. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22940. int conn = connection_count.fetch_add(1);
  22941. // Capture the Last-Event-ID header from each connection
  22942. {
  22943. std::lock_guard<std::mutex> lock(id_mutex);
  22944. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22945. }
  22946. res.set_chunked_content_provider(
  22947. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22948. if (offset == 0) {
  22949. std::string event =
  22950. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22951. sink.write(event.data(), event.size());
  22952. }
  22953. return false;
  22954. });
  22955. });
  22956. Client client("localhost", get_port());
  22957. sse::SSEClient sse(client, "/reconnect-with-id");
  22958. sse.set_reconnect_interval(100);
  22959. sse.set_max_reconnect_attempts(3);
  22960. sse.start_async();
  22961. // Wait for at least 2 connections
  22962. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22963. sse.stop();
  22964. // Verify behavior
  22965. std::lock_guard<std::mutex> lock(id_mutex);
  22966. EXPECT_GE(received_last_event_ids.size(), 2u);
  22967. // First connection should have no Last-Event-ID
  22968. if (!received_last_event_ids.empty()) {
  22969. EXPECT_EQ(received_last_event_ids[0], "");
  22970. }
  22971. // Second connection should have Last-Event-ID from first connection
  22972. if (received_last_event_ids.size() >= 2) {
  22973. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22974. }
  22975. }
  22976. // Test: set_headers updates headers used on reconnect
  22977. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22978. std::vector<std::string> received_tokens;
  22979. std::mutex token_mutex;
  22980. // Endpoint that captures Authorization header
  22981. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22982. {
  22983. std::lock_guard<std::mutex> lock(token_mutex);
  22984. received_tokens.push_back(req.get_header_value("Authorization"));
  22985. }
  22986. res.set_chunked_content_provider(
  22987. "text/event-stream", [](size_t offset, DataSink &sink) {
  22988. if (offset == 0) {
  22989. std::string event = "data: hello\n\n";
  22990. sink.write(event.data(), event.size());
  22991. }
  22992. return false; // Close connection to trigger reconnect
  22993. });
  22994. });
  22995. Client client("localhost", get_port());
  22996. Headers headers = {{"Authorization", "Bearer old-token"}};
  22997. sse::SSEClient sse(client, "/auth-check", headers);
  22998. // Update headers on each successful connection
  22999. sse.on_open(
  23000. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23001. sse.set_reconnect_interval(100);
  23002. sse.set_max_reconnect_attempts(3);
  23003. sse.start_async();
  23004. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23005. sse.stop();
  23006. std::lock_guard<std::mutex> lock(token_mutex);
  23007. ASSERT_GE(received_tokens.size(), 2u);
  23008. // First connection uses original header
  23009. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23010. // Second connection uses updated header from set_headers
  23011. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23012. }
  23013. // Test: 401 allows reconnection (so on_error can refresh headers)
  23014. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23015. std::atomic<int> connection_count{0};
  23016. // Endpoint: returns 401 on first attempt, 200 on second
  23017. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23018. int conn = connection_count.fetch_add(1);
  23019. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23020. res.status = StatusCode::Unauthorized_401;
  23021. res.set_content("Unauthorized", "text/plain");
  23022. return;
  23023. }
  23024. res.set_chunked_content_provider(
  23025. "text/event-stream", [](size_t offset, DataSink &sink) {
  23026. if (offset == 0) {
  23027. std::string event = "data: authenticated\n\n";
  23028. sink.write(event.data(), event.size());
  23029. }
  23030. return false;
  23031. });
  23032. });
  23033. Client client("localhost", get_port());
  23034. Headers headers = {{"Authorization", "Bearer expired"}};
  23035. sse::SSEClient sse(client, "/auth-retry", headers);
  23036. std::atomic<bool> message_received{false};
  23037. // Refresh token on error
  23038. sse.on_error(
  23039. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23040. sse.on_message([&](const sse::SSEMessage &msg) {
  23041. if (msg.data == "authenticated") { message_received.store(true); }
  23042. });
  23043. sse.set_reconnect_interval(100);
  23044. sse.set_max_reconnect_attempts(3);
  23045. sse.start_async();
  23046. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23047. sse.stop();
  23048. // Should have reconnected after 401 and succeeded with new token
  23049. EXPECT_GE(connection_count.load(), 2);
  23050. EXPECT_TRUE(message_received.load());
  23051. }
  23052. TEST(Issue2318Test, EmptyHostString) {
  23053. {
  23054. httplib::Client cli_empty("", PORT);
  23055. auto res = cli_empty.Get("/");
  23056. ASSERT_FALSE(res);
  23057. EXPECT_EQ(httplib::Error::Connection, res.error());
  23058. }
  23059. {
  23060. httplib::Client cli(" ", PORT);
  23061. auto res = cli.Get("/");
  23062. ASSERT_FALSE(res);
  23063. EXPECT_EQ(httplib::Error::Connection, res.error());
  23064. }
  23065. }
  23066. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23067. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23068. Server svr;
  23069. // Set a small payload limit (1KB)
  23070. svr.set_payload_max_length(1024);
  23071. svr.Post("/test", [&](const Request &req, Response &res) {
  23072. res.set_content("Body size: " + std::to_string(req.body.size()),
  23073. "text/plain");
  23074. });
  23075. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23076. auto se = detail::scope_exit([&] {
  23077. svr.stop();
  23078. listen_thread.join();
  23079. });
  23080. svr.wait_until_ready();
  23081. // Create data that compresses well but exceeds limit when decompressed
  23082. // 8KB of repeated null bytes compresses to a very small size
  23083. std::string original_data(8 * 1024, '\0');
  23084. // Compress the data using gzip
  23085. std::string compressed_data;
  23086. detail::gzip_compressor compressor;
  23087. compressor.compress(original_data.data(), original_data.size(), true,
  23088. [&](const char *data, size_t size) {
  23089. compressed_data.append(data, size);
  23090. return true;
  23091. });
  23092. // Verify compression worked (compressed should be much smaller)
  23093. ASSERT_LT(compressed_data.size(), original_data.size());
  23094. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23095. // Send compressed data with Content-Encoding: gzip
  23096. Client cli(HOST, PORT);
  23097. Headers headers = {{"Content-Encoding", "gzip"}};
  23098. auto res =
  23099. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23100. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23102. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23103. }
  23104. #endif
  23105. // ============================================================================
  23106. // OpenSSL-Specific Tests
  23107. // ============================================================================
  23108. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23109. X509 *readCertificate(const std::string &strFileName) {
  23110. std::ifstream inStream(strFileName);
  23111. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23112. std::istreambuf_iterator<char>());
  23113. if (strCertPEM.empty()) return (nullptr);
  23114. BIO *pbCert = BIO_new(BIO_s_mem());
  23115. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23116. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23117. BIO_free(pbCert);
  23118. return (pCert);
  23119. }
  23120. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23121. std::ifstream inStream(strFileName);
  23122. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23123. std::istreambuf_iterator<char>());
  23124. if (strPrivateKeyPEM.empty()) return (nullptr);
  23125. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23126. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23127. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23128. BIO_free(pbPrivKey);
  23129. return (pPrivateKey);
  23130. }
  23131. TEST(BindServerTest, UpdateCerts) {
  23132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23133. int port = svr.bind_to_any_port("0.0.0.0");
  23134. ASSERT_TRUE(svr.is_valid());
  23135. ASSERT_TRUE(port > 0);
  23136. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23137. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23138. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23139. ASSERT_TRUE(cert != nullptr);
  23140. ASSERT_TRUE(ca_cert != nullptr);
  23141. ASSERT_TRUE(key != nullptr);
  23142. X509_STORE *cert_store = X509_STORE_new();
  23143. X509_STORE_add_cert(cert_store, ca_cert);
  23144. // svr.update_certs(cert, key, cert_store); // deprecated
  23145. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23146. CLIENT_CA_CERT_FILE);
  23147. ASSERT_TRUE(svr.is_valid());
  23148. svr.stop();
  23149. X509_STORE_free(cert_store);
  23150. X509_free(cert);
  23151. X509_free(ca_cert);
  23152. EVP_PKEY_free(key);
  23153. }
  23154. // Test that update_certs() updates client CA list correctly
  23155. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23156. // Start with file-based constructor
  23157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23158. ASSERT_TRUE(svr.is_valid());
  23159. // Initially no client CA list should be set
  23160. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23161. ASSERT_TRUE(ssl_ctx != nullptr);
  23162. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23163. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23164. // Now update with client CA (PEM string)
  23165. std::string cert_pem, key_pem, ca_pem;
  23166. read_file(SERVER_CERT_FILE, cert_pem);
  23167. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23168. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23169. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23170. ASSERT_TRUE(svr.is_valid());
  23171. // Now client CA list should be set
  23172. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23173. ASSERT_TRUE(ca_list_after != nullptr);
  23174. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23175. }
  23176. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23177. // Test that the file-path SSLServer constructor properly sets the client CA
  23178. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23179. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23180. ASSERT_TRUE(svr.is_valid());
  23181. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23182. ASSERT_TRUE(ssl_ctx != nullptr);
  23183. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23184. ASSERT_TRUE(ca_list != nullptr);
  23185. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23186. }
  23187. #endif
  23188. // ============================================================================
  23189. // MbedTLS-Specific Tests
  23190. // ============================================================================
  23191. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23192. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23193. using namespace httplib::tls;
  23194. // Track if callback was invoked
  23195. bool callback_invoked = false;
  23196. // The callback receives void* ctx which is actually MbedTlsContext*
  23197. // We can access the mbedtls_ssl_config via the context
  23198. auto setup_callback = [&callback_invoked](void *ctx) {
  23199. callback_invoked = true;
  23200. // Cast to MbedTlsContext* to access the ssl config
  23201. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23202. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23203. // Use static variables to hold certificate data (simplified for test)
  23204. static mbedtls_x509_crt own_cert;
  23205. static mbedtls_pk_context own_key;
  23206. static mbedtls_x509_crt ca_chain;
  23207. static bool initialized = false;
  23208. if (!initialized) {
  23209. mbedtls_x509_crt_init(&own_cert);
  23210. mbedtls_pk_init(&own_key);
  23211. mbedtls_x509_crt_init(&ca_chain);
  23212. // Load server certificate
  23213. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23214. return false;
  23215. }
  23216. // Load server private key.
  23217. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23218. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23219. #if MBEDTLS_VERSION_MAJOR == 3
  23220. ,
  23221. mbedtls_ctr_drbg_random, nullptr
  23222. #endif
  23223. ) != 0) {
  23224. return false;
  23225. }
  23226. // Load CA chain for client verification
  23227. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23228. return false;
  23229. }
  23230. initialized = true;
  23231. }
  23232. // Configure the SSL config
  23233. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23234. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23235. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23236. // Set minimum TLS version using mbedTLS native API
  23237. #if MBEDTLS_VERSION_MAJOR >= 3
  23238. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23239. #else
  23240. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23241. MBEDTLS_SSL_MINOR_VERSION_3);
  23242. #endif
  23243. return true;
  23244. };
  23245. SSLServer svr(setup_callback);
  23246. ASSERT_TRUE(svr.is_valid());
  23247. ASSERT_TRUE(callback_invoked);
  23248. svr.Get("/test", [&](const Request &req, Response &res) {
  23249. res.set_content("test", "text/plain");
  23250. auto cert = req.peer_cert();
  23251. ASSERT_TRUE(static_cast<bool>(cert));
  23252. auto common_name = cert.subject_cn();
  23253. EXPECT_EQ("Common Name", common_name);
  23254. });
  23255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23256. auto se = detail::scope_exit([&] {
  23257. svr.stop();
  23258. t.join();
  23259. ASSERT_FALSE(svr.is_running());
  23260. });
  23261. svr.wait_until_ready();
  23262. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23263. cli.enable_server_certificate_verification(false);
  23264. cli.set_connection_timeout(30);
  23265. auto res = cli.Get("/test");
  23266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23267. ASSERT_EQ(StatusCode::OK_200, res->status);
  23268. }
  23269. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23270. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23271. // keep-alive SSL session, which reads through that config in
  23272. // mbedtls_ssl_close_notify.
  23273. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23275. ASSERT_TRUE(svr.is_valid());
  23276. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23277. res.set_content("test", "text/plain");
  23278. });
  23279. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23280. auto se = detail::scope_exit([&] {
  23281. svr.stop();
  23282. t.join();
  23283. ASSERT_FALSE(svr.is_running());
  23284. });
  23285. svr.wait_until_ready();
  23286. {
  23287. SSLClient cli(HOST, PORT);
  23288. cli.enable_server_certificate_verification(false);
  23289. cli.set_keep_alive(true);
  23290. auto res = cli.Get("/test");
  23291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23292. ASSERT_EQ(StatusCode::OK_200, res->status);
  23293. // cli is destructed here with the keep-alive SSL session still open.
  23294. }
  23295. }
  23296. #endif
  23297. // WebSocket Tests
  23298. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23299. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23300. // defining the meaning of these bits has been negotiated.
  23301. auto make_frame = [](uint8_t first_byte) {
  23302. std::string frame;
  23303. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23304. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23305. frame += "Hello";
  23306. return frame;
  23307. };
  23308. // RSV1 set (0x40)
  23309. {
  23310. detail::BufferStream strm;
  23311. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23312. ws::Opcode opcode;
  23313. std::string payload;
  23314. bool fin;
  23315. EXPECT_EQ(
  23316. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23317. ws::impl::FrameRead::Fail);
  23318. }
  23319. // RSV2 set (0x20)
  23320. {
  23321. detail::BufferStream strm;
  23322. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23323. ws::Opcode opcode;
  23324. std::string payload;
  23325. bool fin;
  23326. EXPECT_EQ(
  23327. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23328. ws::impl::FrameRead::Fail);
  23329. }
  23330. // RSV3 set (0x10)
  23331. {
  23332. detail::BufferStream strm;
  23333. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23334. ws::Opcode opcode;
  23335. std::string payload;
  23336. bool fin;
  23337. EXPECT_EQ(
  23338. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23339. ws::impl::FrameRead::Fail);
  23340. }
  23341. // No RSV bits set - should succeed
  23342. {
  23343. detail::BufferStream strm;
  23344. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23345. ws::Opcode opcode;
  23346. std::string payload;
  23347. bool fin;
  23348. EXPECT_EQ(
  23349. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23350. ws::impl::FrameRead::Ok);
  23351. EXPECT_EQ(ws::Opcode::Text, opcode);
  23352. EXPECT_EQ("Hello", payload);
  23353. EXPECT_TRUE(fin);
  23354. }
  23355. }
  23356. TEST(WebSocketTest, ControlFrameValidation) {
  23357. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23358. // payload length <= 125.
  23359. // Ping with FIN=0 - must be rejected
  23360. {
  23361. detail::BufferStream strm;
  23362. std::string frame;
  23363. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23364. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23365. strm.write(frame.data(), frame.size());
  23366. ws::Opcode opcode;
  23367. std::string payload;
  23368. bool fin;
  23369. EXPECT_EQ(
  23370. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23371. ws::impl::FrameRead::Fail);
  23372. }
  23373. // Close with FIN=0 - must be rejected
  23374. {
  23375. detail::BufferStream strm;
  23376. std::string frame;
  23377. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23378. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23379. strm.write(frame.data(), frame.size());
  23380. ws::Opcode opcode;
  23381. std::string payload;
  23382. bool fin;
  23383. EXPECT_EQ(
  23384. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23385. ws::impl::FrameRead::Fail);
  23386. }
  23387. // Ping with payload_len=126 (extended length) - must be rejected
  23388. {
  23389. detail::BufferStream strm;
  23390. std::string frame;
  23391. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23392. frame += static_cast<char>(126); // payload_len=126 (>125)
  23393. frame += static_cast<char>(0x00); // extended length high byte
  23394. frame += static_cast<char>(126); // extended length low byte
  23395. frame += std::string(126, 'x');
  23396. strm.write(frame.data(), frame.size());
  23397. ws::Opcode opcode;
  23398. std::string payload;
  23399. bool fin;
  23400. EXPECT_EQ(
  23401. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23402. ws::impl::FrameRead::Fail);
  23403. }
  23404. // Ping with FIN=1 and payload_len=125 - should succeed
  23405. {
  23406. detail::BufferStream strm;
  23407. std::string frame;
  23408. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23409. frame += static_cast<char>(125); // payload_len=125
  23410. frame += std::string(125, 'x');
  23411. strm.write(frame.data(), frame.size());
  23412. ws::Opcode opcode;
  23413. std::string payload;
  23414. bool fin;
  23415. EXPECT_EQ(
  23416. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23417. ws::impl::FrameRead::Ok);
  23418. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23419. EXPECT_EQ(125u, payload.size());
  23420. EXPECT_TRUE(fin);
  23421. }
  23422. }
  23423. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23424. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23425. // length MUST be 0.
  23426. // MSB set - must be rejected
  23427. {
  23428. detail::BufferStream strm;
  23429. std::string frame;
  23430. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23431. frame += static_cast<char>(127); // 64-bit extended length
  23432. frame += static_cast<char>(0x80); // MSB set (invalid)
  23433. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23434. strm.write(frame.data(), frame.size());
  23435. ws::Opcode opcode;
  23436. std::string payload;
  23437. bool fin;
  23438. EXPECT_EQ(
  23439. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23440. ws::impl::FrameRead::Fail);
  23441. }
  23442. // MSB clear - should pass length parsing (will be rejected by max_len,
  23443. // but that's a different check; use a small length to verify)
  23444. {
  23445. detail::BufferStream strm;
  23446. std::string frame;
  23447. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23448. frame += static_cast<char>(127); // 64-bit extended length
  23449. frame += std::string(7, '\0'); // high bytes = 0
  23450. frame += static_cast<char>(0x03); // length = 3
  23451. frame += "abc";
  23452. strm.write(frame.data(), frame.size());
  23453. ws::Opcode opcode;
  23454. std::string payload;
  23455. bool fin;
  23456. EXPECT_EQ(
  23457. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23458. ws::impl::FrameRead::Ok);
  23459. EXPECT_EQ(ws::Opcode::Text, opcode);
  23460. EXPECT_EQ("abc", payload);
  23461. }
  23462. }
  23463. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23464. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23465. // Valid UTF-8
  23466. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23467. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23468. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23469. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23470. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23471. // Invalid UTF-8
  23472. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23473. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23474. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23475. EXPECT_FALSE(
  23476. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23477. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23478. }
  23479. TEST(WebSocketTest, ConnectAndDisconnect) {
  23480. Server svr;
  23481. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23482. std::string msg;
  23483. while (ws.read(msg)) {}
  23484. });
  23485. auto port = svr.bind_to_any_port(HOST);
  23486. std::thread t([&]() { svr.listen_after_bind(); });
  23487. svr.wait_until_ready();
  23488. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23489. auto res = client.connect();
  23490. ASSERT_TRUE(res);
  23491. EXPECT_EQ(Error::Success, res.error());
  23492. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23493. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23494. EXPECT_TRUE(client.is_open());
  23495. client.close();
  23496. EXPECT_FALSE(client.is_open());
  23497. svr.stop();
  23498. t.join();
  23499. }
  23500. TEST(WebSocketTest, ValidURL) {
  23501. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23502. EXPECT_TRUE(ws1.is_valid());
  23503. ws::WebSocketClient ws2("ws://example.com/path");
  23504. EXPECT_TRUE(ws2.is_valid());
  23505. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23506. EXPECT_TRUE(ws3.is_valid());
  23507. #ifdef CPPHTTPLIB_SSL_ENABLED
  23508. ws::WebSocketClient wss1("wss://example.com/path");
  23509. EXPECT_TRUE(wss1.is_valid());
  23510. ws::WebSocketClient wss2("wss://example.com:443/path");
  23511. EXPECT_TRUE(wss2.is_valid());
  23512. #endif
  23513. }
  23514. TEST(WebSocketTest, InvalidURL) {
  23515. // No scheme
  23516. ws::WebSocketClient ws1("localhost:8080/path");
  23517. EXPECT_FALSE(ws1.is_valid());
  23518. // No path
  23519. ws::WebSocketClient ws2("ws://localhost:8080");
  23520. EXPECT_FALSE(ws2.is_valid());
  23521. // Empty string
  23522. ws::WebSocketClient ws3("");
  23523. EXPECT_FALSE(ws3.is_valid());
  23524. // Missing host
  23525. ws::WebSocketClient ws4("ws://:8080/path");
  23526. EXPECT_FALSE(ws4.is_valid());
  23527. // Port number overflow — should not crash
  23528. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23529. EXPECT_FALSE(ws5.is_valid());
  23530. // Port out of range
  23531. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23532. EXPECT_FALSE(ws6.is_valid());
  23533. }
  23534. TEST(WebSocketTest, UnsupportedScheme) {
  23535. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23536. ws::WebSocketClient ws1("http://localhost:8080/path");
  23537. EXPECT_FALSE(ws1.is_valid());
  23538. ws::WebSocketClient ws2("https://localhost:8080/path");
  23539. EXPECT_FALSE(ws2.is_valid());
  23540. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23541. EXPECT_FALSE(ws3.is_valid());
  23542. #else
  23543. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23544. std::invalid_argument);
  23545. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23546. std::invalid_argument);
  23547. #endif
  23548. }
  23549. TEST(WebSocketTest, ConnectWhenInvalid) {
  23550. ws::WebSocketClient ws("not a valid url");
  23551. EXPECT_FALSE(ws.is_valid());
  23552. auto res = ws.connect();
  23553. EXPECT_FALSE(res);
  23554. EXPECT_EQ(Error::Connection, res.error());
  23555. EXPECT_EQ(-1, res.status());
  23556. }
  23557. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23558. // Grab a port that is free, then close it again so nothing listens there
  23559. Server svr;
  23560. auto port = svr.bind_to_any_port(HOST);
  23561. svr.stop();
  23562. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23563. auto res = client.connect();
  23564. ASSERT_FALSE(res);
  23565. EXPECT_EQ(Error::Connection, res.error());
  23566. EXPECT_EQ(-1, res.status());
  23567. }
  23568. TEST(WebSocketTest, DefaultPort) {
  23569. ws::WebSocketClient ws1("ws://example.com/path");
  23570. EXPECT_TRUE(ws1.is_valid());
  23571. // ws:// defaults to port 80 (verified by successful parse)
  23572. #ifdef CPPHTTPLIB_SSL_ENABLED
  23573. ws::WebSocketClient ws2("wss://example.com/path");
  23574. EXPECT_TRUE(ws2.is_valid());
  23575. // wss:// defaults to port 443 (verified by successful parse)
  23576. #endif
  23577. }
  23578. TEST(WebSocketTest, IPv6LiteralAddress) {
  23579. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23580. EXPECT_TRUE(ws1.is_valid());
  23581. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23582. EXPECT_TRUE(ws2.is_valid());
  23583. }
  23584. TEST(WebSocketTest, ComplexPath) {
  23585. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23586. EXPECT_TRUE(ws1.is_valid());
  23587. ws::WebSocketClient ws2("ws://localhost:8080/");
  23588. EXPECT_TRUE(ws2.is_valid());
  23589. }
  23590. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23591. Server svr;
  23592. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23593. std::string msg;
  23594. while (ws.read(msg)) {}
  23595. });
  23596. auto port = svr.bind_to_any_port(HOST);
  23597. std::thread t([&]() { svr.listen_after_bind(); });
  23598. svr.wait_until_ready();
  23599. auto another_host = "example.com";
  23600. auto wrong_ip = "192.0.2.1";
  23601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23602. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  23603. ASSERT_TRUE(client.connect());
  23604. EXPECT_TRUE(client.is_open());
  23605. client.close();
  23606. svr.stop();
  23607. t.join();
  23608. }
  23609. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23610. Server svr;
  23611. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23612. std::string msg;
  23613. while (ws.read(msg)) {}
  23614. });
  23615. auto port = svr.bind_to_any_port(HOST);
  23616. std::thread t([&]() { svr.listen_after_bind(); });
  23617. svr.wait_until_ready();
  23618. auto wrong_ip = "192.0.2.1";
  23619. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23620. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  23621. client.set_connection_timeout(1);
  23622. client.set_read_timeout(1);
  23623. client.set_write_timeout(1);
  23624. EXPECT_FALSE(client.connect());
  23625. EXPECT_FALSE(client.is_open());
  23626. svr.stop();
  23627. t.join();
  23628. }
  23629. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23630. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23631. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23632. // (RFC 6761) is only a map key and the Host header value.
  23633. auto host = "target.invalid";
  23634. Server svr;
  23635. std::string received_host;
  23636. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23637. received_host = req.get_header_value("Host");
  23638. std::string msg;
  23639. while (ws.read(msg)) {}
  23640. });
  23641. auto port = svr.bind_to_any_port(HOST);
  23642. std::thread t([&]() { svr.listen_after_bind(); });
  23643. // ASSERT_* below returns from the test body, which would leave t joinable
  23644. // and make ~thread call std::terminate.
  23645. auto se = detail::scope_exit([&] {
  23646. svr.stop();
  23647. if (t.joinable()) { t.join(); }
  23648. });
  23649. svr.wait_until_ready();
  23650. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23651. std::to_string(port) + "/ws");
  23652. client.set_direct_hostname_addr_map({{host, HOST}});
  23653. ASSERT_TRUE(client.connect());
  23654. EXPECT_TRUE(client.is_open());
  23655. client.close();
  23656. svr.stop();
  23657. t.join();
  23658. // The mapping only redirects the connection; the identity stays host_.
  23659. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23660. }
  23661. class WebSocketIntegrationTest : public ::testing::Test {
  23662. protected:
  23663. void SetUp() override {
  23664. server_ = httplib::detail::make_unique<Server>();
  23665. setup_server();
  23666. start_server();
  23667. }
  23668. void TearDown() override {
  23669. server_->stop();
  23670. if (server_thread_.joinable()) { server_thread_.join(); }
  23671. }
  23672. void setup_server() {
  23673. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23674. std::string msg;
  23675. ws::ReadResult ret;
  23676. while ((ret = ws.read(msg))) {
  23677. if (ret == ws::Binary) {
  23678. ws.send(msg.data(), msg.size());
  23679. } else {
  23680. ws.send(msg);
  23681. }
  23682. }
  23683. });
  23684. server_->WebSocket("/ws-echo-string",
  23685. [](const Request &, ws::WebSocket &ws) {
  23686. std::string msg;
  23687. while (ws.read(msg)) {
  23688. ws.send("echo: " + msg);
  23689. }
  23690. });
  23691. server_->WebSocket(
  23692. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23693. // Echo back request metadata
  23694. ws.send("path:" + req.path);
  23695. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23696. std::string msg;
  23697. while (ws.read(msg)) {}
  23698. });
  23699. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23700. std::string msg;
  23701. ws.read(msg); // wait for a message
  23702. ws.close();
  23703. });
  23704. server_->WebSocket("/ws-close-status",
  23705. [](const Request &, ws::WebSocket &ws) {
  23706. std::string msg;
  23707. ws.read(msg); // wait for a message
  23708. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23709. });
  23710. server_->WebSocket(
  23711. "/ws-subprotocol",
  23712. [](const Request &, ws::WebSocket &ws) {
  23713. std::string msg;
  23714. while (ws.read(msg)) {
  23715. ws.send(msg);
  23716. }
  23717. },
  23718. [](const std::vector<std::string> &protocols) -> std::string {
  23719. for (const auto &p : protocols) {
  23720. if (p == "graphql-ws") { return p; }
  23721. }
  23722. return "";
  23723. });
  23724. server_->WebSocket(
  23725. "/ws-subprotocol-unoffered",
  23726. [](const Request &, ws::WebSocket &ws) {
  23727. std::string msg;
  23728. while (ws.read(msg)) {
  23729. ws.send(msg);
  23730. }
  23731. },
  23732. [](const std::vector<std::string> &) -> std::string {
  23733. return "admin";
  23734. });
  23735. }
  23736. void start_server() {
  23737. port_ = server_->bind_to_any_port(HOST);
  23738. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23739. server_->wait_until_ready();
  23740. }
  23741. std::unique_ptr<Server> server_;
  23742. std::thread server_thread_;
  23743. int port_ = 0;
  23744. };
  23745. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23746. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23747. "/ws-echo");
  23748. ASSERT_TRUE(client.connect());
  23749. ASSERT_TRUE(client.is_open());
  23750. ASSERT_TRUE(client.send("Hello WebSocket"));
  23751. std::string msg;
  23752. EXPECT_EQ(ws::Text, client.read(msg));
  23753. EXPECT_EQ("Hello WebSocket", msg);
  23754. client.close();
  23755. }
  23756. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23757. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23758. "/ws-echo");
  23759. ASSERT_TRUE(client.connect());
  23760. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23761. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23762. std::string msg;
  23763. EXPECT_EQ(ws::Binary, client.read(msg));
  23764. EXPECT_EQ(binary_data, msg);
  23765. client.close();
  23766. }
  23767. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23769. "/ws-echo");
  23770. ASSERT_TRUE(client.connect());
  23771. for (int i = 0; i < 10; i++) {
  23772. auto text = "message " + std::to_string(i);
  23773. ASSERT_TRUE(client.send(text));
  23774. std::string msg;
  23775. ASSERT_TRUE(client.read(msg));
  23776. EXPECT_EQ(text, msg);
  23777. }
  23778. client.close();
  23779. }
  23780. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23781. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23782. "/ws-close");
  23783. ASSERT_TRUE(client.connect());
  23784. // Send a message to trigger the server to close
  23785. ASSERT_TRUE(client.send("trigger close"));
  23786. // The server will close, so read should return false
  23787. std::string msg;
  23788. EXPECT_FALSE(client.read(msg));
  23789. EXPECT_FALSE(client.is_open());
  23790. }
  23791. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23792. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23793. "/ws-echo");
  23794. ASSERT_TRUE(client.connect());
  23795. // 128KB message
  23796. std::string large_data(128 * 1024, 'X');
  23797. ASSERT_TRUE(client.send(large_data));
  23798. std::string msg;
  23799. ASSERT_TRUE(client.read(msg));
  23800. EXPECT_EQ(large_data, msg);
  23801. client.close();
  23802. }
  23803. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23804. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23805. "/ws-echo");
  23806. ASSERT_TRUE(client.connect());
  23807. const int num_threads = 4;
  23808. std::vector<std::thread> threads;
  23809. std::atomic<int> send_count{0};
  23810. for (int t = 0; t < num_threads; t++) {
  23811. threads.emplace_back([&client, &send_count, t]() {
  23812. for (int i = 0; i < 5; i++) {
  23813. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23814. if (client.send(text)) { send_count++; }
  23815. }
  23816. });
  23817. }
  23818. for (auto &th : threads) {
  23819. th.join();
  23820. }
  23821. int received = 0;
  23822. std::string msg;
  23823. while (received < send_count.load()) {
  23824. if (!client.read(msg)) { break; }
  23825. received++;
  23826. }
  23827. EXPECT_EQ(send_count.load(), received);
  23828. client.close();
  23829. }
  23830. TEST_F(WebSocketIntegrationTest, ReadString) {
  23831. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23832. "/ws-echo-string");
  23833. ASSERT_TRUE(client.connect());
  23834. ASSERT_TRUE(client.send("hello"));
  23835. std::string msg;
  23836. ASSERT_TRUE(client.read(msg));
  23837. EXPECT_EQ("echo: hello", msg);
  23838. ASSERT_TRUE(client.send("world"));
  23839. ASSERT_TRUE(client.read(msg));
  23840. EXPECT_EQ("echo: world", msg);
  23841. client.close();
  23842. }
  23843. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23844. Headers headers = {{"X-Test-Header", "test-value"}};
  23845. ws::WebSocketClient client(
  23846. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23847. ASSERT_TRUE(client.connect());
  23848. std::string msg;
  23849. ASSERT_TRUE(client.read(msg));
  23850. EXPECT_EQ("path:/ws-request-info", msg);
  23851. ASSERT_TRUE(client.read(msg));
  23852. EXPECT_EQ("header:test-value", msg);
  23853. client.close();
  23854. }
  23855. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23857. "/ws-echo");
  23858. client.set_read_timeout(1, 0); // 1 second
  23859. ASSERT_TRUE(client.connect());
  23860. // Don't send anything — server echo handler waits for a message, so read()
  23861. // should time out. The connection survives it: nothing was consumed.
  23862. std::string msg;
  23863. EXPECT_EQ(client.read(msg), ws::Timeout);
  23864. EXPECT_TRUE(client.is_open());
  23865. // And it is still usable afterwards.
  23866. EXPECT_TRUE(client.send("after timeout"));
  23867. EXPECT_EQ(client.read(msg), ws::Text);
  23868. EXPECT_EQ(msg, "after timeout");
  23869. }
  23870. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23872. "/ws-echo");
  23873. client.set_read_timeout(1, 0);
  23874. ASSERT_TRUE(client.connect());
  23875. ASSERT_TRUE(client.send("first"));
  23876. std::string msg;
  23877. ASSERT_EQ(client.read(msg), ws::Text);
  23878. ASSERT_EQ(msg, "first");
  23879. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23880. // not be used with a read timeout: it would reprocess the previous message.
  23881. EXPECT_EQ(client.read(msg), ws::Timeout);
  23882. EXPECT_EQ(msg, "first");
  23883. }
  23884. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23885. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23886. "/ws-echo");
  23887. ASSERT_TRUE(client.connect());
  23888. // Setting it once the connection is open reaches the live stream, not just
  23889. // the seed for the next connect().
  23890. client.set_read_timeout(1, 0);
  23891. std::string msg;
  23892. EXPECT_EQ(client.read(msg), ws::Timeout);
  23893. EXPECT_TRUE(client.is_open());
  23894. }
  23895. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23897. "/ws-echo");
  23898. client.set_read_timeout(5, 0);
  23899. ASSERT_TRUE(client.connect());
  23900. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23901. // The server should reject it and close the connection.
  23902. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23903. client.send(oversized);
  23904. // The server's read() should have failed due to payload limit,
  23905. // so our read() should return false (connection closed).
  23906. std::string msg;
  23907. EXPECT_FALSE(client.read(msg));
  23908. }
  23909. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23910. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23911. "/ws-echo");
  23912. client.set_read_timeout(10, 0);
  23913. ASSERT_TRUE(client.connect());
  23914. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23915. // This should succeed.
  23916. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23917. ASSERT_TRUE(client.send(at_limit));
  23918. std::string msg;
  23919. ASSERT_TRUE(client.read(msg));
  23920. EXPECT_EQ(at_limit.size(), msg.size());
  23921. client.close();
  23922. }
  23923. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23925. "/nonexistent");
  23926. auto res = client.connect();
  23927. EXPECT_FALSE(res);
  23928. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23929. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23930. EXPECT_FALSE(client.is_open());
  23931. }
  23932. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23934. "/ws-echo");
  23935. ASSERT_TRUE(client.connect());
  23936. ASSERT_TRUE(client.send(""));
  23937. std::string msg;
  23938. EXPECT_EQ(ws::Text, client.read(msg));
  23939. EXPECT_EQ("", msg);
  23940. client.close();
  23941. }
  23942. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23943. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23944. "/ws-echo");
  23945. // First connection
  23946. ASSERT_TRUE(client.connect());
  23947. ASSERT_TRUE(client.send("first"));
  23948. std::string msg;
  23949. ASSERT_TRUE(client.read(msg));
  23950. EXPECT_EQ("first", msg);
  23951. client.close();
  23952. EXPECT_FALSE(client.is_open());
  23953. // Reconnect using the same client object
  23954. ASSERT_TRUE(client.connect());
  23955. ASSERT_TRUE(client.is_open());
  23956. ASSERT_TRUE(client.send("second"));
  23957. ASSERT_TRUE(client.read(msg));
  23958. EXPECT_EQ("second", msg);
  23959. client.close();
  23960. }
  23961. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23962. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23963. "/ws-close-status");
  23964. ASSERT_TRUE(client.connect());
  23965. // Trigger the server to close with GoingAway status
  23966. ASSERT_TRUE(client.send("trigger"));
  23967. // read() should return false after receiving the close frame
  23968. std::string msg;
  23969. EXPECT_FALSE(client.read(msg));
  23970. EXPECT_FALSE(client.is_open());
  23971. }
  23972. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23973. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23974. "/ws-echo");
  23975. ASSERT_TRUE(client.connect());
  23976. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23977. EXPECT_FALSE(client.is_open());
  23978. }
  23979. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23980. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23981. ws::WebSocketClient client(
  23982. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23983. ASSERT_TRUE(client.connect());
  23984. // Server should have selected graphql-ws
  23985. EXPECT_EQ("graphql-ws", client.subprotocol());
  23986. client.close();
  23987. }
  23988. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23989. Headers headers;
  23990. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23991. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23992. ws::WebSocketClient client(
  23993. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23994. ASSERT_TRUE(client.connect());
  23995. // The offer on the second field line counts too, so graphql-ws is selected
  23996. EXPECT_EQ("graphql-ws", client.subprotocol());
  23997. client.close();
  23998. }
  23999. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24000. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24001. ws::WebSocketClient client(
  24002. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24003. ASSERT_TRUE(client.connect());
  24004. // Server should not have selected any subprotocol
  24005. EXPECT_TRUE(client.subprotocol().empty());
  24006. client.close();
  24007. }
  24008. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24009. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24010. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24011. "/ws-subprotocol-unoffered",
  24012. headers);
  24013. ASSERT_TRUE(client.connect());
  24014. EXPECT_TRUE(client.subprotocol().empty());
  24015. client.close();
  24016. }
  24017. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24018. // Connect without requesting any subprotocol
  24019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24020. "/ws-subprotocol");
  24021. ASSERT_TRUE(client.connect());
  24022. EXPECT_TRUE(client.subprotocol().empty());
  24023. client.close();
  24024. }
  24025. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24026. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24027. "/ws-echo");
  24028. client.set_tcp_nodelay(true);
  24029. client.set_connection_timeout(3, 0);
  24030. bool socket_options_called = false;
  24031. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24032. ASSERT_TRUE(client.connect());
  24033. ASSERT_TRUE(client.is_open());
  24034. EXPECT_TRUE(socket_options_called);
  24035. ASSERT_TRUE(client.send("hello"));
  24036. std::string msg;
  24037. auto result = client.read(msg);
  24038. EXPECT_EQ(result, ws::ReadResult::Text);
  24039. EXPECT_EQ(msg, "hello");
  24040. client.close();
  24041. }
  24042. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24044. "/ws-echo");
  24045. client.set_connection_timeout(std::chrono::seconds(3));
  24046. client.set_write_timeout(std::chrono::seconds(3));
  24047. // A sub-second remainder exercises the seconds/microseconds split.
  24048. client.set_read_timeout(std::chrono::milliseconds(1500));
  24049. ASSERT_TRUE(client.connect());
  24050. auto start = std::chrono::steady_clock::now();
  24051. std::string msg;
  24052. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24053. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24054. std::chrono::steady_clock::now() - start)
  24055. .count();
  24056. // Above 1s so that dropping the microseconds half of the split fails here.
  24057. // Ignoring the setter altogether would not reach this line at all: a client
  24058. // waits forever by default.
  24059. EXPECT_GE(elapsed, 1400);
  24060. EXPECT_LT(elapsed, 30000);
  24061. }
  24062. #ifndef _WIN32
  24063. // A send() that times out after part of the data went out returns the count
  24064. // written so far. Every byte of the frame must still be sent, or the peer reads
  24065. // the next frame's header and payload as the rest of this one.
  24066. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24067. signal(SIGPIPE, SIG_IGN);
  24068. const std::string large(4 * 1024 * 1024, 'A');
  24069. std::atomic<bool> large_sent{false};
  24070. std::atomic<bool> small_sent{false};
  24071. Server svr;
  24072. svr.set_write_timeout(0, 500000);
  24073. svr.set_socket_options([](socket_t sock) {
  24074. int size = 8192;
  24075. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24076. reinterpret_cast<const char *>(&size), sizeof(size));
  24077. });
  24078. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24079. large_sent = ws.send(large.data(), large.size());
  24080. small_sent = ws.send("after");
  24081. std::string msg;
  24082. while (ws.read(msg)) {}
  24083. });
  24084. auto port = svr.bind_to_any_port(HOST);
  24085. std::thread t([&]() { svr.listen_after_bind(); });
  24086. auto se = detail::scope_exit([&] {
  24087. svr.stop();
  24088. t.join();
  24089. });
  24090. svr.wait_until_ready();
  24091. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24092. std::to_string(port) + "/ws");
  24093. client.set_read_timeout(5);
  24094. client.set_socket_options([](socket_t sock) {
  24095. int size = 8192;
  24096. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24097. reinterpret_cast<const char *>(&size), sizeof(size));
  24098. });
  24099. ASSERT_TRUE(client.connect());
  24100. // Outlast the server's write timeout, then drain.
  24101. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24102. std::string msg;
  24103. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24104. EXPECT_TRUE(msg == large);
  24105. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24106. EXPECT_EQ("after", msg);
  24107. EXPECT_TRUE(large_sent);
  24108. EXPECT_TRUE(small_sent);
  24109. client.close();
  24110. }
  24111. #endif
  24112. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24113. Server svr;
  24114. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24115. if (!req.has_header("Authorization")) {
  24116. res.status = StatusCode::Unauthorized_401;
  24117. res.set_content("Unauthorized", "text/plain");
  24118. return Server::HandlerResponse::Handled;
  24119. }
  24120. return Server::HandlerResponse::Unhandled;
  24121. });
  24122. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24123. std::string msg;
  24124. while (ws.read(msg)) {
  24125. ws.send(msg);
  24126. }
  24127. });
  24128. auto port = svr.bind_to_any_port("localhost");
  24129. std::thread t([&]() { svr.listen_after_bind(); });
  24130. svr.wait_until_ready();
  24131. // Without Authorization header - should be rejected before upgrade
  24132. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24133. EXPECT_FALSE(client1.connect());
  24134. // The rejection is framed like any other HTTP response
  24135. {
  24136. Client cli("localhost", port);
  24137. Headers headers = {{"Upgrade", "websocket"},
  24138. {"Connection", "Upgrade"},
  24139. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24140. {"Sec-WebSocket-Version", "13"}};
  24141. auto res = cli.Get("/ws", headers);
  24142. ASSERT_TRUE(res);
  24143. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24144. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24145. EXPECT_EQ("Unauthorized", res->body);
  24146. }
  24147. // With Authorization header - should succeed
  24148. Headers headers = {{"Authorization", "Bearer token123"}};
  24149. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24150. headers);
  24151. ASSERT_TRUE(client2.connect());
  24152. ASSERT_TRUE(client2.send("hello"));
  24153. std::string msg;
  24154. ASSERT_TRUE(client2.read(msg));
  24155. EXPECT_EQ("hello", msg);
  24156. client2.close();
  24157. svr.stop();
  24158. t.join();
  24159. }
  24160. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24161. Server svr;
  24162. std::atomic<int> pre_routing_calls{0};
  24163. std::atomic<int> pre_request_calls{0};
  24164. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24165. pre_routing_calls++;
  24166. if (req.path == "/handled") {
  24167. res.set_content("handled", "text/plain");
  24168. return Server::HandlerResponse::Handled;
  24169. }
  24170. return Server::HandlerResponse::Unhandled;
  24171. });
  24172. svr.set_pre_request_handler([&](const Request &, Response &) {
  24173. pre_request_calls++;
  24174. return Server::HandlerResponse::Unhandled;
  24175. });
  24176. svr.Get("/http", [](const Request &, Response &res) {
  24177. res.set_content("http", "text/plain");
  24178. });
  24179. svr.WebSocket("/ws",
  24180. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24181. auto port = svr.bind_to_any_port("localhost");
  24182. std::thread t([&]() { svr.listen_after_bind(); });
  24183. auto se = detail::scope_exit([&] {
  24184. svr.stop();
  24185. t.join();
  24186. });
  24187. svr.wait_until_ready();
  24188. Headers upgrade = {{"Upgrade", "websocket"},
  24189. {"Connection", "Upgrade"},
  24190. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24191. {"Sec-WebSocket-Version", "13"}};
  24192. auto get = [&](const char *path) {
  24193. pre_routing_calls = 0;
  24194. return Client("localhost", port).Get(path, upgrade);
  24195. };
  24196. // No WebSocket route, but an HTTP one
  24197. auto res = get("/http");
  24198. ASSERT_TRUE(res);
  24199. EXPECT_EQ(StatusCode::OK_200, res->status);
  24200. EXPECT_EQ("http", res->body);
  24201. EXPECT_EQ(1, pre_routing_calls);
  24202. EXPECT_EQ(1, pre_request_calls);
  24203. // No route at all
  24204. res = get("/none");
  24205. ASSERT_TRUE(res);
  24206. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24207. EXPECT_EQ(1, pre_routing_calls);
  24208. // Answered by the pre-routing handler
  24209. res = get("/handled");
  24210. ASSERT_TRUE(res);
  24211. EXPECT_EQ(StatusCode::OK_200, res->status);
  24212. EXPECT_EQ("handled", res->body);
  24213. EXPECT_EQ(1, pre_routing_calls);
  24214. // A WebSocket route
  24215. pre_routing_calls = 0;
  24216. pre_request_calls = 0;
  24217. {
  24218. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24219. "/ws");
  24220. ASSERT_TRUE(client.connect());
  24221. std::string msg;
  24222. ASSERT_TRUE(client.read(msg));
  24223. EXPECT_EQ("ws", msg);
  24224. client.close();
  24225. }
  24226. EXPECT_EQ(1, pre_routing_calls);
  24227. EXPECT_EQ(1, pre_request_calls);
  24228. }
  24229. // An upgrade request answered by a hook leaves its body unread, so that body
  24230. // must not be served as the next request on the connection.
  24231. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24232. Server svr;
  24233. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24234. if (req.path == "/pre-routing") {
  24235. res.set_content("pre-routing", "text/plain");
  24236. return Server::HandlerResponse::Handled;
  24237. }
  24238. return Server::HandlerResponse::Unhandled;
  24239. });
  24240. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24241. if (req.matched_route == "/pre-request") {
  24242. res.set_content("pre-request", "text/plain");
  24243. return Server::HandlerResponse::Handled;
  24244. }
  24245. return Server::HandlerResponse::Unhandled;
  24246. });
  24247. svr.Get("/smuggled", [](const Request &, Response &res) {
  24248. res.set_content("smuggled", "text/plain");
  24249. });
  24250. svr.WebSocket("/pre-request",
  24251. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24252. auto port = svr.bind_to_any_port(HOST);
  24253. std::thread t([&]() { svr.listen_after_bind(); });
  24254. auto se = detail::scope_exit([&] {
  24255. svr.stop();
  24256. t.join();
  24257. });
  24258. svr.wait_until_ready();
  24259. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24260. for (auto path : {"/pre-routing", "/pre-request"}) {
  24261. std::string req = std::string("GET ") + path +
  24262. " HTTP/1.1\r\n"
  24263. "Host: localhost\r\n"
  24264. "Upgrade: websocket\r\n"
  24265. "Connection: Upgrade\r\n"
  24266. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24267. "Sec-WebSocket-Version: 13\r\n"
  24268. "Content-Length: " +
  24269. std::to_string(body.size()) + "\r\n\r\n" + body;
  24270. std::string res;
  24271. ASSERT_TRUE(send_request(5, req, &res, port));
  24272. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24273. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24274. // Only one response, and the body was not served as a request
  24275. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24276. }
  24277. }
  24278. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24279. Server svr;
  24280. std::atomic<int> pre_request_calls{0};
  24281. std::atomic<bool> route_matched{false};
  24282. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24283. pre_request_calls++;
  24284. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24285. if (req.get_header_value("Authorization") != "Bearer token123") {
  24286. res.status = StatusCode::Unauthorized_401;
  24287. res.set_content("Unauthorized", "text/plain");
  24288. return Server::HandlerResponse::Handled;
  24289. }
  24290. return Server::HandlerResponse::Unhandled;
  24291. });
  24292. std::atomic<bool> handler_called{false};
  24293. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24294. handler_called = true;
  24295. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24296. });
  24297. auto port = svr.bind_to_any_port("localhost");
  24298. std::thread t([&]() { svr.listen_after_bind(); });
  24299. svr.wait_until_ready();
  24300. // Without Authorization header - should be rejected before upgrade
  24301. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24302. "/ws/1");
  24303. EXPECT_FALSE(client1.connect());
  24304. EXPECT_FALSE(handler_called);
  24305. EXPECT_EQ(1, pre_request_calls);
  24306. EXPECT_TRUE(route_matched);
  24307. // The rejection is an ordinary HTTP response, not a protocol switch
  24308. {
  24309. Client cli("localhost", port);
  24310. Headers headers = {{"Upgrade", "websocket"},
  24311. {"Connection", "Upgrade"},
  24312. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24313. {"Sec-WebSocket-Version", "13"}};
  24314. auto res = cli.Get("/ws/1", headers);
  24315. ASSERT_TRUE(res);
  24316. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24317. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24318. EXPECT_EQ("Unauthorized", res->body);
  24319. }
  24320. EXPECT_FALSE(handler_called);
  24321. // With Authorization header - should succeed
  24322. Headers headers = {{"Authorization", "Bearer token123"}};
  24323. ws::WebSocketClient client2(
  24324. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24325. ASSERT_TRUE(client2.connect());
  24326. std::string msg;
  24327. ASSERT_TRUE(client2.read(msg));
  24328. EXPECT_EQ("/ws/:id 2", msg);
  24329. EXPECT_TRUE(handler_called);
  24330. client2.close();
  24331. svr.stop();
  24332. t.join();
  24333. }
  24334. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24335. static Headers websocket_upgrade_headers() {
  24336. return {{"Upgrade", "websocket"},
  24337. {"Connection", "Upgrade"},
  24338. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24339. {"Sec-WebSocket-Version", "13"},
  24340. {"Sec-WebSocket-Protocol", "chat"}};
  24341. }
  24342. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24343. Server svr;
  24344. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24345. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24346. return Server::HandlerResponse::Unhandled;
  24347. });
  24348. svr.set_pre_request_handler([](const Request &req, Response &) {
  24349. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24350. return Server::HandlerResponse::Unhandled;
  24351. });
  24352. svr.set_exception_handler(
  24353. [](const Request &, Response &res, std::exception_ptr ep) {
  24354. try {
  24355. std::rethrow_exception(ep);
  24356. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24357. });
  24358. auto handler = [](const Request &, ws::WebSocket &) {};
  24359. svr.WebSocket("/pre-routing", handler);
  24360. svr.WebSocket("/pre-request", handler);
  24361. svr.WebSocket("/sub-protocol", handler,
  24362. [](const std::vector<std::string> &) -> std::string {
  24363. throw std::runtime_error("/sub-protocol");
  24364. });
  24365. auto port = svr.bind_to_any_port(HOST);
  24366. ASSERT_GT(port, 0);
  24367. thread t = thread([&] { svr.listen_after_bind(); });
  24368. auto se = detail::scope_exit([&] {
  24369. svr.stop();
  24370. t.join();
  24371. ASSERT_FALSE(svr.is_running());
  24372. });
  24373. svr.wait_until_ready();
  24374. Client cli(HOST, port);
  24375. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24376. auto res = cli.Get(path, websocket_upgrade_headers());
  24377. if (!res) {
  24378. ADD_FAILURE() << path << ": " << to_string(res.error());
  24379. continue;
  24380. }
  24381. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24382. EXPECT_EQ(path, res->body);
  24383. }
  24384. }
  24385. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24386. Server svr;
  24387. svr.set_pre_routing_handler(
  24388. [](const Request &, Response &) -> Server::HandlerResponse {
  24389. throw std::runtime_error("pre-routing");
  24390. });
  24391. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24392. auto port = svr.bind_to_any_port(HOST);
  24393. ASSERT_GT(port, 0);
  24394. thread t = thread([&] { svr.listen_after_bind(); });
  24395. auto se = detail::scope_exit([&] {
  24396. svr.stop();
  24397. t.join();
  24398. ASSERT_FALSE(svr.is_running());
  24399. });
  24400. svr.wait_until_ready();
  24401. Client cli(HOST, port);
  24402. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24403. ASSERT_TRUE(res) << to_string(res.error());
  24404. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24405. }
  24406. #endif
  24407. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24408. Server svr;
  24409. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24410. // A read timeout is how a handler gets control back. Without it, a handler
  24411. // parked in read() can never write on the connection it is reading.
  24412. ws.set_read_timeout(std::chrono::milliseconds(100));
  24413. std::string msg;
  24414. while (ws.is_open()) {
  24415. auto r = ws.read(msg);
  24416. if (r == httplib::ws::Timeout) {
  24417. ws.send("tick");
  24418. continue;
  24419. }
  24420. if (r == httplib::ws::Fail) { break; }
  24421. ws.send(msg);
  24422. }
  24423. });
  24424. auto port = svr.bind_to_any_port("localhost");
  24425. std::thread t([&]() { svr.listen_after_bind(); });
  24426. svr.wait_until_ready();
  24427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24428. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24429. ASSERT_TRUE(client.connect());
  24430. // The client sends nothing, so anything it receives came out of the
  24431. // handler's timeout path.
  24432. std::string msg;
  24433. ASSERT_EQ(client.read(msg), ws::Text);
  24434. EXPECT_EQ("tick", msg);
  24435. client.close();
  24436. svr.stop();
  24437. t.join();
  24438. }
  24439. // Stream::read may return fewer bytes than asked for. This is that contract at
  24440. // its worst -- one byte per call -- which is what a frame header straddling a
  24441. // read buffer's boundary looks like to the frame parser.
  24442. class WsByteAtATimeStream : public Stream {
  24443. public:
  24444. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24445. bool is_readable() const override { return true; }
  24446. bool wait_readable() const override { return true; }
  24447. bool wait_writable() const override { return true; }
  24448. ssize_t read(char *ptr, size_t size) override {
  24449. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24450. *ptr = data_[pos_++];
  24451. return 1;
  24452. }
  24453. ssize_t write(const char *, size_t size) override {
  24454. return static_cast<ssize_t>(size);
  24455. }
  24456. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24457. ip = "127.0.0.1";
  24458. port = 0;
  24459. }
  24460. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24461. ip = "127.0.0.1";
  24462. port = 0;
  24463. }
  24464. socket_t socket() const override { return INVALID_SOCKET; }
  24465. time_t duration() const override { return 0; }
  24466. private:
  24467. std::string data_;
  24468. size_t pos_ = 0;
  24469. };
  24470. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24471. // The payload uses the 16-bit extended length, so the header, the length
  24472. // and the mask key are all multi-byte fields here. Each used to be read
  24473. // with a single read() call, which fails as soon as one is split. The
  24474. // payload is also a little over one read chunk, so it is read in two.
  24475. std::string body;
  24476. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24477. body += static_cast<char>(i % 251);
  24478. }
  24479. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24480. std::string frame;
  24481. frame += static_cast<char>(0x81); // FIN + Text
  24482. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24483. frame += static_cast<char>(body.size() >> 8);
  24484. frame += static_cast<char>(body.size() & 0xff);
  24485. for (size_t i = 0; i < 4; i++) {
  24486. frame += static_cast<char>(mask[i]);
  24487. }
  24488. for (size_t i = 0; i < body.size(); i++) {
  24489. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24490. }
  24491. WsByteAtATimeStream strm(frame);
  24492. ws::Opcode opcode;
  24493. std::string payload;
  24494. bool fin = false;
  24495. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24496. /*expect_masked=*/true, body.size()),
  24497. ws::impl::FrameRead::Ok);
  24498. EXPECT_TRUE(fin);
  24499. EXPECT_EQ(opcode, ws::Opcode::Text);
  24500. EXPECT_EQ(payload, body);
  24501. }
  24502. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24503. std::string body(2000, 'x');
  24504. std::string frame;
  24505. frame += static_cast<char>(0x82); // FIN + Binary
  24506. frame += static_cast<char>(126); // 16-bit length follows
  24507. frame += static_cast<char>(body.size() >> 8);
  24508. frame += static_cast<char>(body.size() & 0xff);
  24509. frame += body;
  24510. detail::BufferStream strm;
  24511. strm.write(frame.data(), frame.size());
  24512. ws::Opcode opcode;
  24513. std::string payload;
  24514. bool fin;
  24515. EXPECT_EQ(
  24516. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24517. ws::impl::FrameRead::Ok);
  24518. EXPECT_EQ(body, payload);
  24519. }
  24520. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24521. // The header announces the largest payload allowed, and only 3 bytes of it
  24522. // ever arrive.
  24523. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24524. std::string frame;
  24525. frame += static_cast<char>(0x82); // FIN + Binary
  24526. frame += static_cast<char>(127); // 64-bit length follows
  24527. for (int shift = 56; shift >= 0; shift -= 8) {
  24528. frame += static_cast<char>((len >> shift) & 0xff);
  24529. }
  24530. frame += "abc";
  24531. detail::BufferStream strm;
  24532. strm.write(frame.data(), frame.size());
  24533. ws::Opcode opcode;
  24534. std::string payload;
  24535. bool fin;
  24536. EXPECT_EQ(
  24537. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24538. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24539. ws::impl::FrameRead::Fail);
  24540. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24541. }
  24542. TEST(WebSocketTest, QueryStringInHandshake) {
  24543. Server svr;
  24544. std::mutex mtx;
  24545. std::string received_target;
  24546. std::string received_token;
  24547. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24548. {
  24549. std::lock_guard<std::mutex> lock(mtx);
  24550. received_target = req.target;
  24551. if (req.has_param("token")) {
  24552. received_token = req.get_param_value("token");
  24553. }
  24554. }
  24555. std::string msg;
  24556. while (ws.read(msg)) {
  24557. ws.send(msg);
  24558. }
  24559. });
  24560. auto port = svr.bind_to_any_port("localhost");
  24561. std::thread t([&]() { svr.listen_after_bind(); });
  24562. svr.wait_until_ready();
  24563. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24564. "/ws?token=ABC&session=123");
  24565. ASSERT_TRUE(client.connect());
  24566. // Round-trip ensures the handler has run and captured the request.
  24567. ASSERT_TRUE(client.send("hello"));
  24568. std::string msg;
  24569. ASSERT_TRUE(client.read(msg));
  24570. EXPECT_EQ("hello", msg);
  24571. client.close();
  24572. {
  24573. std::lock_guard<std::mutex> lock(mtx);
  24574. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24575. EXPECT_EQ("ABC", received_token);
  24576. }
  24577. svr.stop();
  24578. t.join();
  24579. }
  24580. // Run a handshake against a throwaway server and hand the request the server
  24581. // received back to the caller, so tests can assert on the headers the client
  24582. // actually put on the wire.
  24583. static void capture_websocket_handshake_request(
  24584. const Headers &client_headers,
  24585. std::function<void(const Request &, int port)> verify) {
  24586. Server svr;
  24587. std::mutex mtx;
  24588. Request received;
  24589. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24590. {
  24591. std::lock_guard<std::mutex> lock(mtx);
  24592. received = req;
  24593. }
  24594. std::string msg;
  24595. while (ws.read(msg)) {
  24596. ws.send(msg);
  24597. }
  24598. });
  24599. auto port = svr.bind_to_any_port("localhost");
  24600. std::thread t([&]() { svr.listen_after_bind(); });
  24601. auto se = detail::scope_exit([&] {
  24602. svr.stop();
  24603. t.join();
  24604. });
  24605. svr.wait_until_ready();
  24606. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24607. client_headers);
  24608. ASSERT_TRUE(client.connect());
  24609. ASSERT_TRUE(client.send("hello"));
  24610. std::string msg;
  24611. ASSERT_TRUE(client.read(msg));
  24612. client.close();
  24613. {
  24614. std::lock_guard<std::mutex> lock(mtx);
  24615. verify(received, port);
  24616. }
  24617. }
  24618. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24619. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24620. // Non-default port must be present in the Host header. Default ports
  24621. // (80/443) are omitted; that logic is covered by
  24622. // MakeHostAndPortStringTest.
  24623. EXPECT_EQ("localhost:" + std::to_string(port),
  24624. req.get_header_value("Host"));
  24625. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24626. req.get_header_value("User-Agent"));
  24627. EXPECT_FALSE(req.has_header("Accept"));
  24628. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24629. EXPECT_FALSE(req.has_header("Content-Length"));
  24630. });
  24631. }
  24632. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24633. capture_websocket_handshake_request(
  24634. {{"Host", "example.com"},
  24635. {"User-Agent", "custom-agent"},
  24636. {"X-Custom", "value"}},
  24637. [](const Request &req, int) {
  24638. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24639. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24640. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24641. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24642. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24643. });
  24644. }
  24645. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24646. capture_websocket_handshake_request(
  24647. {{"Upgrade", "bogus"},
  24648. {"Connection", "close"},
  24649. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24650. {"Sec-WebSocket-Version", "8"}},
  24651. [](const Request &req, int) {
  24652. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24653. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24654. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24655. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24656. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24657. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24658. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24659. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24660. req.get_header_value("Sec-WebSocket-Key"));
  24661. });
  24662. }
  24663. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24664. // A header the client refuses to send must abort the handshake before any
  24665. // part of it reaches the wire; a lone request line would otherwise sit in
  24666. // the peer's buffer as a truncated request.
  24667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24668. ASSERT_NE(INVALID_SOCKET, srv);
  24669. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24670. sockaddr_in addr{};
  24671. addr.sin_family = AF_INET;
  24672. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24673. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24674. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24675. ASSERT_EQ(0, ::listen(srv, 1));
  24676. sockaddr_in bound{};
  24677. socklen_t bound_len = sizeof(bound);
  24678. ASSERT_EQ(
  24679. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24680. auto port = ntohs(bound.sin_port);
  24681. ssize_t received = -1;
  24682. std::thread t([&] {
  24683. // Bound every blocking call so a regression fails the test with a bad
  24684. // value instead of hanging the suite.
  24685. fd_set rfds;
  24686. FD_ZERO(&rfds);
  24687. FD_SET(srv, &rfds);
  24688. timeval tv{5, 0};
  24689. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24690. 0) {
  24691. return;
  24692. }
  24693. sockaddr_in cli_addr{};
  24694. socklen_t cli_len = sizeof(cli_addr);
  24695. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24696. if (cli == INVALID_SOCKET) { return; }
  24697. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24698. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24699. char buf[4096];
  24700. received = ::recv(cli, buf, sizeof(buf), 0);
  24701. });
  24702. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24703. // connect() has already shut the socket down by the time it returns false,
  24704. // so the peer sees EOF without waiting for the client to be destroyed.
  24705. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24706. {{"X-Bad", "a\r\nInjected: 1"}});
  24707. EXPECT_FALSE(client.connect());
  24708. t.join();
  24709. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24710. EXPECT_EQ(0, received);
  24711. }
  24712. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24713. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24714. // contains "upgrade" as a substring is a different token and must not
  24715. // start a WebSocket handshake.
  24716. auto make_request = [](const std::vector<std::string> &connection_values) {
  24717. Request req;
  24718. req.method = "GET";
  24719. req.headers.emplace("Upgrade", "websocket");
  24720. for (const auto &value : connection_values) {
  24721. req.headers.emplace("Connection", value);
  24722. }
  24723. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24724. req.headers.emplace("Sec-WebSocket-Version", "13");
  24725. return req;
  24726. };
  24727. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24728. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24729. EXPECT_TRUE(
  24730. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24731. EXPECT_TRUE(
  24732. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24733. EXPECT_TRUE(
  24734. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24735. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24736. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24737. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24738. EXPECT_FALSE(
  24739. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24740. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24741. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24742. }
  24743. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24744. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24745. // asks recipients to match each protocol-name case-insensitively, and RFC
  24746. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24747. // client naming websocket alongside another protocol, or on a second field
  24748. // line, is offering websocket; a value that merely contains "websocket" as a
  24749. // substring is a different protocol name and is not.
  24750. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24751. Request req;
  24752. req.method = "GET";
  24753. for (const auto &value : upgrade_values) {
  24754. req.headers.emplace("Upgrade", value);
  24755. }
  24756. req.headers.emplace("Connection", "Upgrade");
  24757. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24758. req.headers.emplace("Sec-WebSocket-Version", "13");
  24759. return req;
  24760. };
  24761. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24762. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24763. EXPECT_TRUE(
  24764. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24765. EXPECT_TRUE(
  24766. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24767. EXPECT_TRUE(
  24768. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24769. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24770. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24771. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24772. EXPECT_FALSE(
  24773. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24774. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24775. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24776. }
  24777. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24778. Server svr;
  24779. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24780. auto port = svr.bind_to_any_port("localhost");
  24781. std::thread t([&]() { svr.listen_after_bind(); });
  24782. auto se = detail::scope_exit([&] {
  24783. svr.stop();
  24784. t.join();
  24785. });
  24786. svr.wait_until_ready();
  24787. Headers headers = {{"Upgrade", "websocket"},
  24788. {"Connection", "notupgrade"},
  24789. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24790. {"Sec-WebSocket-Version", "13"}};
  24791. Client cli("localhost", port);
  24792. auto res = cli.Get("/ws", headers);
  24793. // The route exists only as a WebSocket route, so a request that fails the
  24794. // handshake check falls through to ordinary routing.
  24795. ASSERT_TRUE(res);
  24796. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24797. }
  24798. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24799. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24800. // Connection value is the only thing left for the client to reject.
  24801. Server svr;
  24802. svr.Get("/ws", [](const Request &req, Response &res) {
  24803. res.status = StatusCode::SwitchingProtocol_101;
  24804. res.set_header("Upgrade", "websocket");
  24805. res.set_header("Connection", "notupgrade");
  24806. res.set_header("Sec-WebSocket-Accept",
  24807. detail::websocket_accept_key(
  24808. req.get_header_value("Sec-WebSocket-Key")));
  24809. });
  24810. auto port = svr.bind_to_any_port("localhost");
  24811. std::thread t([&]() { svr.listen_after_bind(); });
  24812. auto se = detail::scope_exit([&] {
  24813. svr.stop();
  24814. t.join();
  24815. });
  24816. svr.wait_until_ready();
  24817. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24818. auto res = client.connect();
  24819. EXPECT_FALSE(res);
  24820. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24821. EXPECT_FALSE(client.is_open());
  24822. }
  24823. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24824. Server svr;
  24825. svr.Get("/ws", [](const Request &req, Response &res) {
  24826. res.status = StatusCode::SwitchingProtocol_101;
  24827. res.set_header("Upgrade", "websocket");
  24828. res.set_header("Connection", "Upgrade");
  24829. res.set_header("Sec-WebSocket-Accept",
  24830. detail::websocket_accept_key(
  24831. req.get_header_value("Sec-WebSocket-Key")));
  24832. res.set_header("Sec-WebSocket-Protocol", "admin");
  24833. });
  24834. auto port = svr.bind_to_any_port("localhost");
  24835. std::thread t([&]() { svr.listen_after_bind(); });
  24836. auto se = detail::scope_exit([&] {
  24837. svr.stop();
  24838. t.join();
  24839. });
  24840. svr.wait_until_ready();
  24841. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24842. // Server selects a subprotocol the client never offered
  24843. {
  24844. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24845. ws::WebSocketClient client(url, headers);
  24846. auto res = client.connect();
  24847. EXPECT_FALSE(res);
  24848. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24849. EXPECT_FALSE(client.is_open());
  24850. EXPECT_TRUE(client.subprotocol().empty());
  24851. }
  24852. // Client offered none but the server named one anyway
  24853. {
  24854. ws::WebSocketClient client(url);
  24855. auto res = client.connect();
  24856. EXPECT_FALSE(res);
  24857. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24858. EXPECT_FALSE(client.is_open());
  24859. EXPECT_TRUE(client.subprotocol().empty());
  24860. }
  24861. }
  24862. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24863. // The socket path doubles as the URL host, so it must not contain '/'.
  24864. const char *shard = getenv("GTEST_SHARD_INDEX");
  24865. const std::string sock_path =
  24866. shard ? std::string("httplib-ws-") + shard + ".sock"
  24867. : std::string("httplib-ws.sock");
  24868. std::remove(sock_path.c_str());
  24869. Server svr;
  24870. std::mutex mtx;
  24871. std::string received_host;
  24872. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24873. {
  24874. std::lock_guard<std::mutex> lock(mtx);
  24875. received_host = req.get_header_value("Host");
  24876. }
  24877. std::string msg;
  24878. while (ws.read(msg)) {
  24879. ws.send(msg);
  24880. }
  24881. });
  24882. svr.set_address_family(AF_UNIX);
  24883. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24884. auto se = detail::scope_exit([&] {
  24885. svr.stop();
  24886. t.join();
  24887. std::remove(sock_path.c_str());
  24888. });
  24889. svr.wait_until_ready();
  24890. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24891. client.set_address_family(AF_UNIX);
  24892. ASSERT_TRUE(client.connect());
  24893. ASSERT_TRUE(client.send("hello"));
  24894. std::string msg;
  24895. ASSERT_TRUE(client.read(msg));
  24896. client.close();
  24897. {
  24898. std::lock_guard<std::mutex> lock(mtx);
  24899. // There is no host:port for a Unix socket, so the same "localhost"
  24900. // placeholder the HTTP client uses is expected.
  24901. EXPECT_EQ("localhost", received_host);
  24902. }
  24903. }
  24904. // Two threads must never parse WebSocket frames from the same stream.
  24905. // close() used to read the peer's Close reply with its own frame read, so it
  24906. // raced a reader thread that was in the middle of a payload: the payload loop
  24907. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24908. // so bytes taken by close() were replaced with bytes from further along the
  24909. // stream. The message kept its length and silently changed content.
  24910. //
  24911. // The raw peer below sends a frame header plus part of the payload, waits for
  24912. // the handler to call close(), and only then sends the rest. Whichever thread
  24913. // would win the race for those bytes, the message must arrive intact, because
  24914. // close() must not touch the stream while read() owns it.
  24915. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24916. #ifndef _WIN32
  24917. signal(SIGPIPE, SIG_IGN);
  24918. #endif
  24919. const size_t payload_len = 120; // fits the 7-bit length field
  24920. const size_t prefix_len = 8;
  24921. const int attempts = 8;
  24922. std::string expected(payload_len, '\0');
  24923. for (size_t i = 0; i < payload_len; i++) {
  24924. expected[i] = static_cast<char>('a' + i % 26);
  24925. }
  24926. std::atomic<bool> peer_stalled{false};
  24927. std::atomic<bool> handler_done{false};
  24928. std::mutex received_mutex;
  24929. std::vector<std::string> received;
  24930. // Bound every wait, so a regression fails the test instead of hanging the
  24931. // suite.
  24932. auto wait_for = [](const std::atomic<bool> &flag) {
  24933. for (int i = 0; i < 500 && !flag; i++) {
  24934. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24935. }
  24936. };
  24937. Server svr;
  24938. svr.set_websocket_ping_interval(0);
  24939. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24940. std::thread reader([&]() {
  24941. std::string msg;
  24942. while (ws.read(msg)) {
  24943. std::lock_guard<std::mutex> guard(received_mutex);
  24944. received.push_back(msg);
  24945. }
  24946. });
  24947. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24948. // inside read_websocket_frame() when close() runs.
  24949. wait_for(peer_stalled);
  24950. ws.close();
  24951. reader.join();
  24952. handler_done = true;
  24953. });
  24954. auto port = svr.bind_to_any_port("127.0.0.1");
  24955. std::thread t([&]() { svr.listen_after_bind(); });
  24956. auto se = detail::scope_exit([&] {
  24957. svr.stop();
  24958. t.join();
  24959. });
  24960. svr.wait_until_ready();
  24961. auto send_bytes = [](socket_t s, const std::string &data) {
  24962. #ifdef _WIN32
  24963. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24964. #else
  24965. auto n = ::send(s, data.data(), data.size(), 0);
  24966. #endif
  24967. return n == static_cast<decltype(n)>(data.size());
  24968. };
  24969. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24970. // Every length used here fits the 7-bit length field.
  24971. auto masked_header = [](uint8_t first_byte, size_t len) {
  24972. std::string h;
  24973. h += static_cast<char>(first_byte);
  24974. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24975. h.append(4, '\0'); // mask key
  24976. return h;
  24977. };
  24978. for (int attempt = 0; attempt < attempts; attempt++) {
  24979. peer_stalled = false;
  24980. handler_done = false;
  24981. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24982. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24983. auto se_sock = detail::scope_exit([&] {
  24984. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24985. });
  24986. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24987. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24988. sockaddr_in addr{};
  24989. addr.sin_family = AF_INET;
  24990. addr.sin_port = htons(static_cast<uint16_t>(port));
  24991. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24992. ASSERT_EQ(
  24993. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24994. << "attempt " << attempt;
  24995. ASSERT_TRUE(send_bytes(sock,
  24996. "GET /ws HTTP/1.1\r\n"
  24997. "Host: 127.0.0.1\r\n"
  24998. "Upgrade: websocket\r\n"
  24999. "Connection: Upgrade\r\n"
  25000. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25001. "Sec-WebSocket-Version: 13\r\n"
  25002. "\r\n"))
  25003. << "attempt " << attempt;
  25004. std::string response;
  25005. while (response.find("\r\n\r\n") == std::string::npos) {
  25006. char buf[512];
  25007. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25008. if (n <= 0) { break; }
  25009. response.append(buf, static_cast<size_t>(n));
  25010. }
  25011. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25012. << "attempt " << attempt;
  25013. // Send the header of a Binary message but only the first prefix_len bytes
  25014. // of its payload, leaving the reader thread stalled inside the payload.
  25015. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25016. expected.substr(0, prefix_len)))
  25017. << "attempt " << attempt;
  25018. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25019. peer_stalled = true;
  25020. // Let close() send its Close frame and park in its own read before the
  25021. // rest of the payload arrives, so both threads are waiting for it.
  25022. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25023. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25024. close_frame += static_cast<char>(0x03); // status 1000
  25025. close_frame += static_cast<char>(0xE8);
  25026. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25027. << "attempt " << attempt;
  25028. // Closing the peer releases the reader thread even on the buggy path,
  25029. // where it waits for bytes another thread already consumed.
  25030. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25031. detail::close_socket(sock);
  25032. sock = INVALID_SOCKET;
  25033. wait_for(handler_done);
  25034. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25035. }
  25036. std::lock_guard<std::mutex> guard(received_mutex);
  25037. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25038. << "a message in flight when close() ran was dropped";
  25039. for (size_t i = 0; i < received.size(); i++) {
  25040. EXPECT_EQ(expected, received[i]) << "message " << i;
  25041. }
  25042. }
  25043. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25044. // returning the socket, or INVALID_SOCKET.
  25045. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25046. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25047. if (sock == INVALID_SOCKET) { return sock; }
  25048. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25049. sockaddr_in addr{};
  25050. addr.sin_family = AF_INET;
  25051. addr.sin_port = htons(static_cast<uint16_t>(port));
  25052. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25053. std::string req = "GET " + path +
  25054. " HTTP/1.1\r\n"
  25055. "Host: 127.0.0.1\r\n"
  25056. "Upgrade: websocket\r\n"
  25057. "Connection: Upgrade\r\n"
  25058. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25059. "Sec-WebSocket-Version: 13\r\n"
  25060. "\r\n";
  25061. std::string res;
  25062. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25063. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25064. static_cast<ssize_t>(req.size())) {
  25065. char c;
  25066. while (res.find("\r\n\r\n") == std::string::npos &&
  25067. ::recv(sock, &c, 1, 0) == 1) {
  25068. res += c;
  25069. }
  25070. }
  25071. if (res.find(" 101 ") == std::string::npos) {
  25072. detail::close_socket(sock);
  25073. return INVALID_SOCKET;
  25074. }
  25075. return sock;
  25076. }
  25077. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25078. // The payload must fit the 7-bit length field.
  25079. static std::string masked_frame(uint8_t first_byte,
  25080. const std::string &payload) {
  25081. std::string f;
  25082. f += static_cast<char>(first_byte);
  25083. f += static_cast<char>(0x80 | payload.size());
  25084. f.append(4, '\0');
  25085. return f + payload;
  25086. }
  25087. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25088. std::atomic<bool> done{false};
  25089. std::string received;
  25090. Server svr;
  25091. svr.set_websocket_ping_interval(0);
  25092. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25093. std::string msg;
  25094. if (ws.read(msg) == ws::Binary) { received = msg; }
  25095. done = true;
  25096. });
  25097. auto port = svr.bind_to_any_port("127.0.0.1");
  25098. std::thread t([&]() { svr.listen_after_bind(); });
  25099. auto se = detail::scope_exit([&] {
  25100. svr.stop();
  25101. t.join();
  25102. });
  25103. svr.wait_until_ready();
  25104. auto sock = connect_raw_websocket(port, "/ws");
  25105. ASSERT_NE(INVALID_SOCKET, sock);
  25106. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25107. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25108. masked_frame(0x89, "p") + // FIN + Ping
  25109. masked_frame(0x80, "lo"); // FIN + Continuation
  25110. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25111. for (int i = 0; i < 500 && !done; i++) {
  25112. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25113. }
  25114. ASSERT_TRUE(done);
  25115. EXPECT_EQ("Hello", received);
  25116. // The Ping between the fragments is answered with a Pong.
  25117. char pong[3];
  25118. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25119. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25120. }
  25121. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25122. Server svr;
  25123. svr.set_websocket_ping_interval(-1);
  25124. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25125. std::string msg;
  25126. while (ws.read(msg)) {}
  25127. });
  25128. auto port = svr.bind_to_any_port("127.0.0.1");
  25129. std::thread t([&]() { svr.listen_after_bind(); });
  25130. auto se = detail::scope_exit([&] {
  25131. svr.stop();
  25132. t.join();
  25133. });
  25134. svr.wait_until_ready();
  25135. auto sock = connect_raw_websocket(port, "/ws");
  25136. ASSERT_NE(INVALID_SOCKET, sock);
  25137. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25138. // Nothing comes while the client stays quiet.
  25139. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25140. char c;
  25141. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25142. }
  25143. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25144. // and that has to end a read() already waiting on the peer, on every platform.
  25145. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25146. // The peer sends no pings, and its handler never calls read(), which is
  25147. // where pongs are written.
  25148. std::mutex mutex;
  25149. std::condition_variable cv;
  25150. auto release = false;
  25151. svr.set_websocket_ping_interval(0);
  25152. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25153. std::unique_lock<std::mutex> lock(mutex);
  25154. cv.wait(lock, [&] { return release; });
  25155. });
  25156. auto port = svr.bind_to_any_port(HOST);
  25157. std::thread t([&]() { svr.listen_after_bind(); });
  25158. auto se = detail::scope_exit([&] {
  25159. {
  25160. std::lock_guard<std::mutex> lock(mutex);
  25161. release = true;
  25162. }
  25163. cv.notify_all();
  25164. svr.stop();
  25165. t.join();
  25166. });
  25167. svr.wait_until_ready();
  25168. ws::WebSocketClient client(std::string(scheme) +
  25169. "://localhost:" + std::to_string(port) + "/ws");
  25170. #ifdef CPPHTTPLIB_SSL_ENABLED
  25171. client.enable_server_certificate_verification(false);
  25172. #endif
  25173. // A ping a second, given up on after two go unanswered: about 3s
  25174. client.set_websocket_ping_interval(1);
  25175. client.set_websocket_max_missed_pongs(2);
  25176. // Well past that, so that a read the timeout ends instead stands out
  25177. client.set_read_timeout(10);
  25178. ASSERT_TRUE(client.connect());
  25179. auto start = std::chrono::steady_clock::now();
  25180. std::string msg;
  25181. EXPECT_EQ(ws::Fail, client.read(msg));
  25182. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25183. std::chrono::steady_clock::now() - start)
  25184. .count(),
  25185. 6000);
  25186. EXPECT_FALSE(client.is_open());
  25187. }
  25188. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25189. Server svr;
  25190. check_pong_timeout_ends_read(svr, "ws");
  25191. }
  25192. #ifdef CPPHTTPLIB_SSL_ENABLED
  25193. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25195. ASSERT_TRUE(svr.is_valid());
  25196. check_pong_timeout_ends_read(svr, "wss");
  25197. }
  25198. #endif
  25199. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25200. Server svr;
  25201. svr.set_websocket_ping_interval(0);
  25202. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25203. std::string msg;
  25204. while (ws.read(msg)) {}
  25205. });
  25206. auto port = svr.bind_to_any_port("127.0.0.1");
  25207. std::thread t([&]() { svr.listen_after_bind(); });
  25208. auto se = detail::scope_exit([&] {
  25209. svr.stop();
  25210. t.join();
  25211. });
  25212. svr.wait_until_ready();
  25213. // Each Close payload and the reply it should get: an echo when valid, 1002
  25214. // otherwise.
  25215. std::vector<std::pair<std::string, std::string>> cases = {
  25216. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25217. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25218. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25219. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25220. };
  25221. // Also between the fragments of a message.
  25222. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25223. for (const auto &c : cases) {
  25224. auto sock = connect_raw_websocket(port, "/ws");
  25225. ASSERT_NE(INVALID_SOCKET, sock);
  25226. auto frames = prefix + masked_frame(0x88, c.first);
  25227. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25228. std::string reply;
  25229. char buf[256];
  25230. while (reply.size() < 2 + c.second.size()) {
  25231. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25232. if (n <= 0) { break; }
  25233. reply.append(buf, static_cast<size_t>(n));
  25234. }
  25235. detail::close_socket(sock);
  25236. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25237. c.second,
  25238. reply);
  25239. }
  25240. }
  25241. }
  25242. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25243. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25244. protected:
  25245. void SetUp() override {
  25246. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25247. SERVER_PRIVATE_KEY_FILE);
  25248. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25249. std::string msg;
  25250. ws::ReadResult ret;
  25251. while ((ret = ws.read(msg))) {
  25252. if (ret == ws::Binary) {
  25253. ws.send(msg.data(), msg.size());
  25254. } else {
  25255. ws.send(msg);
  25256. }
  25257. }
  25258. });
  25259. port_ = server_->bind_to_any_port(HOST);
  25260. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25261. server_->wait_until_ready();
  25262. }
  25263. void TearDown() override {
  25264. server_->stop();
  25265. if (server_thread_.joinable()) { server_thread_.join(); }
  25266. }
  25267. std::unique_ptr<SSLServer> server_;
  25268. std::thread server_thread_;
  25269. int port_ = 0;
  25270. };
  25271. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25272. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25273. {
  25274. ws::WebSocketClient client(url);
  25275. client.enable_server_certificate_verification(false);
  25276. auto calls = 0;
  25277. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25278. calls++;
  25279. return false;
  25280. });
  25281. EXPECT_FALSE(client.connect());
  25282. EXPECT_GT(calls, 0);
  25283. }
  25284. {
  25285. ws::WebSocketClient client(url);
  25286. client.enable_server_certificate_verification(false);
  25287. client.set_session_verifier([](tls::session_t) {
  25288. return SSLVerifierResponse::CertificateRejected;
  25289. });
  25290. EXPECT_FALSE(client.connect());
  25291. }
  25292. {
  25293. ws::WebSocketClient client(url);
  25294. client.enable_server_certificate_verification(false);
  25295. client.set_session_verifier([](tls::session_t) {
  25296. return SSLVerifierResponse::CertificateAccepted;
  25297. });
  25298. EXPECT_TRUE(client.connect());
  25299. }
  25300. }
  25301. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25302. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25303. "/ws-echo");
  25304. client.enable_server_certificate_verification(false);
  25305. ASSERT_TRUE(client.connect());
  25306. ASSERT_TRUE(client.is_open());
  25307. ASSERT_TRUE(client.send("Hello WSS"));
  25308. std::string msg;
  25309. EXPECT_EQ(ws::Text, client.read(msg));
  25310. EXPECT_EQ("Hello WSS", msg);
  25311. client.close();
  25312. }
  25313. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25314. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25315. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25316. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25317. // client (without calling close() first) is the only path that runs
  25318. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25319. // bug exactly.
  25320. //
  25321. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25322. // when linked against an instrumented libssl; run under Valgrind to catch it
  25323. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25324. // suite (the freed session otherwise stalls on the close handshake) — this test
  25325. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25326. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25327. {
  25328. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25329. "/ws-echo");
  25330. client.enable_server_certificate_verification(false);
  25331. client.set_read_timeout(2, 0);
  25332. client.set_write_timeout(2, 0);
  25333. ASSERT_TRUE(client.connect());
  25334. ASSERT_TRUE(client.is_open());
  25335. ASSERT_TRUE(client.send("still open"));
  25336. // Intentionally do NOT call client.close(): leaving scope runs
  25337. // shutdown_and_close() with the WebSocket still open, which must send the
  25338. // close frame while the TLS session is still alive.
  25339. }
  25340. }
  25341. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25342. // shutdown_and_close() at the start of connect(), reproducing the same
  25343. // use-after-free within the test body rather than at scope exit. The second
  25344. // connect must succeed and echo, proving the close handshake ran over a live
  25345. // session. See the note above about memory-tool requirements.
  25346. TEST_F(WebSocketSSLIntegrationTest,
  25347. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25348. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25349. "/ws-echo");
  25350. client.enable_server_certificate_verification(false);
  25351. client.set_read_timeout(2, 0);
  25352. client.set_write_timeout(2, 0);
  25353. ASSERT_TRUE(client.connect());
  25354. ASSERT_TRUE(client.is_open());
  25355. ASSERT_TRUE(client.send("still open"));
  25356. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25357. // the still-open connection, which must not touch a freed TLS session.
  25358. ASSERT_TRUE(client.connect());
  25359. ASSERT_TRUE(client.is_open());
  25360. ASSERT_TRUE(client.send("after reconnect"));
  25361. std::string msg;
  25362. EXPECT_EQ(ws::Text, client.read(msg));
  25363. EXPECT_EQ("after reconnect", msg);
  25364. client.close();
  25365. }
  25366. #endif
  25367. #ifdef CPPHTTPLIB_SSL_ENABLED
  25368. class WebSocketSSLCATest : public ::testing::Test {
  25369. protected:
  25370. void SetUp() override {
  25371. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25372. SERVER_PRIVATE_KEY_FILE);
  25373. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25374. std::string msg;
  25375. while (ws.read(msg)) {
  25376. ws.send(msg);
  25377. }
  25378. });
  25379. port_ = server_->bind_to_any_port("127.0.0.1");
  25380. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25381. server_->wait_until_ready();
  25382. }
  25383. void TearDown() override {
  25384. server_->stop();
  25385. if (server_thread_.joinable()) { server_thread_.join(); }
  25386. }
  25387. std::string url() const {
  25388. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25389. }
  25390. std::unique_ptr<SSLServer> server_;
  25391. std::thread server_thread_;
  25392. int port_ = 0;
  25393. };
  25394. // A custom CA loaded as PEM verifies the server with full certificate
  25395. // verification enabled
  25396. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25397. ws::WebSocketClient client(url());
  25398. std::string cert;
  25399. read_file(SERVER_CERT2_FILE, cert);
  25400. client.load_ca_cert_store(cert.c_str(), cert.size());
  25401. ASSERT_TRUE(client.connect());
  25402. ASSERT_TRUE(client.send("hello"));
  25403. std::string msg;
  25404. EXPECT_EQ(ws::Text, client.read(msg));
  25405. EXPECT_EQ("hello", msg);
  25406. client.close();
  25407. }
  25408. // A custom CA that does not cover the server must fail verification (the
  25409. // custom CA is exclusive; system certs are not loaded alongside it)
  25410. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25411. ws::WebSocketClient client(url());
  25412. std::string cert;
  25413. read_file(CLIENT_CA_CERT_FILE, cert);
  25414. client.load_ca_cert_store(cert.c_str(), cert.size());
  25415. auto res = client.connect();
  25416. ASSERT_FALSE(res);
  25417. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25418. EXPECT_EQ(-1, res.status());
  25419. EXPECT_NE(0u, res.ssl_backend_error());
  25420. }
  25421. // The same CA as a file path rather than PEM in memory
  25422. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25423. ws::WebSocketClient client(url());
  25424. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25425. ASSERT_TRUE(client.connect());
  25426. ASSERT_TRUE(client.send("hello"));
  25427. std::string msg;
  25428. EXPECT_EQ(ws::Text, client.read(msg));
  25429. EXPECT_EQ("hello", msg);
  25430. client.close();
  25431. }
  25432. // ...and a CA file that does not cover the server still fails, so it is the
  25433. // path above that decides the outcome
  25434. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25435. ws::WebSocketClient client(url());
  25436. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25437. ASSERT_FALSE(client.connect());
  25438. }
  25439. // Regression test: reconnecting with a native custom CA store used to reuse
  25440. // a store handle the previous TLS context had already freed (use-after-free
  25441. // under the OpenSSL backend). The context now lives as long as the client.
  25442. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25443. ws::WebSocketClient client(url());
  25444. std::string cert;
  25445. read_file(SERVER_CERT2_FILE, cert);
  25446. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25447. ASSERT_TRUE(client.connect());
  25448. client.close();
  25449. ASSERT_TRUE(client.connect());
  25450. ASSERT_TRUE(client.send("again"));
  25451. std::string msg;
  25452. EXPECT_EQ(ws::Text, client.read(msg));
  25453. EXPECT_EQ("again", msg);
  25454. client.close();
  25455. }
  25456. // Regression test: a certificate with a trusted chain but no identity match
  25457. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25458. // verification entirely for IP hosts, so this connection succeeded there.
  25459. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25460. // chain verification while the identity check must still fail.
  25461. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25463. ASSERT_TRUE(svr.is_valid());
  25464. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25465. std::string msg;
  25466. while (ws.read(msg)) {
  25467. ws.send(msg);
  25468. }
  25469. });
  25470. auto port = svr.bind_to_any_port("127.0.0.1");
  25471. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25472. auto se = detail::scope_exit([&] {
  25473. svr.stop();
  25474. t.join();
  25475. });
  25476. svr.wait_until_ready();
  25477. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25478. "/echo");
  25479. std::string cert;
  25480. read_file(SERVER_CERT_FILE, cert);
  25481. client.load_ca_cert_store(cert.c_str(), cert.size());
  25482. ASSERT_FALSE(client.connect());
  25483. }
  25484. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25485. // SNI, so nothing binds the host name to the TLS session. These bind the
  25486. // server to "localhost" instead, the only shape that exercises the SNI and
  25487. // hostname-verification path with certificate verification left enabled.
  25488. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25489. protected:
  25490. void Start(const char *cert_file) {
  25491. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25492. SERVER_PRIVATE_KEY_FILE);
  25493. ASSERT_TRUE(server_->is_valid());
  25494. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25495. std::string msg;
  25496. while (ws.read(msg)) {
  25497. ws.send(msg);
  25498. }
  25499. });
  25500. port_ = server_->bind_to_any_port("localhost");
  25501. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25502. server_->wait_until_ready();
  25503. }
  25504. void TearDown() override {
  25505. if (server_) { server_->stop(); }
  25506. if (server_thread_.joinable()) { server_thread_.join(); }
  25507. }
  25508. std::string url() const {
  25509. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25510. }
  25511. std::unique_ptr<SSLServer> server_;
  25512. std::thread server_thread_;
  25513. int port_ = 0;
  25514. };
  25515. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25516. // out and the connection is usable
  25517. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25518. Start(SERVER_CERT2_FILE);
  25519. ws::WebSocketClient client(url());
  25520. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25521. ASSERT_TRUE(client.connect());
  25522. ASSERT_TRUE(client.send("hello"));
  25523. std::string msg;
  25524. EXPECT_EQ(ws::Text, client.read(msg));
  25525. EXPECT_EQ("hello", msg);
  25526. client.close();
  25527. }
  25528. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25529. // while the identity check must still reject "localhost"
  25530. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25531. Start(SERVER_CERT_FILE);
  25532. ws::WebSocketClient client(url());
  25533. client.set_ca_cert_path(SERVER_CERT_FILE);
  25534. auto res = client.connect();
  25535. ASSERT_FALSE(res);
  25536. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25537. EXPECT_EQ(-1, res.status());
  25538. }
  25539. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25540. // disabled: the chain is still checked, only the identity check is skipped
  25541. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25542. Start(SERVER_CERT_FILE);
  25543. ws::WebSocketClient client(url());
  25544. client.set_ca_cert_path(SERVER_CERT_FILE);
  25545. client.enable_server_hostname_verification(false);
  25546. ASSERT_TRUE(client.connect());
  25547. ASSERT_TRUE(client.send("hello"));
  25548. std::string msg;
  25549. EXPECT_EQ(ws::Text, client.read(msg));
  25550. EXPECT_EQ("hello", msg);
  25551. client.close();
  25552. }
  25553. // A CA that did not sign the server certificate fails the chain, even though
  25554. // the name would match
  25555. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25556. Start(SERVER_CERT2_FILE);
  25557. ws::WebSocketClient client(url());
  25558. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25559. ASSERT_FALSE(client.connect());
  25560. }
  25561. // With verification disabled, neither the chain nor the name is checked
  25562. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25563. Start(SERVER_CERT_FILE);
  25564. ws::WebSocketClient client(url());
  25565. client.enable_server_certificate_verification(false);
  25566. ASSERT_TRUE(client.connect());
  25567. ASSERT_TRUE(client.send("hello"));
  25568. std::string msg;
  25569. EXPECT_EQ(ws::Text, client.read(msg));
  25570. EXPECT_EQ("hello", msg);
  25571. client.close();
  25572. }
  25573. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25574. protected:
  25575. void SetUp() override {
  25576. server_ = httplib::detail::make_unique<SSLServer>(
  25577. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25578. ASSERT_TRUE(server_->is_valid());
  25579. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25580. std::string msg;
  25581. while (ws.read(msg)) {
  25582. ws.send(msg);
  25583. }
  25584. });
  25585. port_ = server_->bind_to_any_port("localhost");
  25586. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25587. server_->wait_until_ready();
  25588. }
  25589. void TearDown() override {
  25590. server_->stop();
  25591. if (server_thread_.joinable()) { server_thread_.join(); }
  25592. }
  25593. std::string url() const {
  25594. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25595. }
  25596. void ConnectWithClientCert(const std::string &client_cert_file,
  25597. const std::string &client_private_key_file,
  25598. const char *private_key_password) {
  25599. std::string cert_pem, key_pem;
  25600. read_file(client_cert_file, cert_pem);
  25601. read_file(client_private_key_file, key_pem);
  25602. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25603. key_pem.c_str(), key_pem.size(),
  25604. private_key_password};
  25605. ConnectWithPem(pem);
  25606. }
  25607. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25608. ws::WebSocketClient client(url(), pem);
  25609. ASSERT_TRUE(client.is_valid());
  25610. client.enable_server_certificate_verification(false);
  25611. ASSERT_TRUE(client.connect());
  25612. ASSERT_TRUE(client.send("hello"));
  25613. std::string msg;
  25614. EXPECT_EQ(ws::Text, client.read(msg));
  25615. EXPECT_EQ("hello", msg);
  25616. client.close();
  25617. }
  25618. std::unique_ptr<SSLServer> server_;
  25619. std::thread server_thread_;
  25620. int port_ = 0;
  25621. };
  25622. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25623. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25624. }
  25625. // Control for the tests above: the fixture's server really does require a
  25626. // client certificate, so it is the PEM the constructor installed that decides
  25627. // the outcome.
  25628. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25629. ws::WebSocketClient client(url());
  25630. ASSERT_TRUE(client.is_valid());
  25631. client.enable_server_certificate_verification(false);
  25632. EXPECT_FALSE(client.connect());
  25633. }
  25634. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25635. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25636. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25637. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25638. }
  25639. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25640. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25641. std::string cert_pem, key_pem;
  25642. read_file(CLIENT_CERT_FILE, cert_pem);
  25643. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25644. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25645. std::vector<char> key(key_pem.begin(), key_pem.end());
  25646. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25647. key.size(), nullptr};
  25648. ConnectWithPem(pem);
  25649. }
  25650. #endif
  25651. #if !defined(_WIN32)
  25652. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25653. auto secret_dir = std::string("./symlink_test_secret");
  25654. auto served_dir = std::string("./symlink_test_served");
  25655. auto secret_file = secret_dir + "/secret.txt";
  25656. auto symlink_path = served_dir + "/escape";
  25657. // Setup: create directories and files
  25658. mkdir(secret_dir.c_str(), 0755);
  25659. mkdir(served_dir.c_str(), 0755);
  25660. {
  25661. std::ofstream ofs(secret_file);
  25662. ofs << "SECRET_DATA";
  25663. }
  25664. // Create symlink using absolute path so it resolves correctly
  25665. #ifdef PATH_MAX
  25666. char abs_secret[PATH_MAX];
  25667. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25668. #else
  25669. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25670. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25671. ASSERT_NE(nullptr, abs_secret);
  25672. #endif
  25673. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25674. auto se = detail::scope_exit([&] {
  25675. unlink(symlink_path.c_str());
  25676. unlink(secret_file.c_str());
  25677. rmdir(served_dir.c_str());
  25678. rmdir(secret_dir.c_str());
  25679. });
  25680. Server svr;
  25681. svr.set_mount_point("/", served_dir);
  25682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25683. auto se2 = detail::scope_exit([&] {
  25684. svr.stop();
  25685. listen_thread.join();
  25686. });
  25687. svr.wait_until_ready();
  25688. Client cli("localhost", PORT);
  25689. // Symlink pointing outside base dir should be blocked
  25690. auto res = cli.Get("/escape/secret.txt");
  25691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25692. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25693. }
  25694. #endif
  25695. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25696. // "GET /smuggled" request), reads the first response, and only then sends the
  25697. // embedded request as the body. Returns how many times /smuggled ran.
  25698. //
  25699. // The body is sent AFTER receiving the first response (as in the original
  25700. // PoC) so that the stream_line_reader cannot buffer it together with the
  25701. // headers of the first request.
  25702. static int count_smuggled_requests(const std::string &outer_head,
  25703. std::string &first_response) {
  25704. Server svr;
  25705. svr.set_mount_point("/", "./www");
  25706. std::atomic<int> smuggled_count(0);
  25707. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25708. smuggled_count++;
  25709. res.set_content("oops", "text/plain");
  25710. });
  25711. svr.Post("/post", [&](const Request &req, Response &res) {
  25712. res.set_content(req.body, "text/plain");
  25713. });
  25714. auto port = svr.bind_to_any_port("localhost");
  25715. thread t = thread([&] { svr.listen_after_bind(); });
  25716. auto se = detail::scope_exit([&] {
  25717. svr.stop();
  25718. t.join();
  25719. });
  25720. svr.wait_until_ready();
  25721. auto error = Error::Success;
  25722. auto sock = detail::create_client_socket(
  25723. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25724. /*connection_timeout_sec=*/2, 0,
  25725. /*read_timeout_sec=*/2, 0,
  25726. /*write_timeout_sec=*/2, 0, std::string(), error);
  25727. EXPECT_NE(INVALID_SOCKET, sock);
  25728. if (sock == INVALID_SOCKET) { return -1; }
  25729. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25730. // The "smuggled" request will be sent as the body of the outer request
  25731. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25732. "Host: localhost\r\n"
  25733. "Connection: close\r\n"
  25734. "\r\n";
  25735. auto head = outer_head;
  25736. auto len = std::to_string(smuggled.size());
  25737. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25738. pos = head.find("{len}", pos + len.size())) {
  25739. head.replace(pos, 5, len);
  25740. }
  25741. // Step 1: Send only the outer request headers (no body yet)
  25742. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25743. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25744. // Step 2: Read the first response
  25745. char buf[4096];
  25746. for (;;) {
  25747. auto n = recv(sock, buf, sizeof(buf), 0);
  25748. if (n <= 0) break;
  25749. first_response.append(buf, static_cast<size_t>(n));
  25750. // Stop once we have a complete response (headers + body)
  25751. auto hdr_end = first_response.find("\r\n\r\n");
  25752. if (hdr_end != std::string::npos) {
  25753. // Check for Content-Length to know when the body is complete
  25754. auto cl_pos = first_response.find("Content-Length:");
  25755. if (cl_pos != std::string::npos) {
  25756. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25757. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25758. auto cl = std::stoul(
  25759. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25760. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25761. } else {
  25762. break; // No Content-Length, assume headers-only response
  25763. }
  25764. }
  25765. }
  25766. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25767. // vulnerable server the keep-alive loop reads this as a second request. The
  25768. // server may already have closed the connection, so the result is ignored.
  25769. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25770. // Half-close so that a server which drained the body sees EOF and closes,
  25771. // instead of the read below waiting for the read timeout.
  25772. #ifdef _WIN32
  25773. ::shutdown(sock, SD_SEND);
  25774. #else
  25775. ::shutdown(sock, SHUT_WR);
  25776. #endif
  25777. // Step 4: Read until the server closes the connection
  25778. for (;;) {
  25779. auto n = recv(sock, buf, sizeof(buf), 0);
  25780. if (n <= 0) break;
  25781. }
  25782. return smuggled_count.load();
  25783. }
  25784. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25785. // A GET request with Content-Length to a static file handler must have its
  25786. // body drained before the keep-alive connection is reused. Otherwise the
  25787. // unread body bytes are interpreted as the next HTTP request.
  25788. std::string first_response;
  25789. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25790. "Host: localhost\r\n"
  25791. "Content-Length: {len}\r\n"
  25792. "\r\n",
  25793. first_response));
  25794. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25795. }
  25796. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25797. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25798. // be answered with 400 and the connection closed. Treating it as "no body"
  25799. // leaves the body to be parsed as the next request.
  25800. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25801. const char *targets[] = {
  25802. "GET /file", // handler that never reads the body
  25803. "GET /not-found", // no handler matches (404)
  25804. "POST /post", // handler that reads the body
  25805. };
  25806. for (auto target : targets) {
  25807. for (auto value : values) {
  25808. std::string first_response;
  25809. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25810. " HTTP/1.1\r\n"
  25811. "Host: localhost\r\n"
  25812. "Content-Length: " +
  25813. value + "\r\n\r\n",
  25814. first_response))
  25815. << target << " with Content-Length: " << value;
  25816. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25817. << target << " with Content-Length: " << value;
  25818. }
  25819. }
  25820. }
  25821. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25822. // A 400 for an unparseable request line leaves the rest of the message
  25823. // unread, so the connection must be closed rather than reused.
  25824. std::string first_response;
  25825. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25826. "Host: localhost\r\n"
  25827. "Content-Length: {len}\r\n"
  25828. "\r\n",
  25829. first_response));
  25830. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25831. }
  25832. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25833. // Same as above for a header block that fails to parse.
  25834. std::string first_response;
  25835. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25836. "Host: localhost\r\n"
  25837. "Bad Header\r\n"
  25838. "Content-Length: {len}\r\n"
  25839. "\r\n",
  25840. first_response));
  25841. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25842. }
  25843. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25844. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25845. // server must not read another request on that connection, even when the
  25846. // request had no body to drain.
  25847. std::string first_response;
  25848. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25849. "Host: localhost\r\n"
  25850. "\r\n",
  25851. first_response));
  25852. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25853. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25854. }
  25855. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25856. // A content reader that stops early leaves the stream inside the body.
  25857. // Draining the whole Content-Length from there, or reading the body again,
  25858. // reads into the next request, and whatever follows is parsed as a request
  25859. // of its own.
  25860. Server svr;
  25861. std::atomic<int> smuggled_count(0);
  25862. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25863. svr.Post("/upload", [](const Request &req, Response &res,
  25864. const ContentReader &content_reader) {
  25865. // Stop at the last chunk, so the whole body has been read however it
  25866. // arrives.
  25867. auto length = req.get_header_value_u64("Content-Length");
  25868. size_t total = 0;
  25869. auto consumed = content_reader([&](const char *, size_t n) {
  25870. total += n;
  25871. return total < length;
  25872. });
  25873. EXPECT_FALSE(consumed);
  25874. if (req.has_param("retry")) {
  25875. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25876. }
  25877. // Replace the 400 the aborted read set, which would close the connection.
  25878. res.set_redirect("/done");
  25879. });
  25880. auto port = svr.bind_to_any_port(HOST);
  25881. thread t = thread([&] { svr.listen_after_bind(); });
  25882. auto se = detail::scope_exit([&] {
  25883. svr.stop();
  25884. t.join();
  25885. });
  25886. svr.wait_until_ready();
  25887. // A front end sees the second request as a POST whose body is the GET. The
  25888. // first body is as long as the POST's headers, so draining it again reads
  25889. // exactly those and leaves the GET to be parsed next.
  25890. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25891. "Host: localhost\r\n"
  25892. "\r\n";
  25893. std::string second_head = "POST /post HTTP/1.1\r\n"
  25894. "Host: localhost\r\n"
  25895. "Content-Length: " +
  25896. std::to_string(inner.size()) +
  25897. "\r\n"
  25898. "\r\n";
  25899. for (auto target : {"/upload", "/upload?retry"}) {
  25900. smuggled_count = 0;
  25901. std::string request = "POST " + std::string(target) +
  25902. " HTTP/1.1\r\n"
  25903. "Host: localhost\r\n"
  25904. "Content-Length: " +
  25905. std::to_string(second_head.size()) +
  25906. "\r\n"
  25907. "\r\n" +
  25908. std::string(second_head.size(), 'A') + second_head +
  25909. inner;
  25910. std::string response;
  25911. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25912. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25913. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25914. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25915. EXPECT_EQ(0, smuggled_count.load()) << target;
  25916. }
  25917. }
  25918. // An error response closes the connection anyway, so the body is left unread
  25919. // with a redirect, such as one to a login page.
  25920. static void serve_redirects(Server &svr,
  25921. const std::function<void(int)> &client) {
  25922. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25923. res.set_redirect("/login");
  25924. return Server::HandlerResponse::Handled;
  25925. });
  25926. auto port = svr.bind_to_any_port(HOST);
  25927. ASSERT_GT(port, 0);
  25928. thread t = thread([&] { svr.listen_after_bind(); });
  25929. auto se = detail::scope_exit([&] {
  25930. svr.stop();
  25931. t.join();
  25932. ASSERT_FALSE(svr.is_running());
  25933. });
  25934. svr.wait_until_ready();
  25935. client(port);
  25936. }
  25937. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25938. Server svr;
  25939. serve_redirects(svr, [](int port) {
  25940. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25941. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25942. std::to_string(body.size()) + "\r\n\r\n" + body +
  25943. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25944. std::string resp;
  25945. ASSERT_TRUE(send_request(1, req, &resp, port));
  25946. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25947. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25948. });
  25949. }
  25950. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25951. Server svr;
  25952. svr.set_read_timeout(0, 200000);
  25953. serve_redirects(svr, [](int port) {
  25954. // A byte every 100 ms keeps each read within the read timeout, but not the
  25955. // body as a whole, so the server closes and the bytes sent after that fail.
  25956. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25957. "Content-Length: 10\r\n\r\n"};
  25958. parts.resize(11, "x");
  25959. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25960. });
  25961. }
  25962. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25963. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25964. // must be rejected with 400 Bad Request.
  25965. Server svr;
  25966. svr.Post("/test", [&](const Request &, Response &res) {
  25967. res.set_content("ok", "text/plain");
  25968. });
  25969. thread t = thread([&] { svr.listen(HOST, PORT); });
  25970. auto se = detail::scope_exit([&] {
  25971. svr.stop();
  25972. t.join();
  25973. ASSERT_FALSE(svr.is_running());
  25974. });
  25975. svr.wait_until_ready();
  25976. // Exact "chunked"
  25977. {
  25978. auto req = "POST /test HTTP/1.1\r\n"
  25979. "Host: localhost\r\n"
  25980. "Content-Length: 5\r\n"
  25981. "Transfer-Encoding: chunked\r\n"
  25982. "Connection: close\r\n"
  25983. "\r\n"
  25984. "hello";
  25985. std::string response;
  25986. ASSERT_TRUE(send_request(1, req, &response));
  25987. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25988. response.substr(0, response.find("\r\n")));
  25989. }
  25990. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25991. {
  25992. auto req = "POST /test HTTP/1.1\r\n"
  25993. "Host: localhost\r\n"
  25994. "Content-Length: 5\r\n"
  25995. "Transfer-Encoding: gzip, chunked\r\n"
  25996. "Connection: close\r\n"
  25997. "\r\n"
  25998. "hello";
  25999. std::string response;
  26000. ASSERT_TRUE(send_request(1, req, &response));
  26001. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26002. response.substr(0, response.find("\r\n")));
  26003. }
  26004. }
  26005. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26006. Server svr;
  26007. svr.Post("/test", [&](const Request &, Response &res) {
  26008. res.set_content("ok", "text/plain");
  26009. });
  26010. thread t = thread([&] { svr.listen(HOST, PORT); });
  26011. auto se = detail::scope_exit([&] {
  26012. svr.stop();
  26013. t.join();
  26014. ASSERT_FALSE(svr.is_running());
  26015. });
  26016. svr.wait_until_ready();
  26017. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26018. // length cannot be determined, so the server must answer 400 and close
  26019. // rather than treat the request as bodyless and leave the body in the
  26020. // socket for the next request to pick up.
  26021. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26022. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26023. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26024. std::string response;
  26025. ASSERT_TRUE(send_request(1, req, &response));
  26026. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26027. response.substr(0, response.find("\r\n")))
  26028. << transfer_encoding;
  26029. }
  26030. // RFC 9110 5.3: the codings may also be split across several
  26031. // Transfer-Encoding lines, which combine in the order they were received.
  26032. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26033. // just like the single-line "chunked, gzip" above.
  26034. {
  26035. auto req = "POST /test HTTP/1.1\r\n"
  26036. "Host: localhost\r\n"
  26037. "Transfer-Encoding: chunked\r\n"
  26038. "Transfer-Encoding: gzip\r\n"
  26039. "\r\n"
  26040. "0\r\n\r\n";
  26041. std::string response;
  26042. ASSERT_TRUE(send_request(1, req, &response));
  26043. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26044. response.substr(0, response.find("\r\n")));
  26045. }
  26046. }
  26047. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26048. Server svr;
  26049. svr.Post("/test", [&](const Request &, Response &res) {
  26050. res.set_content("ok", "text/plain");
  26051. });
  26052. auto port = svr.bind_to_any_port(HOST);
  26053. ASSERT_GT(port, 0);
  26054. thread t = thread([&] { svr.listen_after_bind(); });
  26055. auto se = detail::scope_exit([&] {
  26056. svr.stop();
  26057. t.join();
  26058. ASSERT_FALSE(svr.is_running());
  26059. });
  26060. svr.wait_until_ready();
  26061. for (auto transfer_encoding :
  26062. {"Transfer-Encoding: gzip, chunked\r\n",
  26063. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26064. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26065. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26066. transfer_encoding + "\r\n0\r\n\r\n";
  26067. std::string response;
  26068. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26069. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26070. response.substr(0, response.find("\r\n")))
  26071. << transfer_encoding;
  26072. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26073. << transfer_encoding;
  26074. }
  26075. }
  26076. // Regression for issue #2450: a DELETE without Content-Length on a
  26077. // keep-alive connection must not let the post-response drain consume the
  26078. // next request's bytes.
  26079. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26080. Server svr;
  26081. std::atomic<int> delete_count(0);
  26082. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26083. delete_count++;
  26084. res.status = StatusCode::NoContent_204;
  26085. });
  26086. auto port = svr.bind_to_any_port(HOST);
  26087. thread t = thread([&] { svr.listen_after_bind(); });
  26088. auto se = detail::scope_exit([&] {
  26089. svr.stop();
  26090. t.join();
  26091. });
  26092. svr.wait_until_ready();
  26093. auto error = Error::Success;
  26094. auto sock = detail::create_client_socket(
  26095. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26096. /*connection_timeout_sec=*/2, 0,
  26097. /*read_timeout_sec=*/2, 0,
  26098. /*write_timeout_sec=*/2, 0, std::string(), error);
  26099. ASSERT_NE(INVALID_SOCKET, sock);
  26100. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26101. auto send_request_and_read_response = [&](const std::string &req,
  26102. std::string &out) -> bool {
  26103. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26104. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26105. char buf[4096];
  26106. for (;;) {
  26107. auto n = recv(sock, buf, sizeof(buf), 0);
  26108. if (n <= 0) { return !out.empty(); }
  26109. out.append(buf, static_cast<size_t>(n));
  26110. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26111. }
  26112. };
  26113. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26114. "Host: localhost\r\n"
  26115. "\r\n";
  26116. std::string resp1;
  26117. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26118. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26119. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26120. "Host: localhost\r\n"
  26121. "Connection: close\r\n"
  26122. "\r\n";
  26123. std::string resp2;
  26124. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26125. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26126. EXPECT_EQ(2, delete_count.load());
  26127. }
  26128. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26129. Server svr;
  26130. svr.Post("/ingest", [&](const Request &, Response &res,
  26131. const ContentReader &content_reader) {
  26132. auto consumed = content_reader([](const char *, size_t) { return false; });
  26133. EXPECT_FALSE(consumed);
  26134. res.status = StatusCode::Conflict_409;
  26135. res.set_header("Connection", "close");
  26136. });
  26137. auto port = svr.bind_to_any_port(HOST);
  26138. thread t = thread([&] { svr.listen_after_bind(); });
  26139. auto se = detail::scope_exit([&] {
  26140. svr.stop();
  26141. t.join();
  26142. });
  26143. svr.wait_until_ready();
  26144. auto error = Error::Success;
  26145. auto sock = detail::create_client_socket(
  26146. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26147. /*connection_timeout_sec=*/2, 0,
  26148. /*read_timeout_sec=*/1, 0,
  26149. /*write_timeout_sec=*/2, 0, std::string(), error);
  26150. ASSERT_NE(INVALID_SOCKET, sock);
  26151. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26152. std::string request = "POST /ingest HTTP/1.1\r\n"
  26153. "Host: localhost\r\n"
  26154. "Transfer-Encoding: chunked\r\n"
  26155. "\r\n"
  26156. "4\r\n"
  26157. "data\r\n";
  26158. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26159. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26160. std::string response;
  26161. ssize_t received = 0;
  26162. do {
  26163. char buf[4096];
  26164. received = recv(sock, buf, sizeof(buf), 0);
  26165. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26166. } while (received > 0);
  26167. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26168. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26169. EXPECT_EQ(0, received);
  26170. }
  26171. namespace no_proxy_test {
  26172. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26173. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26174. // calling listen().
  26175. class ScopedServer {
  26176. public:
  26177. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26178. ~ScopedServer() {
  26179. svr_.stop();
  26180. if (th_.joinable()) { th_.join(); }
  26181. }
  26182. Server &svr() { return svr_; }
  26183. int port() const { return port_; }
  26184. void listen() {
  26185. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26186. svr_.wait_until_ready();
  26187. }
  26188. private:
  26189. Server svr_;
  26190. std::thread th_;
  26191. int port_ = 0;
  26192. };
  26193. class ProxyAndTargetServers {
  26194. public:
  26195. ProxyAndTargetServers() {
  26196. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26197. proxy_hits_++;
  26198. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26199. res.set_content("via-proxy", "text/plain");
  26200. });
  26201. target_.Get(".*", [this](const Request &req, Response &res) {
  26202. target_hits_++;
  26203. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26204. res.set_content("direct", "text/plain");
  26205. });
  26206. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26207. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26208. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26209. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26210. proxy_mock_.wait_until_ready();
  26211. target_.wait_until_ready();
  26212. }
  26213. ~ProxyAndTargetServers() {
  26214. proxy_mock_.stop();
  26215. target_.stop();
  26216. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26217. if (target_thread_.joinable()) { target_thread_.join(); }
  26218. }
  26219. Server &proxy_mock() { return proxy_mock_; }
  26220. Server &target() { return target_; }
  26221. int proxy_port() const { return proxy_port_; }
  26222. int target_port() const { return target_port_; }
  26223. int proxy_hits() const { return proxy_hits_.load(); }
  26224. int target_hits() const { return target_hits_.load(); }
  26225. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26226. void reset_counters() {
  26227. proxy_hits_ = 0;
  26228. target_hits_ = 0;
  26229. last_had_proxy_authz_ = false;
  26230. }
  26231. private:
  26232. Server proxy_mock_;
  26233. Server target_;
  26234. std::thread proxy_thread_;
  26235. std::thread target_thread_;
  26236. int proxy_port_ = 0;
  26237. int target_port_ = 0;
  26238. std::atomic<int> proxy_hits_{0};
  26239. std::atomic<int> target_hits_{0};
  26240. std::atomic<bool> last_had_proxy_authz_{false};
  26241. };
  26242. inline std::unique_ptr<Client> make_client(const std::string &host,
  26243. ProxyAndTargetServers &s) {
  26244. auto cli = detail::make_unique<Client>(host, s.target_port());
  26245. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26246. cli->set_proxy("127.0.0.1", s.proxy_port());
  26247. return cli;
  26248. }
  26249. } // namespace no_proxy_test
  26250. using no_proxy_test::make_client;
  26251. using no_proxy_test::ProxyAndTargetServers;
  26252. // A stream request carries the credentials a buffered request does
  26253. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26254. no_proxy_test::ScopedServer origin;
  26255. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26256. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26257. });
  26258. origin.listen();
  26259. Client cli("127.0.0.1", origin.port());
  26260. cli.set_basic_auth("user", "pass");
  26261. auto handle = cli.open_stream("GET", "/x");
  26262. ASSERT_TRUE(handle.is_valid());
  26263. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26264. Client bearer("127.0.0.1", origin.port());
  26265. bearer.set_bearer_token_auth("tok");
  26266. auto handle2 = bearer.open_stream("GET", "/x");
  26267. ASSERT_TRUE(handle2.is_valid());
  26268. EXPECT_EQ("Bearer tok", read_all(handle2));
  26269. }
  26270. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26271. // takes its own credentials, as for a buffered request
  26272. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26273. std::string target, authz, proxy_authz;
  26274. no_proxy_test::ScopedServer proxy;
  26275. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26276. target = req.target;
  26277. authz = req.get_header_value("Authorization");
  26278. proxy_authz = req.get_header_value("Proxy-Authorization");
  26279. res.set_content("ok", "text/plain");
  26280. });
  26281. proxy.listen();
  26282. Client cli("origin.example", 8080);
  26283. cli.set_proxy("127.0.0.1", proxy.port());
  26284. cli.set_proxy_basic_auth("puser", "ppass");
  26285. cli.set_basic_auth("user", "pass");
  26286. auto handle = cli.open_stream("GET", "/x");
  26287. ASSERT_TRUE(handle.is_valid());
  26288. EXPECT_EQ("ok", read_all(handle));
  26289. EXPECT_EQ("http://origin.example:8080/x", target);
  26290. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26291. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26292. }
  26293. // In absolute-form the path follows the authority, so a path that does not
  26294. // begin with '/' would make the proxy connect to another host
  26295. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26296. std::vector<std::string> targets;
  26297. no_proxy_test::ScopedServer proxy;
  26298. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26299. targets.push_back(req.target);
  26300. res.set_content("ok", "text/plain");
  26301. });
  26302. proxy.listen();
  26303. Client cli("origin.example", 8080);
  26304. cli.set_proxy("127.0.0.1", proxy.port());
  26305. cli.set_basic_auth("user", "pass");
  26306. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26307. auto res = cli.Get(path);
  26308. EXPECT_FALSE(res) << path;
  26309. auto handle = cli.open_stream("GET", path);
  26310. EXPECT_FALSE(handle.is_valid()) << path;
  26311. }
  26312. EXPECT_TRUE(targets.empty());
  26313. auto res = cli.Get("/x");
  26314. ASSERT_TRUE(res);
  26315. ASSERT_EQ(1u, targets.size());
  26316. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26317. }
  26318. TEST(NoProxyTest, ExactHostnameBypasses) {
  26319. ProxyAndTargetServers s;
  26320. auto cli = make_client("example.com", s);
  26321. cli->set_no_proxy({"example.com"});
  26322. auto res = cli->Get("/");
  26323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26324. EXPECT_EQ(0, s.proxy_hits());
  26325. EXPECT_EQ(1, s.target_hits());
  26326. }
  26327. TEST(NoProxyTest, SubdomainBypasses) {
  26328. ProxyAndTargetServers s;
  26329. auto cli = make_client("foo.example.com", s);
  26330. cli->set_no_proxy({"example.com"});
  26331. auto res = cli->Get("/");
  26332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26333. EXPECT_EQ(0, s.proxy_hits());
  26334. EXPECT_EQ(1, s.target_hits());
  26335. }
  26336. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26337. // Regression guard: "evilexample.com" must not be considered a subdomain
  26338. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26339. // check would let traffic bypass the proxy and leak credentials direct
  26340. // to the attacker host.
  26341. ProxyAndTargetServers s;
  26342. auto cli = make_client("evilexample.com", s);
  26343. cli->set_no_proxy({"example.com"});
  26344. auto res = cli->Get("/");
  26345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26346. EXPECT_GE(s.proxy_hits(), 1);
  26347. EXPECT_EQ(0, s.target_hits());
  26348. }
  26349. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26350. ProxyAndTargetServers s;
  26351. auto cli = make_client("example.com.evil.com", s);
  26352. cli->set_no_proxy({"example.com"});
  26353. auto res = cli->Get("/");
  26354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26355. EXPECT_GE(s.proxy_hits(), 1);
  26356. EXPECT_EQ(0, s.target_hits());
  26357. }
  26358. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26359. ProxyAndTargetServers s;
  26360. auto cli = make_client("example.com", s);
  26361. cli->set_no_proxy({".example.com"});
  26362. auto res = cli->Get("/");
  26363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26364. EXPECT_EQ(0, s.proxy_hits());
  26365. EXPECT_EQ(1, s.target_hits());
  26366. }
  26367. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26368. ProxyAndTargetServers s;
  26369. auto cli = make_client("Example.COM", s);
  26370. cli->set_no_proxy({"EXAMPLE.com"});
  26371. auto res = cli->Get("/");
  26372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26373. EXPECT_EQ(0, s.proxy_hits());
  26374. EXPECT_EQ(1, s.target_hits());
  26375. }
  26376. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26377. ProxyAndTargetServers s;
  26378. auto cli = make_client("example.com.", s);
  26379. cli->set_no_proxy({"example.com"});
  26380. auto res = cli->Get("/");
  26381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26382. EXPECT_EQ(0, s.proxy_hits());
  26383. EXPECT_EQ(1, s.target_hits());
  26384. }
  26385. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26386. // Trailing dots must be normalized on BOTH sides — host and entry.
  26387. // An implementation that only strips the host-side trailing dot would
  26388. // fail to match host "example.com" against entry "example.com." because
  26389. // a literal substring search would compare 11 chars against 12.
  26390. ProxyAndTargetServers s;
  26391. auto cli = make_client("example.com", s);
  26392. cli->set_no_proxy({"example.com."});
  26393. auto res = cli->Get("/");
  26394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26395. EXPECT_EQ(0, s.proxy_hits());
  26396. EXPECT_EQ(1, s.target_hits());
  26397. }
  26398. TEST(NoProxyTest, WildcardBypassesEverything) {
  26399. ProxyAndTargetServers s;
  26400. auto cli = make_client("anything.invalid.test", s);
  26401. cli->set_no_proxy({"*"});
  26402. auto res = cli->Get("/");
  26403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26404. EXPECT_EQ(0, s.proxy_hits());
  26405. EXPECT_EQ(1, s.target_hits());
  26406. }
  26407. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26408. ProxyAndTargetServers s;
  26409. Client cli("127.0.0.1", s.target_port());
  26410. cli.set_proxy("127.0.0.1", s.proxy_port());
  26411. cli.set_no_proxy({"127.0.0.1"});
  26412. auto res = cli.Get("/");
  26413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26414. EXPECT_EQ(0, s.proxy_hits());
  26415. EXPECT_EQ(1, s.target_hits());
  26416. }
  26417. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26418. ProxyAndTargetServers s;
  26419. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26420. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26421. cli.set_proxy("127.0.0.1", s.proxy_port());
  26422. cli.set_no_proxy({"::1"});
  26423. auto res = cli.Get("/");
  26424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26425. EXPECT_EQ(0, s.proxy_hits());
  26426. EXPECT_EQ(1, s.target_hits());
  26427. }
  26428. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26429. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26430. // must still be recognized as IPv6 for CIDR matching. Implementations
  26431. // that detect IPv6 only when the host begins with '[' would parse the
  26432. // host as a hostname and miss the match.
  26433. ProxyAndTargetServers s;
  26434. Client cli("fe80::1", s.target_port());
  26435. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26436. cli.set_proxy("127.0.0.1", s.proxy_port());
  26437. cli.set_no_proxy({"fe80::/10"});
  26438. auto res = cli.Get("/");
  26439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26440. EXPECT_EQ(0, s.proxy_hits());
  26441. EXPECT_EQ(1, s.target_hits());
  26442. }
  26443. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26444. ProxyAndTargetServers s;
  26445. Client cli("::1", s.target_port());
  26446. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26447. cli.set_proxy("127.0.0.1", s.proxy_port());
  26448. cli.set_no_proxy({"[::1]"});
  26449. auto res = cli.Get("/");
  26450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26451. EXPECT_EQ(0, s.proxy_hits());
  26452. EXPECT_EQ(1, s.target_hits());
  26453. }
  26454. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26455. ProxyAndTargetServers s;
  26456. Client cli("fe80::1", s.target_port());
  26457. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26458. cli.set_proxy("127.0.0.1", s.proxy_port());
  26459. cli.set_no_proxy({"[fe80::]/10"});
  26460. auto res = cli.Get("/");
  26461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26462. EXPECT_EQ(0, s.proxy_hits());
  26463. EXPECT_EQ(1, s.target_hits());
  26464. }
  26465. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26466. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26467. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26468. // tricks via address-family conversion.
  26469. ProxyAndTargetServers s;
  26470. Client cli("::ffff:127.0.0.1", s.target_port());
  26471. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26472. cli.set_proxy("127.0.0.1", s.proxy_port());
  26473. cli.set_no_proxy({"127.0.0.1"});
  26474. auto res = cli.Get("/");
  26475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26476. EXPECT_GE(s.proxy_hits(), 1);
  26477. EXPECT_EQ(0, s.target_hits());
  26478. }
  26479. TEST(NoProxyTest, IPv4CidrMatch) {
  26480. ProxyAndTargetServers s;
  26481. Client cli("127.0.0.1", s.target_port());
  26482. cli.set_proxy("127.0.0.1", s.proxy_port());
  26483. cli.set_no_proxy({"127.0.0.0/8"});
  26484. auto res = cli.Get("/");
  26485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26486. EXPECT_EQ(0, s.proxy_hits());
  26487. EXPECT_EQ(1, s.target_hits());
  26488. }
  26489. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26490. ProxyAndTargetServers s;
  26491. Client cli("127.0.0.1", s.target_port());
  26492. cli.set_proxy("127.0.0.1", s.proxy_port());
  26493. cli.set_no_proxy({"10.0.0.0/8"});
  26494. auto res = cli.Get("/");
  26495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26496. EXPECT_GE(s.proxy_hits(), 1);
  26497. EXPECT_EQ(0, s.target_hits());
  26498. }
  26499. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26500. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26501. // IPv4 target matches.
  26502. ProxyAndTargetServers s;
  26503. Client cli("127.0.0.1", s.target_port());
  26504. cli.set_proxy("127.0.0.1", s.proxy_port());
  26505. cli.set_no_proxy({"0.0.0.0/0"});
  26506. auto res = cli.Get("/");
  26507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26508. EXPECT_EQ(0, s.proxy_hits());
  26509. EXPECT_EQ(1, s.target_hits());
  26510. }
  26511. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26512. ProxyAndTargetServers s;
  26513. Client cli("127.0.0.1", s.target_port());
  26514. cli.set_proxy("127.0.0.1", s.proxy_port());
  26515. cli.set_no_proxy({"127.0.0.1"});
  26516. auto res = cli.Get("/");
  26517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26518. EXPECT_EQ(0, s.proxy_hits());
  26519. EXPECT_EQ(1, s.target_hits());
  26520. }
  26521. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26522. ProxyAndTargetServers s;
  26523. Client cli("127.0.0.1", s.target_port());
  26524. cli.set_proxy("127.0.0.1", s.proxy_port());
  26525. cli.set_no_proxy({"127.0.0.0/33"});
  26526. auto res = cli.Get("/");
  26527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26528. EXPECT_GE(s.proxy_hits(), 1);
  26529. EXPECT_EQ(0, s.target_hits());
  26530. }
  26531. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26532. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26533. ProxyAndTargetServers s;
  26534. Client cli("127.0.0.1", s.target_port());
  26535. cli.set_proxy("127.0.0.1", s.proxy_port());
  26536. cli.set_no_proxy({"127.0.0.1/"});
  26537. auto res = cli.Get("/");
  26538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26539. EXPECT_GE(s.proxy_hits(), 1);
  26540. EXPECT_EQ(0, s.target_hits());
  26541. }
  26542. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26543. ProxyAndTargetServers s;
  26544. auto cli = make_client("internal.corp", s);
  26545. cli->set_proxy_basic_auth("u", "p");
  26546. cli->set_no_proxy({"internal.corp"});
  26547. auto res = cli->Get("/");
  26548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26549. EXPECT_EQ(1, s.target_hits());
  26550. EXPECT_EQ(0, s.proxy_hits());
  26551. EXPECT_FALSE(s.last_had_proxy_authz())
  26552. << "Proxy-Authorization must not be sent direct to the target";
  26553. }
  26554. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26555. ProxyAndTargetServers s;
  26556. auto cli = make_client("public.example", s);
  26557. cli->set_proxy_basic_auth("u", "p");
  26558. cli->set_no_proxy({"internal.corp"}); // does not match
  26559. auto res = cli->Get("/");
  26560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26561. EXPECT_GE(s.proxy_hits(), 1);
  26562. EXPECT_TRUE(s.last_had_proxy_authz());
  26563. }
  26564. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26565. std::atomic<int> hits{0};
  26566. std::atomic<int> hits_with_authz{0};
  26567. no_proxy_test::ScopedServer proxy_mock;
  26568. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26569. hits++;
  26570. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26571. if (req.target.find("/redir") != std::string::npos) {
  26572. res.set_redirect("http://other.example/landed");
  26573. } else {
  26574. res.set_content("via-proxy", "text/plain");
  26575. }
  26576. });
  26577. proxy_mock.listen();
  26578. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26579. hits = 0;
  26580. hits_with_authz = 0;
  26581. Client cli("public.example", 80);
  26582. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26583. cli.set_proxy_basic_auth(c.first, c.second);
  26584. cli.set_follow_location(true);
  26585. // The redirect to another host goes through the proxy as well
  26586. auto res = cli.Get("/redir");
  26587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26588. EXPECT_EQ(2, hits.load());
  26589. EXPECT_EQ(2, hits_with_authz.load());
  26590. }
  26591. }
  26592. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26593. ProxyAndTargetServers s;
  26594. auto cli = make_client("anything.test", s);
  26595. auto res = cli->Get("/");
  26596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26597. EXPECT_GE(s.proxy_hits(), 1);
  26598. EXPECT_EQ(0, s.target_hits());
  26599. }
  26600. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26601. ProxyAndTargetServers s;
  26602. auto cli = make_client("example.com", s);
  26603. cli->set_no_proxy({"example.com:8080"});
  26604. auto res = cli->Get("/");
  26605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26606. EXPECT_GE(s.proxy_hits(), 1);
  26607. EXPECT_EQ(0, s.target_hits());
  26608. }
  26609. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26610. ProxyAndTargetServers s;
  26611. auto cli = make_client("anything.test", s);
  26612. cli->set_no_proxy({"", " ", "\t"});
  26613. auto res = cli->Get("/");
  26614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26615. EXPECT_GE(s.proxy_hits(), 1);
  26616. EXPECT_EQ(0, s.target_hits());
  26617. }
  26618. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26619. // An entry with leading/trailing whitespace must still match — env-style
  26620. // values are commonly pasted with stray spaces and an implementation
  26621. // that feeds the raw token directly to inet_pton would fail to match
  26622. // valid CIDRs because of the spaces.
  26623. ProxyAndTargetServers s;
  26624. Client cli("127.0.0.1", s.target_port());
  26625. cli.set_proxy("127.0.0.1", s.proxy_port());
  26626. cli.set_no_proxy({" 127.0.0.0/8 "});
  26627. auto res = cli.Get("/");
  26628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26629. EXPECT_EQ(0, s.proxy_hits());
  26630. EXPECT_EQ(1, s.target_hits());
  26631. }
  26632. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26633. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26634. // go direct and must NOT carry Proxy-Authorization.
  26635. std::atomic<int> proxy_hits{0};
  26636. std::atomic<int> target_hits{0};
  26637. std::atomic<bool> target_saw_authz{false};
  26638. no_proxy_test::ScopedServer proxy_mock, target;
  26639. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26640. proxy_hits++;
  26641. res.status = 302;
  26642. res.set_header("Location", "http://127.0.0.1:" +
  26643. std::to_string(target.port()) + "/landed");
  26644. });
  26645. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26646. target_hits++;
  26647. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26648. res.set_content("direct", "text/plain");
  26649. });
  26650. proxy_mock.listen();
  26651. target.listen();
  26652. Client cli("public.example", target.port());
  26653. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26654. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26655. cli.set_proxy_basic_auth("u", "p");
  26656. cli.set_no_proxy({"127.0.0.1"});
  26657. cli.set_follow_location(true);
  26658. auto res = cli.Get("/redir");
  26659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26660. EXPECT_GE(proxy_hits.load(), 1);
  26661. EXPECT_GE(target_hits.load(), 1);
  26662. EXPECT_FALSE(target_saw_authz.load());
  26663. }
  26664. #ifdef CPPHTTPLIB_SSL_ENABLED
  26665. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26666. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26667. // proxy creds would be sent to the (possibly hostile) origin.
  26668. std::atomic<int> target_hits{0};
  26669. std::atomic<bool> target_saw_proxy_authz{false};
  26670. no_proxy_test::ScopedServer target;
  26671. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26672. target_hits++;
  26673. if (req.has_header("Proxy-Authorization")) {
  26674. target_saw_proxy_authz = true;
  26675. }
  26676. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26677. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26678. "nonce=\"abc\", algorithm=MD5");
  26679. });
  26680. target.listen();
  26681. // The proxy address is set to the target's port: the bypass MUST kick in;
  26682. // if it doesn't, the test still routes "via proxy" to the same server and
  26683. // the Proxy-Authorization assertion below catches the leak.
  26684. Client cli("evil.example", target.port());
  26685. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26686. cli.set_proxy("127.0.0.1", target.port());
  26687. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26688. cli.set_no_proxy({"evil.example"});
  26689. auto res = cli.Get("/x");
  26690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26691. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26692. EXPECT_EQ(1, target_hits.load());
  26693. EXPECT_FALSE(target_saw_proxy_authz.load());
  26694. }
  26695. #endif
  26696. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26697. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26698. std::atomic<int> proxy_hits{0};
  26699. std::atomic<int> bypass_hits{0};
  26700. std::atomic<bool> proxy_saw_c_url{false};
  26701. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26702. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26703. proxy_hits++;
  26704. if (req.path.find("/start") != std::string::npos) {
  26705. res.status = 302;
  26706. res.set_header("Location", "http://127.0.0.1:" +
  26707. std::to_string(bypass_server.port()) +
  26708. "/middle");
  26709. return;
  26710. }
  26711. if (req.path.find("/end") != std::string::npos) {
  26712. proxy_saw_c_url = true;
  26713. res.set_content("c-via-proxy", "text/plain");
  26714. return;
  26715. }
  26716. res.set_content("unexpected", "text/plain");
  26717. });
  26718. // public.example's "advertised" port is arbitrary (the request never lands
  26719. // there — it goes through the proxy), but use a dynamic value to stay
  26720. // friendly with sharded parallel runs.
  26721. int public_port = bypass_server.port();
  26722. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26723. bypass_hits++;
  26724. res.status = 302;
  26725. res.set_header("Location", "http://public.example:" +
  26726. std::to_string(public_port) + "/end");
  26727. });
  26728. proxy_mock.listen();
  26729. bypass_server.listen();
  26730. Client cli("public.example", public_port);
  26731. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26732. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26733. cli.set_no_proxy({"127.0.0.1"});
  26734. cli.set_follow_location(true);
  26735. auto res = cli.Get("/start");
  26736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26737. EXPECT_EQ(StatusCode::OK_200, res->status);
  26738. EXPECT_EQ("c-via-proxy", res->body);
  26739. EXPECT_GE(proxy_hits.load(), 2);
  26740. EXPECT_GE(bypass_hits.load(), 1);
  26741. EXPECT_TRUE(proxy_saw_c_url.load());
  26742. }
  26743. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26744. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26745. // request reconnects to the correct endpoint.
  26746. std::atomic<int> proxy_hits{0};
  26747. std::atomic<int> target_hits{0};
  26748. no_proxy_test::ScopedServer proxy_mock, target;
  26749. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26750. proxy_hits++;
  26751. res.set_content("via-proxy", "text/plain");
  26752. });
  26753. target.svr().Get(".*", [&](const Request &, Response &res) {
  26754. target_hits++;
  26755. res.set_content("direct", "text/plain");
  26756. });
  26757. proxy_mock.listen();
  26758. target.listen();
  26759. Client cli("public.example", target.port());
  26760. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26761. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26762. cli.set_keep_alive(true);
  26763. auto res1 = cli.Get("/a");
  26764. ASSERT_TRUE(res1);
  26765. EXPECT_EQ("via-proxy", res1->body);
  26766. EXPECT_EQ(1, proxy_hits.load());
  26767. EXPECT_EQ(0, target_hits.load());
  26768. cli.set_no_proxy({"public.example"});
  26769. auto res2 = cli.Get("/b");
  26770. ASSERT_TRUE(res2);
  26771. EXPECT_EQ("direct", res2->body);
  26772. EXPECT_EQ(1, proxy_hits.load());
  26773. EXPECT_EQ(1, target_hits.load());
  26774. }
  26775. // Forward declarations (see the base64_encode note).
  26776. namespace httplib {
  26777. namespace detail {
  26778. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26779. int shutdown_socket(socket_t sock) noexcept;
  26780. } // namespace detail
  26781. } // namespace httplib
  26782. namespace proxy_tunnel_test {
  26783. const char *const kTunnelEstablished =
  26784. "HTTP/1.1 200 Connection established\r\n\r\n";
  26785. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26786. using ConnectReply = std::function<std::string(const std::string &head)>;
  26787. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26788. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26789. class ScopedConnectProxy {
  26790. public:
  26791. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26792. : forward_port_(forward_port), reply_(std::move(reply)) {
  26793. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26794. if (listen_sock_ == INVALID_SOCKET) { return; }
  26795. auto a = loopback(0);
  26796. auto addr = reinterpret_cast<sockaddr *>(&a);
  26797. socklen_t alen = sizeof(a);
  26798. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26799. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26800. ::listen(listen_sock_, 4) != 0) {
  26801. return;
  26802. }
  26803. port_ = ntohs(a.sin_port);
  26804. th_ = std::thread([this] { run(); });
  26805. }
  26806. ~ScopedConnectProxy() {
  26807. if (th_.joinable()) {
  26808. stop_ = true;
  26809. auto wake = connect_to(port_);
  26810. th_.join();
  26811. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26812. }
  26813. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26814. }
  26815. int port() const { return port_; }
  26816. int connect_hits() const { return connect_hits_.load(); }
  26817. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26818. std::string connect_request() const {
  26819. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26820. return connect_request_;
  26821. }
  26822. private:
  26823. static sockaddr_in loopback(int port) {
  26824. sockaddr_in a{};
  26825. a.sin_family = AF_INET;
  26826. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26827. a.sin_port = htons(static_cast<unsigned short>(port));
  26828. return a;
  26829. }
  26830. static socket_t connect_to(int port) {
  26831. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26832. if (sock == INVALID_SOCKET) { return sock; }
  26833. auto a = loopback(port);
  26834. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26835. detail::close_socket(sock);
  26836. return INVALID_SOCKET;
  26837. }
  26838. return sock;
  26839. }
  26840. static bool send_all(socket_t sock, const char *data, size_t size) {
  26841. while (size > 0) {
  26842. auto n = detail::send_socket(sock, data, size, 0);
  26843. if (n <= 0) { return false; }
  26844. data += n;
  26845. size -= static_cast<size_t>(n);
  26846. }
  26847. return true;
  26848. }
  26849. void run() {
  26850. for (;;) {
  26851. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26852. if (stop_) {
  26853. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26854. return;
  26855. }
  26856. if (client == INVALID_SOCKET) { continue; }
  26857. serve(client);
  26858. detail::close_socket(client);
  26859. }
  26860. }
  26861. void serve(socket_t client) {
  26862. std::string head;
  26863. char buf[2048];
  26864. while (head.find("\r\n\r\n") == std::string::npos) {
  26865. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26866. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26867. if (n <= 0) { return; }
  26868. head.append(buf, static_cast<size_t>(n));
  26869. }
  26870. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26871. connect_hits_++;
  26872. {
  26873. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26874. connect_request_ = head;
  26875. }
  26876. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26877. if (!send_all(client, res.data(), res.size()) ||
  26878. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26879. return;
  26880. }
  26881. auto origin = connect_to(forward_port_);
  26882. if (origin == INVALID_SOCKET) { return; }
  26883. // When either side stops, shut both down so the other pump returns too.
  26884. auto pump = [&](socket_t from, socket_t to) {
  26885. char b[8192];
  26886. for (;;) {
  26887. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26888. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26889. }
  26890. detail::shutdown_socket(client);
  26891. detail::shutdown_socket(origin);
  26892. };
  26893. std::thread up([&] { pump(client, origin); });
  26894. pump(origin, client);
  26895. up.join();
  26896. detail::close_socket(origin);
  26897. }
  26898. int forward_port_;
  26899. ConnectReply reply_;
  26900. socket_t listen_sock_ = INVALID_SOCKET;
  26901. int port_ = 0;
  26902. std::thread th_;
  26903. std::atomic<bool> stop_{false};
  26904. std::atomic<int> connect_hits_{0};
  26905. mutable std::mutex connect_request_mutex_;
  26906. std::string connect_request_;
  26907. };
  26908. } // namespace proxy_tunnel_test
  26909. #ifdef CPPHTTPLIB_SSL_ENABLED
  26910. namespace proxy_tunnel_test {
  26911. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26912. class ScopedSSLServer {
  26913. public:
  26914. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26915. port_ = svr_.bind_to_any_port("127.0.0.1");
  26916. }
  26917. ~ScopedSSLServer() {
  26918. svr_.stop();
  26919. if (th_.joinable()) { th_.join(); }
  26920. }
  26921. SSLServer &svr() { return svr_; }
  26922. int port() const { return port_; }
  26923. void listen() {
  26924. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26925. svr_.wait_until_ready();
  26926. }
  26927. private:
  26928. SSLServer svr_;
  26929. std::thread th_;
  26930. int port_ = 0;
  26931. };
  26932. // Sends one request through the CONNECT proxy to the TLS origin with a
  26933. // credential configured for each hop, and checks that each credential reaches
  26934. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26935. // origin's (every header in origin_headers) on the tunnelled request.
  26936. void CredentialsStayWithTheirHop(
  26937. const std::function<void(SSLClient &)> &set_credentials,
  26938. const std::string &scheme,
  26939. const std::vector<std::string> &origin_headers = {"Authorization"},
  26940. bool stream = false) {
  26941. std::atomic<int> origin_hits{0};
  26942. std::atomic<bool> origin_saw_proxy_authz{false};
  26943. std::atomic<bool> origin_saw_headers{false};
  26944. ScopedSSLServer origin;
  26945. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26946. origin_hits++;
  26947. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26948. origin_saw_headers =
  26949. std::all_of(origin_headers.begin(), origin_headers.end(),
  26950. [&](const std::string &h) { return req.has_header(h); });
  26951. res.set_content("ok", "text/plain");
  26952. });
  26953. origin.listen();
  26954. ScopedConnectProxy proxy(origin.port());
  26955. ASSERT_NE(0, proxy.port());
  26956. // Pinned to 127.0.0.1 for the same reason as the test below.
  26957. SSLClient cli("127.0.0.1", origin.port());
  26958. cli.enable_server_certificate_verification(false);
  26959. cli.set_proxy("127.0.0.1", proxy.port());
  26960. set_credentials(cli);
  26961. if (stream) {
  26962. auto handle = cli.open_stream("GET", "/x");
  26963. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26964. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26965. } else {
  26966. auto res = cli.Get("/x");
  26967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26968. EXPECT_EQ(StatusCode::OK_200, res->status);
  26969. }
  26970. EXPECT_EQ(1, origin_hits.load());
  26971. EXPECT_EQ(1, proxy.connect_hits());
  26972. EXPECT_TRUE(origin_saw_headers.load());
  26973. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26974. << "Proxy-Authorization must not be sent inside the tunnel";
  26975. auto connect_req = proxy.connect_request();
  26976. EXPECT_NE(std::string::npos,
  26977. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26978. for (const auto &h : origin_headers) {
  26979. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26980. << h << " must not be sent to the proxy on CONNECT";
  26981. }
  26982. }
  26983. } // namespace proxy_tunnel_test
  26984. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26985. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26986. [](SSLClient &cli) {
  26987. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26988. cli.set_basic_auth("origin-user", "origin-pass");
  26989. },
  26990. "Basic");
  26991. }
  26992. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26993. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26994. [](SSLClient &cli) {
  26995. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26996. cli.set_basic_auth("origin-user", "origin-pass");
  26997. },
  26998. "Basic", {"Authorization"}, true);
  26999. }
  27000. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27001. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27002. [](SSLClient &cli) {
  27003. cli.set_proxy_bearer_token_auth("proxy-token");
  27004. cli.set_bearer_token_auth("origin-token");
  27005. },
  27006. "Bearer");
  27007. }
  27008. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27009. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27010. [](SSLClient &cli) {
  27011. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27012. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27013. {"Cookie", "sid=origin-session"},
  27014. {"X-Api-Key", "origin-key"}});
  27015. },
  27016. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27017. }
  27018. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27019. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27020. // retry; otherwise proxy creds would be sent to the origin.
  27021. std::atomic<int> origin_hits{0};
  27022. std::atomic<bool> origin_saw_proxy_authz{false};
  27023. proxy_tunnel_test::ScopedSSLServer origin;
  27024. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27025. origin_hits++;
  27026. if (req.has_header("Proxy-Authorization")) {
  27027. origin_saw_proxy_authz = true;
  27028. }
  27029. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27030. res.set_header("Proxy-Authenticate",
  27031. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27032. "algorithm=MD5");
  27033. });
  27034. origin.listen();
  27035. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27036. ASSERT_NE(0, proxy.port());
  27037. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27038. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27039. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27040. // and answer with its own status, making this test flaky.
  27041. SSLClient cli("127.0.0.1", origin.port());
  27042. cli.enable_server_certificate_verification(false);
  27043. cli.set_proxy("127.0.0.1", proxy.port());
  27044. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27045. auto res = cli.Get("/x");
  27046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27047. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27048. EXPECT_EQ(1, origin_hits.load());
  27049. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27050. EXPECT_EQ(1, proxy.connect_hits());
  27051. }
  27052. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27053. std::string origin_sni;
  27054. std::string origin_host;
  27055. proxy_tunnel_test::ScopedSSLServer origin;
  27056. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27057. origin_sni = req.sni();
  27058. origin_host = req.get_header_value("Host");
  27059. res.set_content("ok", "text/plain");
  27060. });
  27061. origin.listen();
  27062. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27063. ASSERT_NE(0, proxy.port());
  27064. SSLClient cli("origin.example", origin.port());
  27065. cli.enable_server_certificate_verification(false);
  27066. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27067. cli.set_proxy("127.0.0.1", proxy.port());
  27068. auto res = cli.Get("/x");
  27069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27070. EXPECT_EQ(StatusCode::OK_200, res->status);
  27071. auto port = std::to_string(origin.port());
  27072. auto target = "127.0.0.1:" + port;
  27073. auto connect_req = proxy.connect_request();
  27074. EXPECT_EQ(1, proxy.connect_hits());
  27075. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27076. EXPECT_NE(std::string::npos,
  27077. connect_req.find("\r\nHost: " + target + "\r\n"));
  27078. EXPECT_EQ("origin.example", origin_sni);
  27079. EXPECT_EQ("origin.example:" + port, origin_host);
  27080. }
  27081. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27082. proxy_tunnel_test::ScopedSSLServer origin;
  27083. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27084. res.set_content("ok", "text/plain");
  27085. });
  27086. origin.listen();
  27087. proxy_tunnel_test::ScopedConnectProxy proxy(
  27088. origin.port(), [](const std::string &head) -> std::string {
  27089. if (head.find(
  27090. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27091. std::string::npos) {
  27092. return proxy_tunnel_test::kTunnelEstablished;
  27093. }
  27094. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27095. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27096. "nonce=\"abc\", algorithm=MD5\r\n"
  27097. "Content-Length: 0\r\n\r\n";
  27098. });
  27099. ASSERT_NE(0, proxy.port());
  27100. SSLClient cli("origin.example", origin.port());
  27101. cli.enable_server_certificate_verification(false);
  27102. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27103. cli.set_proxy("127.0.0.1", proxy.port());
  27104. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27105. auto res = cli.Get("/x");
  27106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27107. EXPECT_EQ(StatusCode::OK_200, res->status);
  27108. // The retried CONNECT is the one the proxy saw last.
  27109. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27110. auto connect_req = proxy.connect_request();
  27111. EXPECT_EQ(2, proxy.connect_hits());
  27112. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27113. EXPECT_NE(std::string::npos,
  27114. connect_req.find("\r\nHost: " + target + "\r\n"));
  27115. }
  27116. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27117. proxy_tunnel_test::ScopedSSLServer origin;
  27118. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27119. res.set_content("ok", "text/plain");
  27120. });
  27121. origin.listen();
  27122. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27123. ASSERT_NE(0, proxy.port());
  27124. SSLClient cli("origin.example", origin.port());
  27125. cli.enable_server_certificate_verification(false);
  27126. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27127. cli.set_proxy("127.0.0.1", proxy.port());
  27128. auto res = cli.Get("/x");
  27129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27130. EXPECT_EQ(StatusCode::OK_200, res->status);
  27131. auto target = "origin.example:" + std::to_string(origin.port());
  27132. auto connect_req = proxy.connect_request();
  27133. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27134. EXPECT_NE(std::string::npos,
  27135. connect_req.find("\r\nHost: " + target + "\r\n"));
  27136. }
  27137. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27138. proxy_tunnel_test::ScopedSSLServer origin;
  27139. auto port = std::to_string(origin.port());
  27140. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27141. res.set_redirect("https://next.example:" + port + "/y");
  27142. });
  27143. origin.svr().Get("/y", [](const Request &, Response &res) {
  27144. res.set_content("ok", "text/plain");
  27145. });
  27146. origin.listen();
  27147. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27148. ASSERT_NE(0, proxy.port());
  27149. SSLClient cli("origin.example", origin.port());
  27150. cli.enable_server_certificate_verification(false);
  27151. cli.set_tunnel_hostname_addr_map(
  27152. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27153. cli.set_proxy("127.0.0.1", proxy.port());
  27154. cli.set_follow_location(true);
  27155. auto res = cli.Get("/x");
  27156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27157. EXPECT_EQ("ok", res->body);
  27158. // The last CONNECT is the redirect client's.
  27159. ASSERT_EQ(2, proxy.connect_hits());
  27160. auto target = "127.0.0.1:" + port;
  27161. auto connect_req = proxy.connect_request();
  27162. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27163. EXPECT_NE(std::string::npos,
  27164. connect_req.find("\r\nHost: " + target + "\r\n"));
  27165. }
  27166. #endif
  27167. namespace proxy_tunnel_test {
  27168. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27169. // anything else gets a 407 with `challenge`.
  27170. ConnectReply require_proxy_auth(const std::string &expected,
  27171. const std::string &challenge) {
  27172. return [=](const std::string &head) -> std::string {
  27173. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27174. std::string::npos) {
  27175. return kTunnelEstablished;
  27176. }
  27177. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27178. "Proxy-Authenticate: " +
  27179. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27180. };
  27181. }
  27182. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27183. // request, then echoes.
  27184. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27185. ws.send(
  27186. "authorization:" + req.get_header_value("Authorization") +
  27187. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27188. std::string msg;
  27189. while (ws.read(msg)) {
  27190. ws.send(msg);
  27191. }
  27192. }
  27193. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27194. class ScopedWebSocketOrigin {
  27195. public:
  27196. ScopedWebSocketOrigin() {
  27197. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27198. server_.listen();
  27199. }
  27200. int port() const { return server_.port(); }
  27201. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27202. std::string url() const {
  27203. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27204. }
  27205. private:
  27206. no_proxy_test::ScopedServer server_;
  27207. };
  27208. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27209. // passed as a constructor header, and checks that each reaches only its hop.
  27210. void WebSocketCredentialsStayWithTheirHop(
  27211. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27212. const std::string &proxy_authz, const std::string &origin_authz) {
  27213. ScopedWebSocketOrigin origin;
  27214. ScopedConnectProxy proxy(
  27215. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27216. ASSERT_NE(0, proxy.port());
  27217. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27218. client.set_proxy("127.0.0.1", proxy.port());
  27219. set_proxy_credentials(client);
  27220. auto res = client.connect();
  27221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27222. std::string msg;
  27223. ASSERT_TRUE(client.read(msg));
  27224. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27225. client.close();
  27226. EXPECT_EQ(1, proxy.connect_hits());
  27227. EXPECT_EQ(std::string::npos,
  27228. proxy.connect_request().find("\r\nAuthorization: "))
  27229. << "origin credentials must not be sent to the proxy";
  27230. }
  27231. } // namespace proxy_tunnel_test
  27232. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27233. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27234. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27235. ASSERT_NE(0, proxy.port());
  27236. ws::WebSocketClient client(origin.url());
  27237. client.set_proxy("127.0.0.1", proxy.port());
  27238. auto res = client.connect();
  27239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27240. std::string msg;
  27241. ASSERT_TRUE(client.read(msg));
  27242. ASSERT_TRUE(client.send("hello"));
  27243. ASSERT_TRUE(client.read(msg));
  27244. EXPECT_EQ("hello", msg);
  27245. client.close();
  27246. EXPECT_EQ(1, proxy.connect_hits());
  27247. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27248. auto connect_req = proxy.connect_request();
  27249. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27250. EXPECT_NE(std::string::npos,
  27251. connect_req.find("\r\nHost: " + target + "\r\n"));
  27252. }
  27253. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27254. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27255. [](ws::WebSocketClient &cli) {
  27256. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27257. },
  27258. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27259. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27260. }
  27261. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27262. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27263. [](ws::WebSocketClient &cli) {
  27264. cli.set_proxy_bearer_token_auth("proxy-token");
  27265. },
  27266. "Bearer proxy-token", "Bearer origin-token");
  27267. }
  27268. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27269. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27270. proxy_tunnel_test::ScopedConnectProxy proxy(
  27271. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27272. "Basic " + detail::base64_encode("proxy-user:"),
  27273. "Basic realm=\"proxy\""));
  27274. ASSERT_NE(0, proxy.port());
  27275. ws::WebSocketClient client(origin.url());
  27276. client.set_proxy("127.0.0.1", proxy.port());
  27277. client.set_proxy_basic_auth("proxy-user", "");
  27278. auto res = client.connect();
  27279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27280. client.close();
  27281. EXPECT_EQ(1, proxy.connect_hits());
  27282. }
  27283. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27284. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27285. proxy_tunnel_test::ScopedConnectProxy proxy(
  27286. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27287. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27288. ASSERT_NE(0, proxy.port());
  27289. ws::WebSocketClient client(origin.url());
  27290. client.set_proxy("127.0.0.1", proxy.port());
  27291. auto res = client.connect();
  27292. EXPECT_FALSE(res);
  27293. EXPECT_EQ(Error::ProxyConnection, res.error());
  27294. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27295. EXPECT_EQ("Basic realm=\"proxy\"",
  27296. res.get_header_value("Proxy-Authenticate"));
  27297. EXPECT_FALSE(client.is_open());
  27298. }
  27299. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27300. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27301. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27302. ASSERT_NE(0, proxy.port());
  27303. ws::WebSocketClient client(origin.url());
  27304. client.set_proxy("127.0.0.1", proxy.port());
  27305. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27306. client.set_no_proxy({"127.0.0.1"});
  27307. auto res = client.connect();
  27308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27309. std::string msg;
  27310. ASSERT_TRUE(client.read(msg));
  27311. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27312. << "proxy credentials must not reach a bypassed origin";
  27313. client.close();
  27314. EXPECT_EQ(0, proxy.connect_hits());
  27315. }
  27316. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27317. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27318. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27319. ASSERT_NE(0, proxy.port());
  27320. ws::WebSocketClient client(origin.url());
  27321. client.set_proxy("127.0.0.1", proxy.port());
  27322. ASSERT_TRUE(client.connect());
  27323. ASSERT_TRUE(client.connect());
  27324. client.close();
  27325. EXPECT_EQ(2, proxy.connect_hits());
  27326. }
  27327. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27328. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27329. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27330. ASSERT_NE(0, proxy.port());
  27331. auto port = std::to_string(origin.port());
  27332. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27333. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27334. client.set_proxy("127.0.0.1", proxy.port());
  27335. auto res = client.connect();
  27336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27337. std::string msg;
  27338. ASSERT_TRUE(client.read(msg));
  27339. client.close();
  27340. EXPECT_EQ(1, proxy.connect_hits());
  27341. auto target = "127.0.0.1:" + port;
  27342. auto connect_req = proxy.connect_request();
  27343. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27344. EXPECT_NE(std::string::npos,
  27345. connect_req.find("\r\nHost: " + target + "\r\n"));
  27346. }
  27347. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27348. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27349. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27350. ASSERT_NE(0, proxy.port());
  27351. auto port = std::to_string(origin.port());
  27352. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27353. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27354. client.set_proxy("127.0.0.1", proxy.port());
  27355. auto res = client.connect();
  27356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27357. client.close();
  27358. auto target = "origin.example:" + port;
  27359. auto connect_req = proxy.connect_request();
  27360. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27361. EXPECT_NE(std::string::npos,
  27362. connect_req.find("\r\nHost: " + target + "\r\n"));
  27363. }
  27364. #ifdef CPPHTTPLIB_SSL_ENABLED
  27365. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27366. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27367. proxy_tunnel_test::ScopedConnectProxy proxy(
  27368. origin.port(), [](const std::string &head) -> std::string {
  27369. if (head.find(
  27370. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27371. std::string::npos) {
  27372. return proxy_tunnel_test::kTunnelEstablished;
  27373. }
  27374. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27375. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27376. "nonce=\"abc\", algorithm=MD5\r\n"
  27377. "Content-Length: 0\r\n\r\n";
  27378. });
  27379. ASSERT_NE(0, proxy.port());
  27380. ws::WebSocketClient client(origin.url());
  27381. client.set_proxy("127.0.0.1", proxy.port());
  27382. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27383. auto res = client.connect();
  27384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27385. std::string msg;
  27386. ASSERT_TRUE(client.read(msg));
  27387. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27388. client.close();
  27389. EXPECT_EQ(2, proxy.connect_hits());
  27390. }
  27391. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27392. proxy_tunnel_test::ScopedSSLServer origin;
  27393. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27394. origin.listen();
  27395. proxy_tunnel_test::ScopedConnectProxy proxy(
  27396. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27397. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27398. ASSERT_NE(0, proxy.port());
  27399. ws::WebSocketClient client(
  27400. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27401. client.enable_server_certificate_verification(false);
  27402. client.set_proxy("127.0.0.1", proxy.port());
  27403. client.set_proxy_bearer_token_auth("proxy-token");
  27404. auto res = client.connect();
  27405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27406. std::string msg;
  27407. ASSERT_TRUE(client.read(msg));
  27408. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27409. << "Proxy-Authorization must not be sent inside the tunnel";
  27410. client.close();
  27411. EXPECT_EQ(1, proxy.connect_hits());
  27412. }
  27413. #endif