1
0

test.cc 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100
  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. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  253. // Another socket in the working directory, which a Location can name as
  254. // its host
  255. const auto other_path = "other-" + pathname_.substr(2);
  256. httplib::Server svr;
  257. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  258. // An absolute Location naming the Host this client sends
  259. res.set_redirect("http://localhost" + pattern_);
  260. });
  261. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  262. res.set_redirect("http://" + other_path + pattern_);
  263. });
  264. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  265. res.set_redirect("http://mapped.test" + pattern_);
  266. });
  267. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  268. res.set_header("X-Auth", req.get_header_value("Authorization"));
  269. res.set_content(content_, "text/plain");
  270. });
  271. httplib::Server other;
  272. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  273. res.set_content("other", "text/plain");
  274. });
  275. std::thread t{[&] {
  276. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  277. }};
  278. std::thread t2{[&] {
  279. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  280. }};
  281. auto se = detail::scope_exit([&] {
  282. svr.stop();
  283. other.stop();
  284. t.join();
  285. t2.join();
  286. std::remove(other_path.c_str());
  287. });
  288. svr.wait_until_ready();
  289. other.wait_until_ready();
  290. httplib::Client cli{pathname_};
  291. cli.set_address_family(AF_UNIX);
  292. cli.set_follow_location(true);
  293. cli.set_bearer_token_auth("token");
  294. // Another host: the same socket, without the credentials
  295. auto res = cli.Get("/cross");
  296. ASSERT_TRUE(res) << "error: " << res.error();
  297. EXPECT_EQ(StatusCode::OK_200, res->status);
  298. EXPECT_EQ(content_, res->body);
  299. EXPECT_EQ("", res->get_header_value("X-Auth"));
  300. // localhost is this client's own host
  301. res = cli.Get("/redirect");
  302. ASSERT_TRUE(res) << "error: " << res.error();
  303. EXPECT_EQ(StatusCode::OK_200, res->status);
  304. EXPECT_EQ(content_, res->body);
  305. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  306. // A host the caller mapped to a socket goes there
  307. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  308. res = cli.Get("/mapped");
  309. ASSERT_TRUE(res) << "error: " << res.error();
  310. EXPECT_EQ(StatusCode::OK_200, res->status);
  311. EXPECT_EQ("other", res->body);
  312. }
  313. #ifndef _WIN32
  314. TEST(SocketStream, wait_writable_UNIX) {
  315. int fds[2];
  316. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  317. const auto asSocketStream = [&](socket_t fd,
  318. std::function<bool(Stream &)> func) {
  319. return detail::process_client_socket(
  320. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  321. };
  322. asSocketStream(fds[0], [&](Stream &s0) {
  323. EXPECT_EQ(s0.socket(), fds[0]);
  324. EXPECT_TRUE(s0.wait_writable());
  325. EXPECT_TRUE(s0.is_peer_alive());
  326. EXPECT_EQ(0, close(fds[1]));
  327. EXPECT_FALSE(s0.is_peer_alive());
  328. return true;
  329. });
  330. EXPECT_EQ(0, close(fds[0]));
  331. }
  332. TEST(SocketStream, wait_writable_INET) {
  333. sockaddr_in addr;
  334. memset(&addr, 0, sizeof(addr));
  335. addr.sin_family = AF_INET;
  336. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  337. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  338. int disconnected_svr_sock = -1;
  339. std::thread svr{[&] {
  340. const int s = socket(AF_INET, SOCK_STREAM, 0);
  341. ASSERT_LE(0, s);
  342. // PORT + 1 is shared with the SSL redirect tests and with
  343. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  344. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  345. // because that happens on a worker thread the ASSERT does not stop the
  346. // test: it runs on and fails at the disconnected_svr_sock check instead.
  347. default_socket_options(s);
  348. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  349. ASSERT_EQ(0, listen(s, 1));
  350. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  351. ASSERT_EQ(0, close(s));
  352. }};
  353. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  354. std::thread cli{[&] {
  355. const int s = socket(AF_INET, SOCK_STREAM, 0);
  356. ASSERT_LE(0, s);
  357. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  358. ASSERT_EQ(0, close(s));
  359. }};
  360. cli.join();
  361. svr.join();
  362. ASSERT_NE(disconnected_svr_sock, -1);
  363. const auto asSocketStream = [&](socket_t fd,
  364. std::function<bool(Stream &)> func) {
  365. return detail::process_client_socket(
  366. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  367. };
  368. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  369. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  370. // wait_writable() returns true because select_write() only checks if the
  371. // send buffer has space. Peer disconnection is detected later by send().
  372. EXPECT_TRUE(ss.wait_writable());
  373. return true;
  374. });
  375. ASSERT_EQ(0, close(disconnected_svr_sock));
  376. }
  377. #endif // #ifndef _WIN32
  378. TEST(SetSocketOptTest, TcpNoDelay) {
  379. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  380. ASSERT_NE(sock, INVALID_SOCKET);
  381. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  382. int val = 0;
  383. socklen_t len = sizeof(val);
  384. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  385. reinterpret_cast<char *>(&val), &len));
  386. EXPECT_NE(val, 0);
  387. detail::close_socket(sock);
  388. }
  389. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  390. // accept() reports failures through WSAGetLastError() on Windows and through
  391. // errno everywhere else. Asking the wrong one is what made the accept loop
  392. // treat every recoverable failure as fatal on Windows.
  393. struct Classification {
  394. bool resource;
  395. bool transient;
  396. };
  397. auto classify = [](int err) {
  398. #ifdef _WIN32
  399. WSASetLastError(err);
  400. #else
  401. errno = err;
  402. #endif
  403. // Read both before asserting: an assertion may clobber the error slot.
  404. Classification c;
  405. c.resource = detail::is_accept_resource_error();
  406. c.transient = detail::is_accept_transient_error();
  407. return c;
  408. };
  409. #ifdef _WIN32
  410. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  411. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  412. WSAECONNRESET, WSAECONNABORTED};
  413. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  414. #else
  415. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  416. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  417. ECONNABORTED};
  418. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  419. #endif
  420. for (auto err : resource_errors) {
  421. const auto c = classify(err);
  422. EXPECT_TRUE(c.resource) << "error " << err;
  423. EXPECT_FALSE(c.transient) << "error " << err;
  424. }
  425. for (auto err : transient_errors) {
  426. const auto c = classify(err);
  427. EXPECT_TRUE(c.transient) << "error " << err;
  428. EXPECT_FALSE(c.resource) << "error " << err;
  429. }
  430. for (auto err : fatal_errors) {
  431. const auto c = classify(err);
  432. EXPECT_FALSE(c.resource) << "error " << err;
  433. EXPECT_FALSE(c.transient) << "error " << err;
  434. }
  435. #ifdef _WIN32
  436. WSASetLastError(0);
  437. #else
  438. errno = 0;
  439. #endif
  440. }
  441. TEST(ClientTest, MoveConstructible) {
  442. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  443. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  444. }
  445. TEST(ClientTest, MoveAssignable) {
  446. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  447. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  448. }
  449. #ifdef _WIN32
  450. TEST(StartupTest, WSAStartup) {
  451. WSADATA wsaData;
  452. int ret = WSAStartup(0x0002, &wsaData);
  453. ASSERT_EQ(0, ret);
  454. }
  455. #endif
  456. TEST(DecodePathTest, PercentCharacter) {
  457. EXPECT_EQ(
  458. decode_path_component(
  459. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  460. U8("descrip=Gastos áéíóúñÑ 6"));
  461. }
  462. TEST(DecodePathTest, PercentCharacterNUL) {
  463. string expected;
  464. expected.push_back('x');
  465. expected.push_back('\0');
  466. expected.push_back('x');
  467. EXPECT_EQ(decode_path_component("x%00x"), expected);
  468. }
  469. TEST(DecodePathTest, UnicodeEncoding) {
  470. // %u0041 = 'A' (1-byte UTF-8)
  471. EXPECT_EQ("A", decode_path_component("%u0041"));
  472. // %u00E9 = 'é' (2-byte UTF-8)
  473. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  474. // %u3042 = 'あ' (3-byte UTF-8)
  475. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  476. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  477. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  478. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  479. // neighbours)
  480. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  481. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  482. }
  483. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  484. // A sign or whitespace inside the two-character escape window must not be
  485. // accepted as a valid percent-encoding; the sequence is passed through
  486. // literally, matching decode_uri_component / decode_path_component.
  487. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  488. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  489. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  490. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  491. // Well-formed escapes still decode.
  492. EXPECT_EQ("-", decode_query_component("%2D", false));
  493. EXPECT_EQ("A", decode_query_component("%41", false));
  494. }
  495. TEST(SanitizeFilenameTest, VariousPatterns) {
  496. // Path traversal
  497. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  498. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  499. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  500. // Normal and edge cases
  501. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  502. EXPECT_EQ("filename.txt",
  503. httplib::sanitize_filename("/path/to/filename.txt"));
  504. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  505. EXPECT_EQ("", httplib::sanitize_filename(".."));
  506. EXPECT_EQ("", httplib::sanitize_filename(""));
  507. // Null bytes stripped
  508. EXPECT_EQ("safe.txt",
  509. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  510. // Whitespace-only rejected
  511. EXPECT_EQ("", httplib::sanitize_filename(" "));
  512. }
  513. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  514. // before it is dropped; anywhere else it is an ordinary file name character.
  515. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  516. #ifdef _WIN32
  517. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  518. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  519. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  520. #else
  521. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  522. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  523. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  524. #endif
  525. }
  526. // Forward declaration (see the base64_encode note below): split builds move the
  527. // definition into httplib.cc, so re-declaring it here lets the test link.
  528. namespace httplib {
  529. namespace detail {
  530. bool is_chunked_transfer_encoding(const Headers &headers);
  531. } // namespace detail
  532. } // namespace httplib
  533. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  534. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  535. auto make = [](std::initializer_list<const char *> lines) {
  536. Headers h;
  537. for (auto te : lines) {
  538. if (te) { h.emplace("Transfer-Encoding", te); }
  539. }
  540. return h;
  541. };
  542. // Sole coding, matched case-insensitively.
  543. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  544. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  545. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  546. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  547. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  548. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  549. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  550. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  551. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  552. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  553. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  554. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  555. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  556. // were received, into one list. Headers preserves that order, so the answer
  557. // is decided by the last coding of the last line and the order the lines
  558. // arrived in is significant.
  559. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  560. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  561. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  562. // The split can fall anywhere in the list.
  563. EXPECT_TRUE(
  564. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  565. EXPECT_FALSE(
  566. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  567. // A trailing line naming no coding leaves the list ending in nothing, so it
  568. // must not inherit the chunked from the line before it.
  569. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  570. }
  571. // Forward declarations (see the base64_encode note below).
  572. namespace httplib {
  573. namespace detail {
  574. bool parse_status_line(const char *line, std::string &version, int &status,
  575. std::string &reason);
  576. std::string file_extension(const std::string &path);
  577. std::string
  578. find_content_type(const std::string &path,
  579. const std::map<std::string, std::string> &user_data,
  580. const std::string &default_content_type);
  581. bool can_compress_content_type(const std::string &content_type);
  582. bool is_prohibited_header_name(const std::string &name);
  583. bool is_valid_path(const std::string &path);
  584. #ifdef CPPHTTPLIB_SSL_ENABLED
  585. bool match_hostname(const std::string &pattern, const std::string &hostname);
  586. #endif
  587. } // namespace detail
  588. } // namespace httplib
  589. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  590. struct {
  591. const char *line;
  592. const char *version;
  593. int status;
  594. const char *reason;
  595. } cases[] = {
  596. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  597. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  598. // The reason phrase may be empty, or left out along with its space.
  599. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  600. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  601. };
  602. for (const auto &c : cases) {
  603. std::string version;
  604. int status = 0;
  605. std::string reason = "unset";
  606. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  607. << c.line;
  608. EXPECT_EQ(c.version, version);
  609. EXPECT_EQ(c.status, status);
  610. EXPECT_EQ(c.reason, reason);
  611. }
  612. }
  613. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  614. const char *lines[] = {
  615. "HTTP/2 200 OK\r\n",
  616. "HTTP/1.2 200 OK\r\n",
  617. "HTTP/1.1 20 OK\r\n",
  618. "HTTP/1.1 2000 OK\r\n",
  619. "HTTP/1.1 2x0 OK\r\n",
  620. "HTTP/1.1 200 OK\r\n",
  621. "HTTP/1.1 200OK\r\n",
  622. "HTTP/1.1 200 O\rK\r\n",
  623. "HTTP/1.1 200 OK",
  624. "HTTP/1.1 200 OK\r\nX",
  625. "",
  626. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  627. "HTTP/1.1 200 OK\n",
  628. #endif
  629. };
  630. for (auto line : lines) {
  631. std::string version;
  632. int status = 0;
  633. std::string reason;
  634. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  635. << line;
  636. }
  637. }
  638. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  639. // Long enough to overflow the stack when matched with std::regex.
  640. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  641. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  642. std::string version;
  643. int status = 0;
  644. std::string reason;
  645. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  646. EXPECT_EQ(200, status);
  647. EXPECT_EQ(long_reason, reason);
  648. }
  649. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  650. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  651. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  652. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  653. EXPECT_EQ("", detail::file_extension("noext"));
  654. EXPECT_EQ("", detail::file_extension("a."));
  655. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  656. EXPECT_EQ("", detail::file_extension("a.b-c"));
  657. // Long enough to overflow the stack when matched with std::regex.
  658. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  659. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  660. }
  661. #ifdef CPPHTTPLIB_SSL_ENABLED
  662. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  663. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  664. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  665. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  666. // A wildcard needs two labels after it, in the leftmost label only
  667. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  668. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  669. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  670. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  671. EXPECT_FALSE(
  672. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  673. // No name may have an empty label
  674. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  675. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  676. }
  677. #endif
  678. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  679. detail::case_ignore::hash hash;
  680. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  681. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  682. // Long enough to overflow the stack if hashed one call per character.
  683. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  684. }
  685. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  686. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  687. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  688. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  689. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  690. // Same 26-bit hash as html, svg and js.
  691. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  692. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  693. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  694. }
  695. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  696. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  697. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  698. }
  699. }
  700. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  701. // name anywhere else.
  702. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  703. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  704. #ifdef _WIN32
  705. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  706. #else
  707. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  708. #endif
  709. }
  710. }
  711. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  712. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  713. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  714. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  715. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  716. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  717. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  718. // Same 26-bit hash as application/json.
  719. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  720. }
  721. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  722. Request req;
  723. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  724. EXPECT_TRUE(req.is_multipart_form_data());
  725. std::string boundary;
  726. EXPECT_TRUE(detail::parse_multipart_boundary(
  727. req.get_header_value("Content-Type"), boundary));
  728. EXPECT_EQ("x", boundary);
  729. }
  730. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  731. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  732. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  733. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  734. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  735. // Same 26-bit hash as REMOTE_ADDR.
  736. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  737. }
  738. // Forward declaration: in split builds split.py strips `inline` and moves the
  739. // definition into httplib.cc, so detail::base64_encode is not visible from the
  740. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  741. // in both header-only and split builds.
  742. namespace httplib {
  743. namespace detail {
  744. std::string base64_encode(const std::string &in);
  745. } // namespace detail
  746. } // namespace httplib
  747. TEST(Base64EncodeTest, KnownAnswers) {
  748. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  749. // where the accumulator's top bit is already set before the next shift.
  750. EXPECT_EQ("", detail::base64_encode(""));
  751. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  752. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  753. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  754. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  755. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  756. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  757. // High bytes keep the top bit set across several rounds.
  758. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  759. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  760. }
  761. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  762. string unescapedCharacters = "-_.!~*'()";
  763. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  764. }
  765. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  766. string reservedCharacters = ";,/?:@&=+$";
  767. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  768. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  769. }
  770. TEST(ClientQueryOrder, PreserveOrder) {
  771. // This test reproduces Issue #2259: client may reorder query parameters
  772. // when sending a GET request. The expected behavior is that the client
  773. // preserves the original query string order when the caller supplied it
  774. // as part of the path.
  775. Server svr;
  776. svr.Get("/", [&](const Request &req, Response &res) {
  777. // Echo back the raw target so the test can assert ordering
  778. res.set_content(req.target, "text/plain");
  779. });
  780. std::thread t{[&] { svr.listen(HOST, PORT); }};
  781. auto se = detail::scope_exit([&] {
  782. svr.stop();
  783. t.join();
  784. ASSERT_FALSE(svr.is_running());
  785. });
  786. svr.wait_until_ready();
  787. Client cli(HOST, PORT);
  788. ASSERT_TRUE(cli.is_valid());
  789. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  790. auto res = cli.Get(original);
  791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  792. // Expect the echoed target to exactly match the original path (order
  793. // preserved)
  794. EXPECT_EQ(res->body, original);
  795. }
  796. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  797. string chineseCharacters = U8("中国語");
  798. string russianCharacters = U8("дом");
  799. string brazilianCharacters = U8("óculos");
  800. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  801. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  802. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  803. "%D0%B4%D0%BE%D0%BC");
  804. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  805. }
  806. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  807. string unescapedCharacters = "-_.!~*'()";
  808. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  809. }
  810. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  811. string reservedCharacters = ";,/?:@&=+$";
  812. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  813. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  814. }
  815. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  816. string chineseCharacters = U8("中国語");
  817. string russianCharacters = U8("дом");
  818. string brazilianCharacters = U8("óculos");
  819. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  820. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  821. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  822. "%D0%B4%D0%BE%D0%BC");
  823. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  824. }
  825. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  826. // Issue #2082 use case: encoding path component with ampersand
  827. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  828. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  829. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  830. }
  831. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  832. string unescapedCharacters = "-_.!~*'()";
  833. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  834. }
  835. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  836. string reservedCharacters = ";,/?:@&=+$#";
  837. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  838. }
  839. TEST(EncodeUriTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  846. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  847. }
  848. TEST(EncodeUriTest, TestCompleteUri) {
  849. string uri =
  850. "https://example.com/path/to/resource?query=value&param=test#fragment";
  851. EXPECT_EQ(
  852. httplib::encode_uri(uri),
  853. "https://example.com/path/to/resource?query=value&param=test#fragment");
  854. }
  855. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  856. string uri =
  857. "https://example.com/path with spaces/file name.html?q=hello world";
  858. EXPECT_EQ(httplib::encode_uri(uri),
  859. "https://example.com/path%20with%20spaces/"
  860. "file%20name.html?q=hello%20world");
  861. }
  862. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  863. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  864. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  865. }
  866. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  867. string unescapedCharacters = "-_.!~*'()";
  868. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  869. }
  870. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  871. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  872. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  873. string encodedBrazilian = "%C3%B3culos";
  874. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  875. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  876. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  877. }
  878. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  879. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  880. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  881. "Piri Tommy Villiers - on & on");
  882. }
  883. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  884. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  885. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  886. }
  887. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  888. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  889. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  890. }
  891. TEST(DecodeUriTest, TestUTF8Characters) {
  892. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  893. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  894. string encodedBrazilian = "%C3%B3culos";
  895. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  896. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  897. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  898. }
  899. TEST(DecodeUriTest, TestCompleteUri) {
  900. string encodedUri = "https://example.com/path%20with%20spaces/"
  901. "file%20name.html?q=hello%20world";
  902. EXPECT_EQ(
  903. httplib::decode_uri(encodedUri),
  904. "https://example.com/path with spaces/file name.html?q=hello world");
  905. }
  906. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  907. string original =
  908. "https://example.com/path with spaces/file name.html?q=hello world";
  909. string encoded = httplib::encode_uri(original);
  910. string decoded = httplib::decode_uri(encoded);
  911. EXPECT_EQ(decoded, original);
  912. }
  913. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  914. // decode_uri is the inverse of encode_uri: an escaped reserved character
  915. // stays encoded so it is not promoted into a real delimiter, while
  916. // non-reserved escapes still decode (like JS decodeURI).
  917. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  918. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  919. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  920. "%3F%3A%40%26%3D%2B%24%2C%3B");
  921. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  922. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  923. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  924. "http://example.com/a%2Fb");
  925. // decode_uri_component still decodes the reserved character.
  926. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  927. }
  928. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  929. string original = "Piri Tommy Villiers - on & on";
  930. string encoded = httplib::encode_uri_component(original);
  931. string decoded = httplib::decode_uri_component(encoded);
  932. EXPECT_EQ(decoded, original);
  933. }
  934. TEST(TrimTests, TrimStringTests) {
  935. EXPECT_EQ("abc", detail::trim_copy("abc"));
  936. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  937. EXPECT_TRUE(detail::trim_copy("").empty());
  938. }
  939. TEST(AsciiTest, LocaleIndependentClassification) {
  940. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  941. // which consult the global C locale: std::isalnum(0xC5) can return true
  942. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  943. // helpers must classify every byte by the ASCII grammar alone.
  944. for (int i = 0; i < 256; i++) {
  945. auto c = static_cast<char>(i);
  946. auto is_digit = i >= '0' && i <= '9';
  947. auto is_upper = i >= 'A' && i <= 'Z';
  948. auto is_lower = i >= 'a' && i <= 'z';
  949. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  950. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  951. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  952. << "byte " << i;
  953. }
  954. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  955. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  956. // Non-ASCII bytes must be percent-encoded, never passed through as
  957. // alphanumeric.
  958. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  959. }
  960. TEST(FromCharsTest, Double) {
  961. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  962. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  963. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  964. auto parse = [](const std::string &s, double &v) {
  965. return detail::from_chars(s.data(), s.data() + s.size(), v);
  966. };
  967. double v = -1.0;
  968. // Representative quality values.
  969. EXPECT_EQ(parse("0", v).ec, std::errc{});
  970. EXPECT_DOUBLE_EQ(v, 0.0);
  971. EXPECT_EQ(parse("1", v).ec, std::errc{});
  972. EXPECT_DOUBLE_EQ(v, 1.0);
  973. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  974. EXPECT_DOUBLE_EQ(v, 0.8);
  975. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  976. EXPECT_DOUBLE_EQ(v, 0.001);
  977. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  978. EXPECT_DOUBLE_EQ(v, 1.0);
  979. // A missing integer or fractional part is tolerated.
  980. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  981. EXPECT_DOUBLE_EQ(v, 0.5);
  982. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  983. EXPECT_DOUBLE_EQ(v, 5.0);
  984. // Values outside [0, 1] still parse; the caller range-checks them.
  985. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  986. EXPECT_DOUBLE_EQ(v, 123.456);
  987. // Stops at the first byte that is not part of the number and reports where.
  988. std::string trailing = "0.9, text/html";
  989. auto r = parse(trailing, v);
  990. EXPECT_EQ(r.ec, std::errc{});
  991. EXPECT_DOUBLE_EQ(v, 0.9);
  992. EXPECT_EQ(*r.ptr, ',');
  993. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  994. // outright, and an 'e'/'E' simply ends the number.
  995. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  996. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  997. std::string exp_input = "1.5e3";
  998. r = parse(exp_input, v);
  999. EXPECT_EQ(r.ec, std::errc{});
  1000. EXPECT_DOUBLE_EQ(v, 1.5);
  1001. EXPECT_EQ(*r.ptr, 'e');
  1002. // Invalid inputs.
  1003. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1004. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1005. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1006. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1007. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1008. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1009. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1010. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1011. std::errc{});
  1012. EXPECT_DOUBLE_EQ(v, 0.0);
  1013. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1014. std::errc{});
  1015. EXPECT_GE(v, 0.0);
  1016. EXPECT_LE(v, 1.0);
  1017. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1018. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1019. }
  1020. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1021. // Simple case without quality values
  1022. std::vector<std::string> result1;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "text/html,application/json,text/plain", result1));
  1025. EXPECT_EQ(result1.size(), 3U);
  1026. EXPECT_EQ(result1[0], "text/html");
  1027. EXPECT_EQ(result1[1], "application/json");
  1028. EXPECT_EQ(result1[2], "text/plain");
  1029. // With quality values
  1030. std::vector<std::string> result2;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1033. EXPECT_EQ(result2.size(), 3U);
  1034. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1035. EXPECT_EQ(result2[1], "text/html");
  1036. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1037. }
  1038. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1039. // Mixed with and without quality values
  1040. std::vector<std::string> result;
  1041. EXPECT_TRUE(detail::parse_accept_header(
  1042. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1043. EXPECT_EQ(result.size(), 3U);
  1044. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1045. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1046. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1047. }
  1048. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1049. // Empty header
  1050. std::vector<std::string> empty_result;
  1051. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1052. EXPECT_TRUE(empty_result.empty());
  1053. // Single type
  1054. std::vector<std::string> single_result;
  1055. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1056. EXPECT_EQ(single_result.size(), 1U);
  1057. EXPECT_EQ(single_result[0], "application/json");
  1058. // Wildcard types
  1059. std::vector<std::string> wildcard_result;
  1060. EXPECT_TRUE(detail::parse_accept_header(
  1061. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1062. EXPECT_EQ(wildcard_result.size(), 3U);
  1063. EXPECT_EQ(wildcard_result[0], "application/json");
  1064. EXPECT_EQ(wildcard_result[1], "text/*");
  1065. EXPECT_EQ(wildcard_result[2], "*/*");
  1066. }
  1067. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1068. // Common browser Accept header
  1069. std::vector<std::string> browser_result;
  1070. EXPECT_TRUE(
  1071. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1072. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1073. browser_result));
  1074. EXPECT_EQ(browser_result.size(), 6U);
  1075. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1076. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1077. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1078. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1079. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1080. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1081. // API client header
  1082. std::vector<std::string> api_result;
  1083. EXPECT_TRUE(detail::parse_accept_header(
  1084. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1085. api_result));
  1086. EXPECT_EQ(api_result.size(), 3U);
  1087. EXPECT_EQ(api_result[0], "application/json");
  1088. EXPECT_EQ(api_result[1], "application/xml");
  1089. EXPECT_EQ(api_result[2], "text/plain");
  1090. }
  1091. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1092. // Quality value with 3 decimal places
  1093. std::vector<std::string> decimal_result;
  1094. EXPECT_TRUE(detail::parse_accept_header(
  1095. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1096. EXPECT_EQ(decimal_result.size(), 2U);
  1097. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1098. EXPECT_EQ(decimal_result[1], "text/html");
  1099. // Zero quality (should still be included but with lowest priority)
  1100. std::vector<std::string> zero_q_result;
  1101. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1102. zero_q_result));
  1103. EXPECT_EQ(zero_q_result.size(), 2U);
  1104. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1105. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1106. // No spaces around commas
  1107. std::vector<std::string> no_space_result;
  1108. EXPECT_TRUE(detail::parse_accept_header(
  1109. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1110. no_space_result));
  1111. EXPECT_EQ(no_space_result.size(), 3U);
  1112. EXPECT_EQ(no_space_result[0], "text/html");
  1113. EXPECT_EQ(no_space_result[1], "application/json");
  1114. EXPECT_EQ(no_space_result[2], "text/plain");
  1115. }
  1116. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1117. // Quality values always use '.' as the decimal separator, so parsing must
  1118. // not depend on the process locale. An embedding application may have
  1119. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1120. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1121. std::string saved = cur ? cur : "C";
  1122. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1123. "fr_FR.UTF-8"};
  1124. bool switched = false;
  1125. for (const auto loc : comma_locales) {
  1126. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1127. std::localeconv()->decimal_point[0] == ',') {
  1128. switched = true;
  1129. break;
  1130. }
  1131. }
  1132. if (!switched) {
  1133. std::setlocale(LC_NUMERIC, saved.c_str());
  1134. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1135. }
  1136. // The higher-weighted type appears later in the list, so a correct parse
  1137. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1138. // sensitive parse reads both weights as 0 and leaves the original order.
  1139. std::vector<std::string> result;
  1140. EXPECT_TRUE(detail::parse_accept_header(
  1141. "application/json;q=0.1,text/html;q=0.9", result));
  1142. ASSERT_EQ(result.size(), 2U);
  1143. EXPECT_EQ(result[0], "text/html");
  1144. EXPECT_EQ(result[1], "application/json");
  1145. std::setlocale(LC_NUMERIC, saved.c_str());
  1146. }
  1147. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1148. std::vector<std::string> result;
  1149. // Invalid quality value (> 1.0)
  1150. EXPECT_FALSE(
  1151. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1152. // Invalid quality value (< 0.0)
  1153. EXPECT_FALSE(
  1154. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1155. // Invalid quality value (not a number)
  1156. EXPECT_FALSE(detail::parse_accept_header(
  1157. "text/html;q=invalid,application/json", result));
  1158. // A valid numeric prefix does not make the entire quality value valid.
  1159. EXPECT_FALSE(detail::parse_accept_header(
  1160. "text/html;q=0.5junk,application/json", result));
  1161. // Empty quality value
  1162. EXPECT_FALSE(
  1163. detail::parse_accept_header("text/html;q=,application/json", result));
  1164. // Invalid media type format (no slash and not wildcard)
  1165. EXPECT_FALSE(
  1166. detail::parse_accept_header("invalidtype,application/json", result));
  1167. // Valid cases should still work
  1168. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1169. EXPECT_EQ(result.size(), 1U);
  1170. EXPECT_EQ(result[0], "*/*");
  1171. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1172. EXPECT_EQ(result.size(), 1U);
  1173. EXPECT_EQ(result[0], "*");
  1174. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1175. EXPECT_EQ(result.size(), 1U);
  1176. EXPECT_EQ(result[0], "text/*");
  1177. }
  1178. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1179. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1180. // and must not be answered with 400 Bad Request.
  1181. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1182. struct {
  1183. const char *value;
  1184. std::vector<std::string> expected;
  1185. } cases[] = {
  1186. {",application/json", {"application/json"}},
  1187. {"text/html,", {"text/html"}},
  1188. {"text/html,,*/*", {"text/html", "*/*"}},
  1189. // An empty element may be spelled with whitespace in it
  1190. {"text/html, , application/json", {"text/html", "application/json"}},
  1191. // Nothing but empty elements is an empty list, which means the same
  1192. // thing as no Accept header at all
  1193. {",,,", {}},
  1194. // Quality values still apply across ignored empty elements
  1195. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1196. };
  1197. for (const auto &c : cases) {
  1198. std::vector<std::string> result;
  1199. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1200. << "value: " << c.value;
  1201. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1202. }
  1203. // An invalid entry is still rejected when empty elements surround it
  1204. std::vector<std::string> result;
  1205. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1206. }
  1207. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1208. // or ';' inside one does not end the list element or the parameter. Section
  1209. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1210. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1211. struct {
  1212. const char *value;
  1213. std::vector<std::string> expected;
  1214. } cases[] = {
  1215. {"text/html;profile=\"a,b\",application/json",
  1216. {"text/html", "application/json"}},
  1217. // A "q=" inside a quoted value is not the weight
  1218. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1219. {"text/html", "application/json"}},
  1220. // The weight after a quoted value still applies
  1221. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1222. {"application/json", "text/html"}},
  1223. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1224. {"application/json", "text/html"}},
  1225. {"text/html;profile=\"a\\\"b\",application/json",
  1226. {"text/html", "application/json"}},
  1227. // An escaped backslash does not escape the '"' after it
  1228. {"text/html;profile=\"a\\\\\",application/json",
  1229. {"text/html", "application/json"}},
  1230. };
  1231. for (const auto &c : cases) {
  1232. std::vector<std::string> result;
  1233. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1234. << "value: " << c.value;
  1235. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1236. }
  1237. }
  1238. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1239. Server svr;
  1240. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1241. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1242. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1243. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1244. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1245. res.set_content("ok", "text/plain");
  1246. });
  1247. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1248. EXPECT_TRUE(false);
  1249. res.set_content("bad request", "text/plain");
  1250. });
  1251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1252. auto se = detail::scope_exit([&] {
  1253. svr.stop();
  1254. listen_thread.join();
  1255. ASSERT_FALSE(svr.is_running());
  1256. });
  1257. svr.wait_until_ready();
  1258. Client cli("localhost", PORT);
  1259. {
  1260. auto res = cli.Get(
  1261. "/accept_ok",
  1262. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1264. EXPECT_EQ(StatusCode::OK_200, res->status);
  1265. }
  1266. {
  1267. auto res = cli.Get("/accept_bad_request",
  1268. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1271. }
  1272. }
  1273. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1274. Server svr;
  1275. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1276. res.set_content("ok", "text/plain");
  1277. });
  1278. std::atomic<int> start_count{0};
  1279. std::atomic<bool> running_when_called{false};
  1280. svr.set_start_handler([&]() {
  1281. running_when_called = svr.is_running();
  1282. start_count++;
  1283. });
  1284. auto port = svr.bind_to_any_port(HOST);
  1285. std::thread t([&]() { svr.listen_after_bind(); });
  1286. auto se = detail::scope_exit([&] {
  1287. svr.stop();
  1288. t.join();
  1289. ASSERT_FALSE(svr.is_running());
  1290. });
  1291. svr.wait_until_ready();
  1292. // A successful request proves the accept loop is running, which the start
  1293. // handler precedes; so by now the handler must have run exactly once.
  1294. Client cli(HOST, port);
  1295. cli.set_connection_timeout(std::chrono::seconds(5));
  1296. auto res = cli.Get("/");
  1297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1298. EXPECT_EQ(StatusCode::OK_200, res->status);
  1299. EXPECT_EQ(1, start_count.load());
  1300. EXPECT_TRUE(running_when_called.load());
  1301. }
  1302. TEST(DivideTest, DivideStringTests) {
  1303. auto divide = [](const std::string &str, char d) {
  1304. std::string lhs;
  1305. std::string rhs;
  1306. detail::divide(str, d,
  1307. [&](const char *lhs_data, std::size_t lhs_size,
  1308. const char *rhs_data, std::size_t rhs_size) {
  1309. lhs.assign(lhs_data, lhs_size);
  1310. rhs.assign(rhs_data, rhs_size);
  1311. });
  1312. return std::make_pair(std::move(lhs), std::move(rhs));
  1313. };
  1314. {
  1315. const auto res = divide("", '=');
  1316. EXPECT_EQ(res.first, "");
  1317. EXPECT_EQ(res.second, "");
  1318. }
  1319. {
  1320. const auto res = divide("=", '=');
  1321. EXPECT_EQ(res.first, "");
  1322. EXPECT_EQ(res.second, "");
  1323. }
  1324. {
  1325. const auto res = divide(" ", '=');
  1326. EXPECT_EQ(res.first, " ");
  1327. EXPECT_EQ(res.second, "");
  1328. }
  1329. {
  1330. const auto res = divide("a", '=');
  1331. EXPECT_EQ(res.first, "a");
  1332. EXPECT_EQ(res.second, "");
  1333. }
  1334. {
  1335. const auto res = divide("a=", '=');
  1336. EXPECT_EQ(res.first, "a");
  1337. EXPECT_EQ(res.second, "");
  1338. }
  1339. {
  1340. const auto res = divide("=b", '=');
  1341. EXPECT_EQ(res.first, "");
  1342. EXPECT_EQ(res.second, "b");
  1343. }
  1344. {
  1345. const auto res = divide("a=b", '=');
  1346. EXPECT_EQ(res.first, "a");
  1347. EXPECT_EQ(res.second, "b");
  1348. }
  1349. {
  1350. const auto res = divide("a=b=", '=');
  1351. EXPECT_EQ(res.first, "a");
  1352. EXPECT_EQ(res.second, "b=");
  1353. }
  1354. {
  1355. const auto res = divide("a=b=c", '=');
  1356. EXPECT_EQ(res.first, "a");
  1357. EXPECT_EQ(res.second, "b=c");
  1358. }
  1359. }
  1360. TEST(SplitTest, ParseQueryString) {
  1361. string s = "key1=val1&key2=val2&key3=val3";
  1362. Params dic;
  1363. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1364. [&](const char *b, const char *e) {
  1365. string key, val;
  1366. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1367. if (key.empty()) {
  1368. key.assign(b2, e2);
  1369. } else {
  1370. val.assign(b2, e2);
  1371. }
  1372. });
  1373. dic.emplace(key, val);
  1374. });
  1375. EXPECT_EQ("val1", dic.find("key1")->second);
  1376. EXPECT_EQ("val2", dic.find("key2")->second);
  1377. EXPECT_EQ("val3", dic.find("key3")->second);
  1378. }
  1379. TEST(SplitTest, ParseInvalidQueryTests) {
  1380. {
  1381. string s = " ";
  1382. Params dict;
  1383. detail::parse_query_text(s, dict);
  1384. EXPECT_TRUE(dict.empty());
  1385. }
  1386. {
  1387. string s = " = =";
  1388. Params dict;
  1389. detail::parse_query_text(s, dict);
  1390. EXPECT_TRUE(dict.empty());
  1391. }
  1392. }
  1393. TEST(ParseQueryTest, ParseQueryString) {
  1394. {
  1395. std::string s = "key1=val1&key2=val2&key3=val3";
  1396. Params dic;
  1397. detail::parse_query_text(s, dic);
  1398. EXPECT_EQ("val1", dic.find("key1")->second);
  1399. EXPECT_EQ("val2", dic.find("key2")->second);
  1400. EXPECT_EQ("val3", dic.find("key3")->second);
  1401. }
  1402. {
  1403. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1404. Params dic;
  1405. detail::parse_query_text(s, dic);
  1406. EXPECT_EQ("", dic.find("key1")->second);
  1407. EXPECT_EQ("val1", dic.find("key2")->second);
  1408. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1409. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1410. }
  1411. }
  1412. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1413. Params dic;
  1414. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1415. dic.emplace("key1", "val1");
  1416. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1417. dic.emplace("key2", "val2");
  1418. dic.emplace("key3", "val3");
  1419. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1420. }
  1421. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1422. Params params;
  1423. params.emplace("a", "1");
  1424. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1425. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1426. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1427. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1428. // Long enough to overflow the stack when matched with std::regex.
  1429. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1430. EXPECT_EQ("/p?" + long_query + "&a=1",
  1431. append_query_params("/p?" + long_query, params));
  1432. }
  1433. // Joins every entry of a Headers or Params into "key=value " so a whole
  1434. // traversal can be compared in one assertion. Both are instantiations of the
  1435. // same insertion-ordered container, so one helper serves both.
  1436. template <typename Map> static std::string entries_to_string(const Map &m) {
  1437. std::string s;
  1438. for (const auto &entry : m) {
  1439. s += entry.first + "=" + entry.second + " ";
  1440. }
  1441. return s;
  1442. }
  1443. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1444. // Params used to be a std::multimap, which sorted by name and handed the
  1445. // caller's query back alphabetised. A client signing its query string could
  1446. // not reproduce the order it asked for.
  1447. Params dic;
  1448. dic.emplace("zulu", "1");
  1449. dic.emplace("alpha", "2");
  1450. dic.emplace("mike", "3");
  1451. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1452. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1453. }
  1454. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1455. Params dic;
  1456. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1457. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1458. }
  1459. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1460. Request req;
  1461. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1462. req.params);
  1463. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1464. EXPECT_EQ("first", req.get_param_value("tag"));
  1465. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1466. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1467. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1468. EXPECT_EQ("", req.get_param_value("tag", 3));
  1469. }
  1470. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1471. // Params shares its container with Headers, which matches field names
  1472. // case-insensitively. Parameter names must not pick that up.
  1473. Params dic;
  1474. dic.emplace("Key", "upper");
  1475. dic.emplace("key", "lower");
  1476. EXPECT_EQ(2U, dic.size());
  1477. EXPECT_EQ(1U, dic.count("Key"));
  1478. EXPECT_EQ(1U, dic.count("key"));
  1479. EXPECT_EQ("upper", dic.find("Key")->second);
  1480. EXPECT_EQ("lower", dic.find("key")->second);
  1481. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1482. }
  1483. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1484. Server svr;
  1485. std::string order;
  1486. svr.Get("/order", [&](const Request &req, Response &res) {
  1487. order = entries_to_string(req.params);
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, port);
  1499. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1502. }
  1503. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1504. Server svr;
  1505. std::string field_order, file_order;
  1506. svr.Post("/order", [&](const Request &req, Response &res) {
  1507. for (const auto &field : req.form.fields) {
  1508. field_order += field.first + "=" + field.second.content + " ";
  1509. }
  1510. for (const auto &file : req.form.files) {
  1511. file_order += file.first + "=" + file.second.filename + " ";
  1512. }
  1513. res.set_content("ok", "text/plain");
  1514. });
  1515. auto port = svr.bind_to_any_port(HOST);
  1516. thread t = thread([&] { svr.listen_after_bind(); });
  1517. auto se = detail::scope_exit([&] {
  1518. svr.stop();
  1519. t.join();
  1520. ASSERT_FALSE(svr.is_running());
  1521. });
  1522. svr.wait_until_ready();
  1523. UploadFormDataItems items = {
  1524. {"zulu", "1", "", ""},
  1525. {"alpha", "2", "", ""},
  1526. {"mike", "3", "", ""},
  1527. {"zebra", "z", "z.txt", "text/plain"},
  1528. {"apple", "a", "a.txt", "text/plain"},
  1529. };
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/order", items);
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1534. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1535. }
  1536. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1537. Server svr;
  1538. std::vector<std::string> values;
  1539. std::string first, second, out_of_range, order;
  1540. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1541. values = req.form.get_fields("tag");
  1542. first = req.form.get_field("tag", 0);
  1543. second = req.form.get_field("tag", 1);
  1544. out_of_range = req.form.get_field("tag", 2);
  1545. for (const auto &field : req.form.fields) {
  1546. order += field.first + "=" + field.second.content + " ";
  1547. }
  1548. res.set_content("ok", "text/plain");
  1549. });
  1550. auto port = svr.bind_to_any_port(HOST);
  1551. thread t = thread([&] { svr.listen_after_bind(); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. t.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1559. // not adjacent in the container.
  1560. UploadFormDataItems items = {
  1561. {"tag", "first", "", ""},
  1562. {"other", "x", "", ""},
  1563. {"tag", "second", "", ""},
  1564. };
  1565. Client cli(HOST, port);
  1566. auto res = cli.Post("/repeated", items);
  1567. ASSERT_TRUE(res);
  1568. ASSERT_EQ(2U, values.size());
  1569. EXPECT_EQ("first", values[0]);
  1570. EXPECT_EQ("second", values[1]);
  1571. EXPECT_EQ("first", first);
  1572. EXPECT_EQ("second", second);
  1573. // std::multimap already kept entries sharing a name in insertion order, so
  1574. // everything above passes without this change too. The whole traversal is
  1575. // what tells the two apart: sorting by name would hoist "other" to the front
  1576. // and the two "tag" parts would end up adjacent.
  1577. EXPECT_EQ("tag=first other=x tag=second ", order);
  1578. // Advancing past the last entry of a name used to run off the container;
  1579. // the container's saturating increment makes it return the default instead.
  1580. EXPECT_EQ("", out_of_range);
  1581. }
  1582. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1583. Server svr;
  1584. std::string file_names;
  1585. svr.Post("/upload", [&](const Request &req, Response &res) {
  1586. for (const auto &file : req.form.files) {
  1587. file_names += file.first + "|" + file.second.filename + " ";
  1588. }
  1589. res.set_content("ok", "text/plain");
  1590. });
  1591. auto port = svr.bind_to_any_port(HOST);
  1592. thread t = thread([&] { svr.listen_after_bind(); });
  1593. auto se = detail::scope_exit([&] {
  1594. svr.stop();
  1595. t.join();
  1596. ASSERT_FALSE(svr.is_running());
  1597. });
  1598. svr.wait_until_ready();
  1599. // A trailing backslash would otherwise escape the closing quote.
  1600. UploadFormDataItems items = {
  1601. {"dir\\", "x", "a.txt", "text/plain"},
  1602. {"b", "y", "a\\\\b.txt", "text/plain"},
  1603. };
  1604. Client cli(HOST, port);
  1605. auto res = cli.Post("/upload", items);
  1606. ASSERT_TRUE(res);
  1607. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1608. }
  1609. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1610. // Server::read_content() keeps a FormFields::iterator alive across the
  1611. // content callbacks that fill the part it points at. The container is
  1612. // vector-backed, so a later emplace can reallocate and invalidate an older
  1613. // iterator; 64 parts grow the vector through seven reallocations, which
  1614. // checks that every part's content still lands in its own entry.
  1615. const size_t part_count = 64;
  1616. // One formula for both the parts sent and the values expected back, so the
  1617. // two cannot drift apart.
  1618. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1619. auto content_of = [](size_t i) {
  1620. return std::string(64, static_cast<char>('a' + (i % 26)));
  1621. };
  1622. Server svr;
  1623. std::vector<std::pair<std::string, std::string>> received;
  1624. svr.Post("/many", [&](const Request &req, Response &res) {
  1625. for (const auto &field : req.form.fields) {
  1626. received.emplace_back(field.first, field.second.content);
  1627. }
  1628. res.set_content("ok", "text/plain");
  1629. });
  1630. auto port = svr.bind_to_any_port(HOST);
  1631. thread t = thread([&] { svr.listen_after_bind(); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. t.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. UploadFormDataItems items;
  1639. for (size_t i = 0; i < part_count; i++) {
  1640. items.push_back({name_of(i), content_of(i), "", ""});
  1641. }
  1642. Client cli(HOST, port);
  1643. auto res = cli.Post("/many", items);
  1644. ASSERT_TRUE(res);
  1645. ASSERT_EQ(part_count, received.size());
  1646. for (size_t i = 0; i < part_count; i++) {
  1647. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1648. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1649. }
  1650. }
  1651. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1652. string content_type = "multipart/form-data; boundary=something";
  1653. string boundary;
  1654. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(boundary, "something");
  1657. }
  1658. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1659. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1660. string boundary;
  1661. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1662. EXPECT_TRUE(ret);
  1663. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1666. string content_type =
  1667. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1668. string boundary;
  1669. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1670. EXPECT_TRUE(ret);
  1671. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1672. }
  1673. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1674. string content_type =
  1675. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1676. string boundary;
  1677. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1678. EXPECT_TRUE(ret);
  1679. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1680. }
  1681. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1682. const string boundary(70, 'a');
  1683. string content_type = "multipart/form-data; boundary=" + boundary;
  1684. string parsed;
  1685. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1686. EXPECT_TRUE(ret);
  1687. EXPECT_EQ(parsed, boundary);
  1688. }
  1689. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1690. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1691. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1692. string parsed;
  1693. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1694. EXPECT_FALSE(ret);
  1695. }
  1696. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1697. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1698. // is 72 characters on the wire and still valid.
  1699. const string boundary(70, 'a');
  1700. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1701. string parsed;
  1702. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1703. EXPECT_EQ(parsed, boundary);
  1704. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1705. parsed.clear();
  1706. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1709. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1710. // The parameter parser must not treat that '=' as the key/value separator.
  1711. string content_type =
  1712. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1713. "charset=UTF-8";
  1714. string parsed;
  1715. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1716. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1717. }
  1718. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1719. // A ';' inside the quoted-string is part of the value, not a parameter
  1720. // separator, so it must not truncate the boundary.
  1721. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1722. string parsed;
  1723. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1724. EXPECT_EQ(parsed, "a;b");
  1725. }
  1726. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1727. string parsed;
  1728. EXPECT_TRUE(detail::parse_multipart_boundary(
  1729. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1730. EXPECT_EQ("a\\b", parsed);
  1731. EXPECT_TRUE(detail::parse_multipart_boundary(
  1732. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1733. EXPECT_EQ("a\"b", parsed);
  1734. }
  1735. TEST(ParseDispositionParamsTest, QuotedValues) {
  1736. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1737. // ';' and '=' are ordinary characters inside one.
  1738. struct {
  1739. const char *value;
  1740. std::vector<std::pair<const char *, const char *>> expected;
  1741. } cases[] = {
  1742. {"name=\"file1\"; filename=\"a.txt\"",
  1743. {{"name", "file1"}, {"filename", "a.txt"}}},
  1744. // Whitespace around '=' and ';' is still trimmed
  1745. {"name=\"file2\" ;filename = \"a.html\"",
  1746. {{"name", "file2"}, {"filename", "a.html"}}},
  1747. // '=' inside the value used to leave only the text after the last one
  1748. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1749. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1750. {"name=\"x=y\"", {{"name", "x=y"}}},
  1751. // ';' inside the value used to truncate the pair and leave a bogus one
  1752. {"name=\"file3\"; filename=\"a;b.txt\"",
  1753. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1754. // An unquoted value keeps working, and so does filename*
  1755. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1756. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1757. // A parameter with no key is dropped rather than turned into one whose
  1758. // key is the value
  1759. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1760. // An escaped quote does not end the value
  1761. {"name=\"a\\\"; filename=evil.php\"",
  1762. {{"name", "a\"; filename=evil.php"}}},
  1763. // Other backslashes, as in a Windows path, are kept
  1764. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1765. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1766. };
  1767. for (const auto &c : cases) {
  1768. Params params;
  1769. detail::parse_disposition_params(c.value, params);
  1770. for (const auto &kv : c.expected) {
  1771. auto it = params.find(kv.first);
  1772. ASSERT_NE(it, params.end())
  1773. << "value: " << c.value << ", key: " << kv.first;
  1774. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1775. }
  1776. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1777. }
  1778. }
  1779. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1780. Server svr;
  1781. std::string filename;
  1782. std::string content;
  1783. svr.Post("/upload", [&](const Request &req, Response &) {
  1784. const auto &file = req.form.get_file("file");
  1785. filename = file.filename;
  1786. content = file.content;
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. std::string body = "--B\r\n"
  1796. "Content-Disposition: form-data; name=\"file\"; "
  1797. "filename=\"a.txt\"\r\n"
  1798. "Content-Type: text/plain\r\n"
  1799. "\r\n"
  1800. "hello\r\n"
  1801. "--B--\r\n";
  1802. Client cli(HOST, PORT);
  1803. auto res = cli.Post(
  1804. "/upload",
  1805. [&](size_t offset, DataSink &sink) {
  1806. if (offset < body.size()) {
  1807. sink.write(&body[offset], 1);
  1808. } else {
  1809. sink.done();
  1810. }
  1811. return true;
  1812. },
  1813. "multipart/form-data; boundary=B");
  1814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1815. EXPECT_EQ(StatusCode::OK_200, res->status);
  1816. EXPECT_EQ("a.txt", filename);
  1817. EXPECT_EQ("hello", content);
  1818. }
  1819. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1820. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1821. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1822. Server svr;
  1823. std::string field_value, file_name, file_filename;
  1824. bool has_field = false, has_file = false;
  1825. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1826. has_field = req.form.has_field("x=y");
  1827. field_value = req.form.get_field("x=y");
  1828. has_file = req.form.has_file("file1");
  1829. const auto &file = req.form.get_file("file1");
  1830. file_name = file.name;
  1831. file_filename = file.filename;
  1832. res.set_content("ok", "text/plain");
  1833. });
  1834. auto port = svr.bind_to_any_port(HOST);
  1835. thread t = thread([&] { svr.listen_after_bind(); });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. t.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. UploadFormDataItems items = {
  1843. {"x=y", "field-value", "", ""},
  1844. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1845. };
  1846. Client cli(HOST, port);
  1847. auto res = cli.Post("/quoted", items);
  1848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1849. ASSERT_EQ(StatusCode::OK_200, res->status);
  1850. EXPECT_TRUE(has_field);
  1851. EXPECT_EQ("field-value", field_value);
  1852. EXPECT_TRUE(has_file);
  1853. EXPECT_EQ("file1", file_name);
  1854. EXPECT_EQ("a;b=report.pdf", file_filename);
  1855. }
  1856. TEST(GetHeaderValueTest, DefaultValue) {
  1857. Headers headers = {{"Dummy", "Dummy"}};
  1858. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1859. EXPECT_STREQ("text/plain", val);
  1860. }
  1861. TEST(GetHeaderValueTest, DefaultValueInt) {
  1862. Headers headers = {{"Dummy", "Dummy"}};
  1863. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1864. EXPECT_EQ(100ull, val);
  1865. }
  1866. TEST(GetHeaderValueTest, RegularValue) {
  1867. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1868. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1869. EXPECT_STREQ("text/html", val);
  1870. }
  1871. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1872. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1873. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1874. EXPECT_STREQ("text/html", val);
  1875. }
  1876. TEST(GetHeaderValueTest, SetContent) {
  1877. Response res;
  1878. res.set_content("html", "text/html");
  1879. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1880. res.set_content("text", "text/plain");
  1881. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1882. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1883. }
  1884. TEST(GetHeaderValueTest, RegularValueInt) {
  1885. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1887. EXPECT_EQ(100ull, val);
  1888. }
  1889. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1890. Headers headers = {{"Content-Length", "x"}};
  1891. auto is_invalid_value = false;
  1892. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1893. is_invalid_value);
  1894. EXPECT_EQ(0ull, val);
  1895. EXPECT_TRUE(is_invalid_value);
  1896. }
  1897. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1898. // An all-digit value that overflows size_t must be reported as invalid, not
  1899. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1900. // a large length to a small one on 32-bit builds, leaving the framing length
  1901. // wrong while is_invalid_value stayed false.
  1902. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1903. auto is_invalid_value = false;
  1904. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1905. is_invalid_value);
  1906. EXPECT_TRUE(is_invalid_value);
  1907. // A well-formed length is unaffected.
  1908. Headers ok = {{"Content-Length", "1234"}};
  1909. is_invalid_value = false;
  1910. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1911. is_invalid_value);
  1912. EXPECT_EQ(1234ull, val);
  1913. EXPECT_FALSE(is_invalid_value);
  1914. }
  1915. TEST(GetHeaderValueTest, Range) {
  1916. {
  1917. Headers headers = {make_range_header({{1, -1}})};
  1918. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1919. EXPECT_STREQ("bytes=1-", val);
  1920. }
  1921. {
  1922. Headers headers = {make_range_header({{-1, 1}})};
  1923. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1924. EXPECT_STREQ("bytes=-1", val);
  1925. }
  1926. {
  1927. Headers headers = {make_range_header({{1, 10}})};
  1928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1929. EXPECT_STREQ("bytes=1-10", val);
  1930. }
  1931. {
  1932. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1934. EXPECT_STREQ("bytes=1-10, 100-", val);
  1935. }
  1936. {
  1937. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1938. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1939. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1940. }
  1941. {
  1942. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1943. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1944. EXPECT_STREQ("bytes=0-0, -1", val);
  1945. }
  1946. }
  1947. TEST(BearerTokenAuthTest, SchemeValidation) {
  1948. // A value shorter than "Bearer " must not throw from the fixed-length
  1949. // substr, and a non-Bearer scheme must not be reported as a token.
  1950. struct {
  1951. const char *value;
  1952. const char *expected;
  1953. } cases[] = {
  1954. {"x", ""},
  1955. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1956. {"Bearer abc123", "abc123"},
  1957. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1958. };
  1959. for (const auto &c : cases) {
  1960. Request req;
  1961. req.set_header("Authorization", c.value);
  1962. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1963. }
  1964. }
  1965. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1966. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1967. // to depend on the standard library (libstdc++ handed back duplicates in
  1968. // reverse insertion order, libc++ in insertion order).
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "gzip");
  1971. req.set_header("Accept-Encoding", "deflate");
  1972. req.set_header("Accept-Encoding", "br");
  1973. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1974. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1975. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1976. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1977. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1978. }
  1979. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1980. Request req;
  1981. req.set_header("X-Test", "only");
  1982. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1983. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1984. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1985. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1986. }
  1987. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1988. Request req;
  1989. req.set_header("X-First", "1");
  1990. req.set_header("X-Test", "2");
  1991. req.params.emplace("first", "1");
  1992. req.params.emplace("test", "2");
  1993. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1994. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1995. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1996. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1997. // The second one is negative when read as a signed value
  1998. const auto max_id = (std::numeric_limits<size_t>::max)();
  1999. for (auto id : {max_id / 2, max_id}) {
  2000. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2001. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2002. EXPECT_EQ("", req.get_param_value("test", id));
  2003. EXPECT_EQ("", req.form.get_field("test", id));
  2004. EXPECT_EQ("", req.form.get_file("test", id).content);
  2005. }
  2006. }
  2007. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2008. Headers headers;
  2009. headers.emplace("Host", "example.com");
  2010. headers.emplace("Accept-Encoding", "gzip");
  2011. headers.emplace("User-Agent", "test");
  2012. headers.emplace("Accept-Encoding", "deflate");
  2013. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2014. "Accept-Encoding=deflate ",
  2015. entries_to_string(headers));
  2016. }
  2017. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2018. Headers headers = {{"Content-Type", "text/html"},
  2019. {"CONTENT-TYPE", "text/xml"}};
  2020. EXPECT_EQ(2U, headers.count("content-type"));
  2021. auto it = headers.find("content-type");
  2022. ASSERT_TRUE(it != headers.end());
  2023. EXPECT_EQ("text/html", it->second);
  2024. }
  2025. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2026. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2027. // drop only those fields and leave everything positioned between them.
  2028. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2029. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2030. auto rng = headers.equal_range("a");
  2031. headers.erase(rng.first, rng.second);
  2032. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2033. }
  2034. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2035. Headers headers = {
  2036. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2037. EXPECT_EQ(3U, headers.erase("A"));
  2038. EXPECT_EQ(0U, headers.count("A"));
  2039. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2040. }
  2041. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2042. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2043. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2044. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2045. }
  2046. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2047. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2048. headers.emplace_front("Host", "example.com");
  2049. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2050. entries_to_string(headers));
  2051. }
  2052. TEST(ParseHeaderValueTest, Range) {
  2053. {
  2054. Ranges ranges;
  2055. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2056. EXPECT_TRUE(ret);
  2057. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2058. }
  2059. {
  2060. Ranges ranges;
  2061. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2062. EXPECT_TRUE(ret);
  2063. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2064. }
  2065. {
  2066. Ranges ranges;
  2067. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2068. EXPECT_TRUE(ret);
  2069. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2070. }
  2071. {
  2072. Ranges ranges;
  2073. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2074. EXPECT_FALSE(ret);
  2075. }
  2076. {
  2077. Ranges ranges;
  2078. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2079. EXPECT_TRUE(ret);
  2080. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2081. }
  2082. {
  2083. Ranges ranges;
  2084. auto ret =
  2085. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2086. EXPECT_TRUE(ret);
  2087. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2088. }
  2089. {
  2090. Ranges ranges;
  2091. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2092. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2093. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2094. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2095. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2096. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2097. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2098. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2099. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2100. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2101. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2102. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2103. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2104. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2105. EXPECT_FALSE(
  2106. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2107. EXPECT_TRUE(ranges.empty());
  2108. }
  2109. {
  2110. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2111. // remainder of the representation, so it stays accepted.
  2112. Ranges ranges;
  2113. auto ret =
  2114. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2115. EXPECT_TRUE(ret);
  2116. ASSERT_EQ(1u, ranges.size());
  2117. EXPECT_EQ(0, ranges[0].first);
  2118. EXPECT_EQ(-1, ranges[0].second);
  2119. }
  2120. // RFC 9110 14.1: range unit names are case-insensitive.
  2121. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2122. Ranges ranges;
  2123. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2124. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2125. }
  2126. }
  2127. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2128. Request req;
  2129. req.set_header("Accept-Encoding", "gzip");
  2130. Response res;
  2131. res.set_header("Content-Type", "text/plain");
  2132. auto ret = detail::encoding_type(req, res);
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #else
  2136. EXPECT_TRUE(ret == detail::EncodingType::None);
  2137. #endif
  2138. }
  2139. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2140. Request req;
  2141. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2142. Response res;
  2143. res.set_header("Content-Type", "text/plain");
  2144. auto ret = detail::encoding_type(req, res);
  2145. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2146. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2147. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2149. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2151. #else
  2152. EXPECT_TRUE(ret == detail::EncodingType::None);
  2153. #endif
  2154. }
  2155. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2156. Request req;
  2157. req.set_header("Accept-Encoding",
  2158. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2159. Response res;
  2160. res.set_header("Content-Type", "text/plain");
  2161. auto ret = detail::encoding_type(req, res);
  2162. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2163. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2164. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2165. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2166. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2168. #else
  2169. EXPECT_TRUE(ret == detail::EncodingType::None);
  2170. #endif
  2171. }
  2172. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2173. // All supported encodings rejected with q=0 should return None
  2174. Request req;
  2175. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2176. Response res;
  2177. res.set_header("Content-Type", "text/plain");
  2178. auto ret = detail::encoding_type(req, res);
  2179. EXPECT_TRUE(ret == detail::EncodingType::None);
  2180. }
  2181. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2182. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2183. Request req;
  2184. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2185. Response res;
  2186. res.set_header("Content-Type", "text/plain");
  2187. auto ret = detail::encoding_type(req, res);
  2188. EXPECT_TRUE(ret == detail::EncodingType::None);
  2189. }
  2190. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2191. Request req;
  2192. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2193. Response res;
  2194. res.set_header("Content-Type", "text/plain");
  2195. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2196. }
  2197. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2198. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2199. Request req;
  2200. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2201. Response res;
  2202. res.set_header("Content-Type", "text/plain");
  2203. auto ret = detail::encoding_type(req, res);
  2204. EXPECT_TRUE(ret == detail::EncodingType::None);
  2205. }
  2206. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2207. // RFC 7231: Accept-Encoding values are case-insensitive
  2208. Request req;
  2209. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2210. Response res;
  2211. res.set_header("Content-Type", "text/plain");
  2212. auto ret = detail::encoding_type(req, res);
  2213. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2214. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2215. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2216. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2217. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2218. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2219. #else
  2220. EXPECT_TRUE(ret == detail::EncodingType::None);
  2221. #endif
  2222. }
  2223. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2224. // q value should determine priority, not hardcoded order
  2225. Request req;
  2226. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2227. Response res;
  2228. res.set_header("Content-Type", "text/plain");
  2229. auto ret = detail::encoding_type(req, res);
  2230. // gzip has highest q=1.0, so it should be selected even though
  2231. // br and zstd are also supported
  2232. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2233. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2234. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2235. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2236. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2237. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2238. #else
  2239. EXPECT_TRUE(ret == detail::EncodingType::None);
  2240. #endif
  2241. }
  2242. TEST(BufferStreamTest, read) {
  2243. detail::BufferStream strm1;
  2244. Stream &strm = strm1;
  2245. EXPECT_EQ(5, strm.write("hello"));
  2246. char buf[512];
  2247. EXPECT_EQ(2, strm.read(buf, 2));
  2248. EXPECT_EQ('h', buf[0]);
  2249. EXPECT_EQ('e', buf[1]);
  2250. EXPECT_EQ(2, strm.read(buf, 2));
  2251. EXPECT_EQ('l', buf[0]);
  2252. EXPECT_EQ('l', buf[1]);
  2253. EXPECT_EQ(1, strm.read(buf, 1));
  2254. EXPECT_EQ('o', buf[0]);
  2255. EXPECT_EQ(0, strm.read(buf, 1));
  2256. }
  2257. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2258. auto host = "www.httpwatch.com";
  2259. auto ip = hosted_at(host);
  2260. EXPECT_EQ("23.96.13.243", ip);
  2261. std::vector<std::string> addrs;
  2262. hosted_at(host, addrs);
  2263. EXPECT_EQ(1u, addrs.size());
  2264. }
  2265. #if 0 // It depends on each test environment...
  2266. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2267. auto host = "www.youtube.com";
  2268. std::vector<std::string> addrs;
  2269. hosted_at(host, addrs);
  2270. EXPECT_EQ(20u, addrs.size());
  2271. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2272. EXPECT_TRUE(it != addrs.end());
  2273. }
  2274. #endif
  2275. class ChunkedEncodingTest : public ::testing::Test {
  2276. protected:
  2277. ChunkedEncodingTest()
  2278. : cli_(HOST, PORT)
  2279. #ifdef CPPHTTPLIB_SSL_ENABLED
  2280. ,
  2281. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2282. #endif
  2283. {
  2284. cli_.set_connection_timeout(2);
  2285. #ifdef CPPHTTPLIB_SSL_ENABLED
  2286. cli_.enable_server_certificate_verification(false);
  2287. #endif
  2288. }
  2289. virtual void SetUp() {
  2290. read_file("./image.jpg", image_data_);
  2291. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2292. res.set_content("Hello World!", "text/plain");
  2293. });
  2294. svr_.Get(
  2295. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2296. res.set_chunked_content_provider(
  2297. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2298. size_t remaining = image_data_.size() - offset;
  2299. if (remaining == 0) {
  2300. sink.done();
  2301. } else {
  2302. constexpr size_t CHUNK_SIZE = 1024;
  2303. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2304. sink.write(&image_data_[offset], send_size);
  2305. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2306. }
  2307. return true;
  2308. });
  2309. });
  2310. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2311. svr_.wait_until_ready();
  2312. }
  2313. virtual void TearDown() {
  2314. svr_.stop();
  2315. if (!request_threads_.empty()) {
  2316. std::this_thread::sleep_for(std::chrono::seconds(1));
  2317. for (auto &t : request_threads_) {
  2318. t.join();
  2319. }
  2320. }
  2321. t_.join();
  2322. }
  2323. #ifdef CPPHTTPLIB_SSL_ENABLED
  2324. SSLClient cli_;
  2325. SSLServer svr_;
  2326. #else
  2327. Client cli_;
  2328. Server svr_;
  2329. #endif
  2330. thread t_;
  2331. std::vector<thread> request_threads_;
  2332. std::string image_data_;
  2333. };
  2334. TEST_F(ChunkedEncodingTest, NormalGet) {
  2335. auto res = cli_.Get("/chunked");
  2336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2337. std::string out;
  2338. read_file("./image.jpg", out);
  2339. EXPECT_EQ(StatusCode::OK_200, res->status);
  2340. EXPECT_EQ(out, res->body);
  2341. }
  2342. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2343. std::string body;
  2344. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2345. body.append(data, data_length);
  2346. return true;
  2347. });
  2348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2349. std::string out;
  2350. read_file("./image.jpg", out);
  2351. EXPECT_EQ(StatusCode::OK_200, res->status);
  2352. EXPECT_EQ(out, body);
  2353. }
  2354. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2355. std::string body;
  2356. auto res = cli_.Get(
  2357. "/chunked",
  2358. [&](const Response &response) {
  2359. EXPECT_EQ(StatusCode::OK_200, response.status);
  2360. return true;
  2361. },
  2362. [&](const char *data, size_t data_length) {
  2363. body.append(data, data_length);
  2364. return true;
  2365. });
  2366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2367. std::string out;
  2368. read_file("./image.jpg", out);
  2369. EXPECT_EQ(StatusCode::OK_200, res->status);
  2370. EXPECT_EQ(out, body);
  2371. }
  2372. TEST(RangeTest, FromHTTPBin_Online) {
  2373. auto host = "httpbingo.org";
  2374. auto path = std::string{"/range/32"};
  2375. #ifdef CPPHTTPLIB_SSL_ENABLED
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. #else
  2379. auto port = 80;
  2380. Client cli(host, port);
  2381. #endif
  2382. cli.set_connection_timeout(5);
  2383. {
  2384. auto res = cli.Get(path);
  2385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2386. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2387. EXPECT_EQ(StatusCode::OK_200, res->status);
  2388. }
  2389. {
  2390. Headers headers = {make_range_header({{1, -1}})};
  2391. auto res = cli.Get(path, headers);
  2392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2393. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2395. }
  2396. {
  2397. Headers headers = {make_range_header({{1, 10}})};
  2398. auto res = cli.Get(path, headers);
  2399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2400. EXPECT_EQ("bcdefghijk", res->body);
  2401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2402. }
  2403. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2404. // entire resource, while the original httpbin returned 200. Both are
  2405. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2406. {
  2407. Headers headers = {make_range_header({{0, 31}})};
  2408. auto res = cli.Get(path, headers);
  2409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2410. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2411. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2412. res->status == StatusCode::PartialContent_206);
  2413. }
  2414. {
  2415. Headers headers = {make_range_header({{0, -1}})};
  2416. auto res = cli.Get(path, headers);
  2417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2418. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2419. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2420. res->status == StatusCode::PartialContent_206);
  2421. }
  2422. // go-httpbin returns 206 with clamped range for over-range requests,
  2423. // while the original httpbin returned 416. Both behaviors are observed
  2424. // in real servers, so we only verify the request succeeds.
  2425. {
  2426. Headers headers = {make_range_header({{0, 32}})};
  2427. auto res = cli.Get(path, headers);
  2428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2429. }
  2430. }
  2431. TEST(RangeTest, IgnoredForPost) {
  2432. Server svr;
  2433. svr.Post("/", [](const Request &, Response &res) {
  2434. res.set_content("abcdefg", "text/plain");
  2435. });
  2436. auto port = svr.bind_to_any_port(HOST);
  2437. ASSERT_GT(port, 0);
  2438. thread t = thread([&] { svr.listen_after_bind(); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. t.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, port);
  2446. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2447. auto res = cli.Post("/", Headers{{"Range", range}});
  2448. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2449. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2450. EXPECT_EQ("abcdefg", res->body) << range;
  2451. }
  2452. }
  2453. TEST(RangeTest, IgnoredForUnknownUnit) {
  2454. Server svr;
  2455. svr.Get("/", [](const Request &, Response &res) {
  2456. res.set_content("abcdefg", "text/plain");
  2457. });
  2458. auto port = svr.bind_to_any_port(HOST);
  2459. ASSERT_GT(port, 0);
  2460. thread t = thread([&] { svr.listen_after_bind(); });
  2461. auto se = detail::scope_exit([&] {
  2462. svr.stop();
  2463. t.join();
  2464. ASSERT_FALSE(svr.is_running());
  2465. });
  2466. svr.wait_until_ready();
  2467. Client cli(HOST, port);
  2468. for (auto range : {"items=1-2", "none=x"}) {
  2469. auto res = cli.Get("/", Headers{{"Range", range}});
  2470. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2471. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2472. EXPECT_EQ("abcdefg", res->body) << range;
  2473. }
  2474. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2475. ASSERT_TRUE(res) << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2477. }
  2478. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2479. auto host = "unresolvableaddress.local";
  2480. auto path = std::string{"/"};
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. auto port = 443;
  2483. SSLClient cli(host, port);
  2484. #else
  2485. auto port = 80;
  2486. Client cli(host, port);
  2487. #endif
  2488. cli.set_connection_timeout(1);
  2489. {
  2490. auto res = cli.Get(path);
  2491. ASSERT_FALSE(res);
  2492. }
  2493. std::this_thread::sleep_for(std::chrono::seconds(8));
  2494. }
  2495. #if defined(__linux__) && defined(__GLIBC__) && \
  2496. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2497. // Forward declaration: in split builds split.py strips `inline` and moves the
  2498. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2499. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2500. // against the symbol in both header-only and split builds.
  2501. namespace httplib {
  2502. namespace detail {
  2503. int getaddrinfo_with_timeout(const char *node, const char *service,
  2504. const struct addrinfo *hints,
  2505. struct addrinfo **res, time_t timeout_sec);
  2506. } // namespace detail
  2507. } // namespace httplib
  2508. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2509. //
  2510. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2511. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2512. // gai_suspend() call hits the connection timeout the function calls
  2513. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2514. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2515. // still alive and still references the now-destroyed stack frame.
  2516. //
  2517. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2518. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2519. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2520. // and runs them in a container.
  2521. namespace {
  2522. bool should_run_issue_2431_tests() {
  2523. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2524. return v && *v && std::string(v) != "0";
  2525. }
  2526. std::string unique_unresolvable_host(int n) {
  2527. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2528. // glibc still asks the configured nameserver — which is exactly the path
  2529. // we want to exercise. A unique label per call avoids the resolver cache.
  2530. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2531. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2532. std::to_string(n) + ".invalid";
  2533. }
  2534. } // namespace
  2535. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2536. if (!should_run_issue_2431_tests()) {
  2537. GTEST_SKIP()
  2538. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2539. }
  2540. for (int i = 0; i < 8; ++i) {
  2541. struct addrinfo hints;
  2542. memset(&hints, 0, sizeof(hints));
  2543. hints.ai_family = AF_UNSPEC;
  2544. hints.ai_socktype = SOCK_STREAM;
  2545. auto host = unique_unresolvable_host(i);
  2546. struct addrinfo *result = nullptr;
  2547. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2548. &result, /*timeout_sec=*/1);
  2549. if (rc == 0 && result) { freeaddrinfo(result); }
  2550. }
  2551. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2552. // stack region they still believe holds their gaicb.
  2553. std::this_thread::sleep_for(std::chrono::seconds(3));
  2554. }
  2555. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2556. if (!should_run_issue_2431_tests()) {
  2557. GTEST_SKIP()
  2558. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2559. }
  2560. std::atomic<bool> stop{false};
  2561. std::vector<std::thread> threads;
  2562. for (int t = 0; t < 8; ++t) {
  2563. threads.emplace_back([t, &stop] {
  2564. int i = 0;
  2565. while (!stop.load(std::memory_order_relaxed)) {
  2566. struct addrinfo hints;
  2567. memset(&hints, 0, sizeof(hints));
  2568. hints.ai_family = AF_UNSPEC;
  2569. hints.ai_socktype = SOCK_STREAM;
  2570. auto host = unique_unresolvable_host(t * 100000 + i++);
  2571. struct addrinfo *result = nullptr;
  2572. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2573. &result, /*timeout_sec=*/1);
  2574. if (rc == 0 && result) { freeaddrinfo(result); }
  2575. }
  2576. });
  2577. }
  2578. std::this_thread::sleep_for(std::chrono::seconds(8));
  2579. stop.store(true, std::memory_order_relaxed);
  2580. for (auto &th : threads) {
  2581. th.join();
  2582. }
  2583. std::this_thread::sleep_for(std::chrono::seconds(3));
  2584. }
  2585. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2586. if (!should_run_issue_2431_tests()) {
  2587. GTEST_SKIP()
  2588. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2589. }
  2590. std::atomic<bool> stop{false};
  2591. std::vector<std::thread> threads;
  2592. for (int t = 0; t < 8; ++t) {
  2593. threads.emplace_back([t, &stop] {
  2594. int i = 0;
  2595. while (!stop.load(std::memory_order_relaxed)) {
  2596. auto host = unique_unresolvable_host(t * 100000 + i++);
  2597. Client cli(host, 80);
  2598. cli.set_connection_timeout(1, 0);
  2599. cli.set_read_timeout(1, 0);
  2600. cli.set_write_timeout(1, 0);
  2601. (void)cli.Get("/");
  2602. }
  2603. });
  2604. }
  2605. std::this_thread::sleep_for(std::chrono::seconds(8));
  2606. stop.store(true, std::memory_order_relaxed);
  2607. for (auto &th : threads) {
  2608. th.join();
  2609. }
  2610. std::this_thread::sleep_for(std::chrono::seconds(3));
  2611. }
  2612. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2613. TEST(ConnectionErrorTest, InvalidHost) {
  2614. auto host = "-abcde.com";
  2615. #ifdef CPPHTTPLIB_SSL_ENABLED
  2616. auto port = 443;
  2617. SSLClient cli(host, port);
  2618. #else
  2619. auto port = 80;
  2620. Client cli(host, port);
  2621. #endif
  2622. cli.set_connection_timeout(std::chrono::seconds(2));
  2623. auto res = cli.Get("/");
  2624. ASSERT_TRUE(!res);
  2625. EXPECT_EQ(Error::Connection, res.error());
  2626. }
  2627. TEST(ConnectionErrorTest, InvalidHost2) {
  2628. auto host = "httpcan.org/";
  2629. #ifdef CPPHTTPLIB_SSL_ENABLED
  2630. SSLClient cli(host);
  2631. #else
  2632. Client cli(host);
  2633. #endif
  2634. cli.set_connection_timeout(std::chrono::seconds(2));
  2635. auto res = cli.Get("/");
  2636. ASSERT_TRUE(!res);
  2637. EXPECT_EQ(Error::Connection, res.error());
  2638. }
  2639. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2640. auto host = "httpcan.org/";
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. SSLClient cli(host);
  2643. #else
  2644. Client cli(host);
  2645. #endif
  2646. cli.set_connection_timeout(std::chrono::seconds(2));
  2647. auto res = cli.Get("/");
  2648. ASSERT_TRUE(!res);
  2649. stringstream s;
  2650. s << "error code: " << res.error();
  2651. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2652. }
  2653. TEST(ConnectionErrorTest, InvalidPort) {
  2654. auto host = "localhost";
  2655. auto port = 44380;
  2656. #ifdef CPPHTTPLIB_SSL_ENABLED
  2657. SSLClient cli(host, port);
  2658. #else
  2659. Client cli(host, port);
  2660. #endif
  2661. cli.set_connection_timeout(std::chrono::seconds(2));
  2662. auto res = cli.Get("/");
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_TRUE(Error::Connection == res.error() ||
  2665. Error::ConnectionTimeout == res.error());
  2666. }
  2667. TEST(ConnectionErrorTest, Timeout_Online) {
  2668. auto host = "google.com";
  2669. #ifdef CPPHTTPLIB_SSL_ENABLED
  2670. auto port = 44380;
  2671. SSLClient cli(host, port);
  2672. #else
  2673. auto port = 8080;
  2674. Client cli(host, port);
  2675. #endif
  2676. cli.set_connection_timeout(std::chrono::seconds(2));
  2677. // only probe one address type so that the error reason
  2678. // correlates to the timed-out IPv4, not the unsupported
  2679. // IPv6 connection attempt
  2680. cli.set_address_family(AF_INET);
  2681. auto res = cli.Get("/");
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2684. }
  2685. TEST(CancelTest, NoCancel_Online) {
  2686. auto host = "httpbingo.org";
  2687. auto path = std::string{"/range/32"};
  2688. #ifdef CPPHTTPLIB_SSL_ENABLED
  2689. auto port = 443;
  2690. SSLClient cli(host, port);
  2691. #else
  2692. auto port = 80;
  2693. Client cli(host, port);
  2694. #endif
  2695. cli.set_connection_timeout(std::chrono::seconds(5));
  2696. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2698. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2699. EXPECT_EQ(StatusCode::OK_200, res->status);
  2700. }
  2701. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2702. // Use /bytes with a large payload so that the DownloadProgress callback
  2703. // (which only fires for Content-Length responses) is invoked before the
  2704. // entire body is received, giving cancellation a chance to fire.
  2705. auto host = "httpbingo.org";
  2706. auto path = std::string{"/bytes/524288"};
  2707. #ifdef CPPHTTPLIB_SSL_ENABLED
  2708. auto port = 443;
  2709. SSLClient cli(host, port);
  2710. #else
  2711. auto port = 80;
  2712. Client cli(host, port);
  2713. #endif
  2714. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2715. cli.set_connection_timeout(std::chrono::seconds(5));
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_EQ(Error::Canceled, res.error());
  2718. }
  2719. TEST(CancelTest, WithCancelLargePayload_Online) {
  2720. auto host = "httpbingo.org";
  2721. auto path = std::string{"/bytes/524288"};
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. auto port = 443;
  2724. SSLClient cli(host, port);
  2725. #else
  2726. auto port = 80;
  2727. Client cli(host, port);
  2728. #endif
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. uint32_t count = 0;
  2731. auto res =
  2732. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelPost) {
  2737. Server svr;
  2738. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2758. Server svr;
  2759. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadPost) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. TEST(CancelTest, NoCancelPut) {
  2800. Server svr;
  2801. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("Hello World!", "text/plain");
  2803. });
  2804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2805. auto se = detail::scope_exit([&] {
  2806. svr.stop();
  2807. thread.join();
  2808. ASSERT_FALSE(svr.is_running());
  2809. });
  2810. svr.wait_until_ready();
  2811. Client cli(HOST, PORT);
  2812. cli.set_connection_timeout(std::chrono::seconds(5));
  2813. auto res =
  2814. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2815. "application/json", [](uint64_t, uint64_t) { return true; });
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ("Hello World!", res->body);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. }
  2820. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2821. Server svr;
  2822. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2823. res.set_content("Hello World!", "text/plain");
  2824. });
  2825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2826. auto se = detail::scope_exit([&] {
  2827. svr.stop();
  2828. thread.join();
  2829. ASSERT_FALSE(svr.is_running());
  2830. });
  2831. svr.wait_until_ready();
  2832. Client cli(HOST, PORT);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. TEST(CancelTest, WithCancelLargePayloadPut) {
  2841. Server svr;
  2842. svr.set_payload_max_length(200 * 1024 * 1024);
  2843. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2844. res.set_content(LARGE_DATA, "text/plain");
  2845. });
  2846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(HOST, PORT);
  2854. cli.set_payload_max_length(200 * 1024 * 1024);
  2855. cli.set_connection_timeout(std::chrono::seconds(5));
  2856. auto res =
  2857. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2858. "application/json", [](uint64_t, uint64_t) { return false; });
  2859. ASSERT_TRUE(!res);
  2860. EXPECT_EQ(Error::Canceled, res.error());
  2861. }
  2862. TEST(CancelTest, NoCancelPatch) {
  2863. Server svr;
  2864. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2865. res.set_content("Hello World!", "text/plain");
  2866. });
  2867. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2868. auto se = detail::scope_exit([&] {
  2869. svr.stop();
  2870. thread.join();
  2871. ASSERT_FALSE(svr.is_running());
  2872. });
  2873. svr.wait_until_ready();
  2874. Client cli(HOST, PORT);
  2875. cli.set_connection_timeout(std::chrono::seconds(5));
  2876. auto res =
  2877. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2878. "application/json", [](uint64_t, uint64_t) { return true; });
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ("Hello World!", res->body);
  2881. EXPECT_EQ(StatusCode::OK_200, res->status);
  2882. }
  2883. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2884. Server svr;
  2885. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. thread.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. Client cli(HOST, PORT);
  2896. cli.set_connection_timeout(std::chrono::seconds(5));
  2897. auto res =
  2898. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2899. "application/json", [](uint64_t, uint64_t) { return false; });
  2900. ASSERT_TRUE(!res);
  2901. EXPECT_EQ(Error::Canceled, res.error());
  2902. }
  2903. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2904. Server svr;
  2905. svr.set_payload_max_length(200 * 1024 * 1024);
  2906. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2907. res.set_content(LARGE_DATA, "text/plain");
  2908. });
  2909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2910. auto se = detail::scope_exit([&] {
  2911. svr.stop();
  2912. thread.join();
  2913. ASSERT_FALSE(svr.is_running());
  2914. });
  2915. svr.wait_until_ready();
  2916. Client cli(HOST, PORT);
  2917. cli.set_payload_max_length(200 * 1024 * 1024);
  2918. cli.set_connection_timeout(std::chrono::seconds(5));
  2919. auto res =
  2920. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2921. "application/json", [](uint64_t, uint64_t) { return false; });
  2922. ASSERT_TRUE(!res);
  2923. EXPECT_EQ(Error::Canceled, res.error());
  2924. }
  2925. TEST(CancelTest, NoCancelDelete) {
  2926. Server svr;
  2927. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2928. res.set_content("Hello World!", "text/plain");
  2929. });
  2930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2931. auto se = detail::scope_exit([&] {
  2932. svr.stop();
  2933. thread.join();
  2934. ASSERT_FALSE(svr.is_running());
  2935. });
  2936. svr.wait_until_ready();
  2937. Client cli(HOST, PORT);
  2938. cli.set_connection_timeout(std::chrono::seconds(5));
  2939. auto res =
  2940. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2941. "application/json", [](uint64_t, uint64_t) { return true; });
  2942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2943. EXPECT_EQ("Hello World!", res->body);
  2944. EXPECT_EQ(StatusCode::OK_200, res->status);
  2945. }
  2946. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2947. Server svr;
  2948. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2949. res.set_content("Hello World!", "text/plain");
  2950. });
  2951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2952. auto se = detail::scope_exit([&] {
  2953. svr.stop();
  2954. thread.join();
  2955. ASSERT_FALSE(svr.is_running());
  2956. });
  2957. svr.wait_until_ready();
  2958. Client cli(HOST, PORT);
  2959. cli.set_connection_timeout(std::chrono::seconds(5));
  2960. auto res =
  2961. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2962. "application/json", [](uint64_t, uint64_t) { return false; });
  2963. ASSERT_TRUE(!res);
  2964. EXPECT_EQ(Error::Canceled, res.error());
  2965. }
  2966. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2967. Server svr;
  2968. svr.set_payload_max_length(200 * 1024 * 1024);
  2969. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2970. res.set_content(LARGE_DATA, "text/plain");
  2971. });
  2972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2973. auto se = detail::scope_exit([&] {
  2974. svr.stop();
  2975. thread.join();
  2976. ASSERT_FALSE(svr.is_running());
  2977. });
  2978. svr.wait_until_ready();
  2979. Client cli(HOST, PORT);
  2980. cli.set_payload_max_length(200 * 1024 * 1024);
  2981. cli.set_connection_timeout(std::chrono::seconds(5));
  2982. auto res =
  2983. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2984. "application/json", [](uint64_t, uint64_t) { return false; });
  2985. ASSERT_TRUE(!res);
  2986. EXPECT_EQ(Error::Canceled, res.error());
  2987. }
  2988. // One stop() from another thread ends a request that waits for the response
  2989. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2990. Server svr;
  2991. std::atomic<bool> received{false};
  2992. std::atomic<bool> done{false};
  2993. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2994. received.store(true);
  2995. while (!done.load()) {
  2996. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2997. }
  2998. res.set_content("Hello World!", "text/plain");
  2999. });
  3000. auto port = svr.bind_to_any_port(HOST);
  3001. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3002. Client cli(HOST, port);
  3003. cli.set_read_timeout(std::chrono::seconds(30));
  3004. std::future<Result> request;
  3005. auto se = detail::scope_exit([&] {
  3006. done.store(true);
  3007. svr.stop();
  3008. thread.join();
  3009. ASSERT_FALSE(svr.is_running());
  3010. });
  3011. svr.wait_until_ready();
  3012. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3013. for (int i = 0; i < 500 && !received.load(); ++i) {
  3014. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3015. }
  3016. ASSERT_TRUE(received.load());
  3017. // Let the client block in the wait for the response
  3018. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3019. auto start = std::chrono::steady_clock::now();
  3020. cli.stop();
  3021. ASSERT_EQ(std::future_status::ready,
  3022. request.wait_for(std::chrono::seconds(5)));
  3023. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3024. auto res = request.get();
  3025. ASSERT_TRUE(!res);
  3026. EXPECT_EQ(Error::Read, res.error());
  3027. }
  3028. static std::string remove_whitespace(const std::string &input) {
  3029. std::string output;
  3030. output.reserve(input.size());
  3031. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3032. [](unsigned char c) { return !std::isspace(c); });
  3033. return output;
  3034. }
  3035. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3036. auto host = "httpbingo.org";
  3037. auto path = std::string{"/basic-auth/hello/world"};
  3038. #ifdef CPPHTTPLIB_SSL_ENABLED
  3039. auto port = 443;
  3040. SSLClient cli(host, port);
  3041. #else
  3042. auto port = 80;
  3043. Client cli(host, port);
  3044. #endif
  3045. {
  3046. auto res = cli.Get(path);
  3047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3048. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3049. }
  3050. {
  3051. auto res = cli.Get(
  3052. path, Headers{make_basic_authentication_header("hello", "world")});
  3053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3054. auto body = remove_whitespace(res->body);
  3055. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3056. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. }
  3059. {
  3060. cli.set_basic_auth("hello", "world");
  3061. auto res = cli.Get(path);
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. auto body = remove_whitespace(res->body);
  3064. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3065. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3066. EXPECT_EQ(StatusCode::OK_200, res->status);
  3067. }
  3068. {
  3069. cli.set_basic_auth("hello", "bad");
  3070. auto res = cli.Get(path);
  3071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3072. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3073. }
  3074. {
  3075. cli.set_basic_auth("bad", "world");
  3076. auto res = cli.Get(path);
  3077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3078. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3079. }
  3080. }
  3081. #ifdef CPPHTTPLIB_SSL_ENABLED
  3082. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3083. auto host = "httpbingo.org";
  3084. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3085. auto paths = std::vector<std::string>{
  3086. "/digest-auth/auth/hello/world/MD5",
  3087. "/digest-auth/auth/hello/world/SHA-256",
  3088. };
  3089. auto port = 443;
  3090. SSLClient cli(host, port);
  3091. {
  3092. auto res = cli.Get(unauth_path);
  3093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3094. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3095. }
  3096. {
  3097. cli.set_digest_auth("hello", "world");
  3098. for (const auto &path : paths) {
  3099. auto res = cli.Get(path.c_str());
  3100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3101. auto body = remove_whitespace(res->body);
  3102. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3103. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3104. EXPECT_EQ(StatusCode::OK_200, res->status);
  3105. }
  3106. cli.set_digest_auth("hello", "bad");
  3107. for (const auto &path : paths) {
  3108. auto res = cli.Get(path.c_str());
  3109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3110. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3111. }
  3112. }
  3113. }
  3114. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3115. // comma-separated list of challenges, and each challenge may itself carry a
  3116. // comma-separated auth-param list, so a server can legally offer Basic
  3117. // before Digest, either as two field lines or packed into one. Runs one 401
  3118. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3119. // value() joins them in receipt order) and checks that the retry carries a
  3120. // well-formed Digest Authorization header naming expected_realm.
  3121. static void
  3122. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3123. const std::string &expected_realm) {
  3124. std::atomic<int> hits{0};
  3125. Server svr;
  3126. svr.Get("/x", [&](const Request &req, Response &res) {
  3127. if (++hits == 1) {
  3128. res.status = StatusCode::Unauthorized_401;
  3129. for (const auto &challenge : challenges) {
  3130. res.set_header("WWW-Authenticate", challenge);
  3131. }
  3132. } else {
  3133. auto authorization = req.get_header_value("Authorization");
  3134. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3135. EXPECT_NE(std::string::npos,
  3136. authorization.find("realm=\"" + expected_realm + "\""));
  3137. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3138. res.set_content("ok", "text/plain");
  3139. }
  3140. });
  3141. auto port = svr.bind_to_any_port(HOST);
  3142. std::thread t([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. t.join();
  3146. });
  3147. svr.wait_until_ready();
  3148. Client cli(HOST, port);
  3149. cli.set_digest_auth("hello", "world");
  3150. auto res = cli.Get("/x");
  3151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3152. EXPECT_EQ(2, hits.load());
  3153. }
  3154. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3155. static const char *kDigestChallenge =
  3156. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3157. "algorithm=MD5";
  3158. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3159. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3160. "testrealm");
  3161. }
  3162. // Same challenge list with the schemes in the opposite order, to make sure
  3163. // the fix above didn't just special-case "Basic first".
  3164. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3165. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3166. "testrealm");
  3167. }
  3168. // A comma inside a quoted auth-param value must not be mistaken for the
  3169. // separator between two challenges (or two auth-params).
  3170. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3171. run_digest_challenge_list_test(
  3172. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3173. "algorithm=MD5"},
  3174. "test,realm");
  3175. }
  3176. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3177. // the params and leaves out the fragment.
  3178. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3179. Server svr;
  3180. std::string uri, target;
  3181. svr.Get("/a b", [&](const Request &req, Response &res) {
  3182. auto auth = req.get_header_value("Authorization");
  3183. if (auth.empty()) {
  3184. res.status = StatusCode::Unauthorized_401;
  3185. res.set_header("WWW-Authenticate",
  3186. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3187. return;
  3188. }
  3189. auto b = auth.find("uri=\"") + 5;
  3190. uri = auth.substr(b, auth.find('"', b) - b);
  3191. target = req.target;
  3192. });
  3193. auto port = svr.bind_to_any_port(HOST);
  3194. std::thread t([&]() { svr.listen_after_bind(); });
  3195. auto se = detail::scope_exit([&] {
  3196. svr.stop();
  3197. t.join();
  3198. });
  3199. svr.wait_until_ready();
  3200. Client cli(HOST, port);
  3201. cli.set_digest_auth("hello", "world");
  3202. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3204. EXPECT_EQ("/a%20b?x=1", target);
  3205. EXPECT_EQ(target, uri);
  3206. }
  3207. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3208. // make_digest_authentication_header() dereferences both unconditionally, so
  3209. // a server sending a challenge missing either one must not be treated as
  3210. // usable -- doing so used to crash the client with std::out_of_range.
  3211. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3212. Server svr;
  3213. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3214. res.status = StatusCode::Unauthorized_401;
  3215. res.set_header("WWW-Authenticate", challenge);
  3216. });
  3217. auto port = svr.bind_to_any_port(HOST);
  3218. std::thread t([&]() { svr.listen_after_bind(); });
  3219. auto se = detail::scope_exit([&] {
  3220. svr.stop();
  3221. t.join();
  3222. });
  3223. svr.wait_until_ready();
  3224. Client cli(HOST, port);
  3225. cli.set_digest_auth("hello", "world");
  3226. auto res = cli.Get("/x");
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3229. }
  3230. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3231. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3232. }
  3233. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3234. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3235. }
  3236. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3237. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3238. }
  3239. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3240. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3241. // when storing the values, so the header builder has to re-escape them (and
  3242. // keep algorithm a bare token); otherwise the value breaks out of its
  3243. // quoted-string and injects extra auth-params into the client's Authorization.
  3244. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3245. std::atomic<int> hits{0};
  3246. std::string authorization;
  3247. Server svr;
  3248. svr.Get("/x", [&](const Request &req, Response &res) {
  3249. if (++hits == 1) {
  3250. res.status = StatusCode::Unauthorized_401;
  3251. // On the wire the quotes embedded in the values are backslash-escaped.
  3252. res.set_header("WWW-Authenticate",
  3253. "Digest realm=\"testrealm\", "
  3254. "nonce=\"n\\\"; injected=\\\"x\", "
  3255. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3256. } else {
  3257. authorization = req.get_header_value("Authorization");
  3258. res.set_content("ok", "text/plain");
  3259. }
  3260. });
  3261. auto port = svr.bind_to_any_port(HOST);
  3262. std::thread t([&]() { svr.listen_after_bind(); });
  3263. auto se = detail::scope_exit([&] {
  3264. svr.stop();
  3265. t.join();
  3266. });
  3267. svr.wait_until_ready();
  3268. Client cli(HOST, port);
  3269. cli.set_digest_auth("hello", "world");
  3270. auto res = cli.Get("/x");
  3271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3272. EXPECT_EQ(2, hits.load());
  3273. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3274. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3275. // inside its quoted-string rather than starting an "injected" auth-param.
  3276. EXPECT_NE(std::string::npos,
  3277. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3278. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3279. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3280. }
  3281. #endif
  3282. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3283. auto host = "google.com";
  3284. auto another_host = "example.com";
  3285. auto wrong_ip = "0.0.0.0";
  3286. #ifdef CPPHTTPLIB_SSL_ENABLED
  3287. SSLClient cli(host);
  3288. #else
  3289. Client cli(host);
  3290. #endif
  3291. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3292. auto res = cli.Get("/");
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3295. }
  3296. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3297. auto host = "google.com";
  3298. auto wrong_ip = "0.0.0.0";
  3299. #ifdef CPPHTTPLIB_SSL_ENABLED
  3300. SSLClient cli(host);
  3301. #else
  3302. Client cli(host);
  3303. #endif
  3304. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3305. auto res = cli.Get("/");
  3306. ASSERT_TRUE(!res);
  3307. EXPECT_EQ(Error::Connection, res.error());
  3308. }
  3309. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3310. // A mapped value that is not an IP literal must be resolved. "localhost"
  3311. // resolves from the hosts file, so this test needs no external DNS.
  3312. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3313. auto host = "target.invalid";
  3314. Server svr;
  3315. std::string received_host;
  3316. svr.Get("/hi", [&](const Request &req, Response &res) {
  3317. received_host = req.get_header_value("Host");
  3318. res.set_content("Hello World!", "text/plain");
  3319. });
  3320. auto port = svr.bind_to_any_port(HOST);
  3321. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3322. auto se = detail::scope_exit([&] {
  3323. svr.stop();
  3324. thread.join();
  3325. ASSERT_FALSE(svr.is_running());
  3326. });
  3327. svr.wait_until_ready();
  3328. Client cli(host, port);
  3329. cli.set_direct_hostname_addr_map({{host, HOST}});
  3330. auto res = cli.Get("/hi");
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::OK_200, res->status);
  3333. // The mapping only redirects the connection; the identity stays host_.
  3334. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3335. }
  3336. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3337. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3338. auto host = "target.invalid";
  3339. Server svr;
  3340. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3341. res.set_content("Hello World!", "text/plain");
  3342. });
  3343. auto port = svr.bind_to_any_port("127.0.0.1");
  3344. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3345. auto se = detail::scope_exit([&] {
  3346. svr.stop();
  3347. thread.join();
  3348. ASSERT_FALSE(svr.is_running());
  3349. });
  3350. svr.wait_until_ready();
  3351. Client cli(host, port);
  3352. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3353. auto res = cli.Get("/hi");
  3354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3355. EXPECT_EQ(StatusCode::OK_200, res->status);
  3356. }
  3357. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3358. // An empty mapped value must leave host_ as the connection target. Without
  3359. // that guard the empty value would become the host argument, getaddrinfo
  3360. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3361. // loopback - silently connecting somewhere the caller never asked for.
  3362. // The server listens on loopback, so such a fallback would succeed and is
  3363. // therefore observable as a failure of this test.
  3364. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3365. Server svr;
  3366. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3367. res.set_content("Hello World!", "text/plain");
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. thread.join();
  3374. ASSERT_FALSE(svr.is_running());
  3375. });
  3376. svr.wait_until_ready();
  3377. Client cli(blackhole, port);
  3378. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3379. cli.set_connection_timeout(1);
  3380. auto res = cli.Get("/hi");
  3381. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3382. }
  3383. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3384. auto host = "target.invalid";
  3385. Server svr;
  3386. std::string received_host;
  3387. svr.Get("/hi", [&](const Request &req, Response &res) {
  3388. received_host = req.get_header_value("Host");
  3389. res.set_content("Hello World!", "text/plain");
  3390. });
  3391. auto port = svr.bind_to_any_port("127.0.0.1");
  3392. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3393. auto se = detail::scope_exit([&] {
  3394. svr.stop();
  3395. thread.join();
  3396. ASSERT_FALSE(svr.is_running());
  3397. });
  3398. svr.wait_until_ready();
  3399. Client cli(host, port);
  3400. #pragma GCC diagnostic push
  3401. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3402. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3403. #pragma GCC diagnostic pop
  3404. auto res = cli.Get("/hi");
  3405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3406. EXPECT_EQ(StatusCode::OK_200, res->status);
  3407. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3408. }
  3409. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3410. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3411. Server svr;
  3412. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3413. res.set_content("Hello World!", "text/plain");
  3414. });
  3415. auto port = svr.bind_to_any_port("127.0.0.1");
  3416. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. thread.join();
  3420. ASSERT_FALSE(svr.is_running());
  3421. });
  3422. svr.wait_until_ready();
  3423. Client cli("127.0.0.1", port);
  3424. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3425. cli.set_connection_timeout(1);
  3426. auto res = cli.Get("/hi");
  3427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3428. EXPECT_EQ(StatusCode::OK_200, res->status);
  3429. }
  3430. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3431. auto host = "httpbingo.org";
  3432. auto path = std::string{"/absolute-redirect/3"};
  3433. #ifdef CPPHTTPLIB_SSL_ENABLED
  3434. SSLClient cli(host);
  3435. #else
  3436. Client cli(host);
  3437. #endif
  3438. cli.set_follow_location(true);
  3439. auto res = cli.Get(path);
  3440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3441. EXPECT_EQ(StatusCode::OK_200, res->status);
  3442. }
  3443. TEST(RedirectTest, Redirect_Online) {
  3444. auto host = "httpbingo.org";
  3445. auto path = std::string{"/redirect/3"};
  3446. #ifdef CPPHTTPLIB_SSL_ENABLED
  3447. SSLClient cli(host);
  3448. #else
  3449. Client cli(host);
  3450. #endif
  3451. cli.set_follow_location(true);
  3452. auto res = cli.Get(path);
  3453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. }
  3456. TEST(RelativeRedirectTest, Redirect_Online) {
  3457. auto host = "httpbingo.org";
  3458. auto path = std::string{"/relative-redirect/3"};
  3459. #ifdef CPPHTTPLIB_SSL_ENABLED
  3460. SSLClient cli(host);
  3461. #else
  3462. Client cli(host);
  3463. #endif
  3464. cli.set_follow_location(true);
  3465. auto res = cli.Get(path);
  3466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. }
  3469. TEST(TooManyRedirectTest, Redirect_Online) {
  3470. auto host = "httpbingo.org";
  3471. auto path = std::string{"/redirect/21"};
  3472. #ifdef CPPHTTPLIB_SSL_ENABLED
  3473. SSLClient cli(host);
  3474. #else
  3475. Client cli(host);
  3476. #endif
  3477. cli.set_follow_location(true);
  3478. auto res = cli.Get(path);
  3479. ASSERT_TRUE(!res);
  3480. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3481. }
  3482. #ifdef CPPHTTPLIB_SSL_ENABLED
  3483. TEST(YahooRedirectTest, Redirect_Online) {
  3484. Client cli("yahoo.com");
  3485. auto res = cli.Get("/");
  3486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3487. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3488. cli.set_follow_location(true);
  3489. res = cli.Get("/");
  3490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3491. EXPECT_EQ(StatusCode::OK_200, res->status);
  3492. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3493. }
  3494. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3495. #define REDIR_HOST "httpbingo.org"
  3496. #define REDIR_PATH "/redirect-to"
  3497. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3498. SSLClient cli(REDIR_HOST);
  3499. cli.set_follow_location(true);
  3500. auto res =
  3501. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3503. EXPECT_EQ(StatusCode::OK_200, res->status);
  3504. }
  3505. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3506. SSLClient cli(REDIR_HOST);
  3507. cli.set_follow_location(true);
  3508. Params params;
  3509. params.emplace("url", "http://example.com");
  3510. params.emplace("status_code", "302");
  3511. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3513. EXPECT_EQ(StatusCode::OK_200, res->status);
  3514. }
  3515. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3516. SSLClient cli(REDIR_HOST);
  3517. cli.set_follow_location(true);
  3518. Params params;
  3519. params.emplace("url", "http://example.com");
  3520. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. }
  3524. TEST(UrlWithSpace, Redirect_Online) {
  3525. SSLClient cli("edge.forgecdn.net");
  3526. cli.set_follow_location(true);
  3527. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3531. }
  3532. #endif
  3533. #if !defined(_WIN32) && !defined(_WIN64)
  3534. TEST(ReceiveSignals, Signal) {
  3535. auto setupSignalHandlers = []() {
  3536. struct sigaction act;
  3537. sigemptyset(&act.sa_mask);
  3538. act.sa_flags = SA_SIGINFO;
  3539. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3540. switch (sig) {
  3541. case SIGINT:
  3542. default: break;
  3543. }
  3544. };
  3545. ::sigaction(SIGINT, &act, nullptr);
  3546. };
  3547. Server svr;
  3548. int port = 0;
  3549. auto thread = std::thread([&]() {
  3550. setupSignalHandlers();
  3551. port = svr.bind_to_any_port(HOST);
  3552. svr.listen_after_bind();
  3553. });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. ASSERT_TRUE(svr.is_running());
  3561. pthread_kill(thread.native_handle(), SIGINT);
  3562. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3563. ASSERT_TRUE(svr.is_running());
  3564. }
  3565. #endif
  3566. TEST(RedirectToDifferentPort, Redirect) {
  3567. Server svr1;
  3568. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3569. res.set_content("Hello World!", "text/plain");
  3570. });
  3571. int svr1_port = 0;
  3572. auto thread1 = std::thread([&]() {
  3573. svr1_port = svr1.bind_to_any_port(HOST);
  3574. svr1.listen_after_bind();
  3575. });
  3576. Server svr2;
  3577. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3578. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3579. });
  3580. int svr2_port = 0;
  3581. auto thread2 = std::thread([&]() {
  3582. svr2_port = svr2.bind_to_any_port(HOST);
  3583. svr2.listen_after_bind();
  3584. });
  3585. auto se = detail::scope_exit([&] {
  3586. svr2.stop();
  3587. thread2.join();
  3588. svr1.stop();
  3589. thread1.join();
  3590. ASSERT_FALSE(svr2.is_running());
  3591. ASSERT_FALSE(svr1.is_running());
  3592. });
  3593. svr1.wait_until_ready();
  3594. svr2.wait_until_ready();
  3595. Client cli("localhost", svr2_port);
  3596. cli.set_follow_location(true);
  3597. auto res = cli.Get("/2");
  3598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("Hello World!", res->body);
  3601. }
  3602. // GET /redir on one server redirects to /target on another port, so the
  3603. // client follows it with a new client.
  3604. static Result
  3605. GetThroughRedirectToDifferentPort(Server::Handler target,
  3606. const std::function<void(Client &)> &setup,
  3607. const Headers &headers = Headers()) {
  3608. Server target_svr;
  3609. target_svr.Get("/target", target);
  3610. int target_port = 0;
  3611. auto target_thread = std::thread([&]() {
  3612. target_port = target_svr.bind_to_any_port(HOST);
  3613. target_svr.listen_after_bind();
  3614. });
  3615. Server origin_svr;
  3616. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3617. res.set_redirect(
  3618. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3619. });
  3620. int origin_port = 0;
  3621. auto origin_thread = std::thread([&]() {
  3622. origin_port = origin_svr.bind_to_any_port(HOST);
  3623. origin_svr.listen_after_bind();
  3624. });
  3625. auto se = detail::scope_exit([&] {
  3626. origin_svr.stop();
  3627. origin_thread.join();
  3628. target_svr.stop();
  3629. target_thread.join();
  3630. });
  3631. target_svr.wait_until_ready();
  3632. origin_svr.wait_until_ready();
  3633. Client cli("localhost", origin_port);
  3634. cli.set_follow_location(true);
  3635. setup(cli);
  3636. return cli.Get("/redir", headers);
  3637. }
  3638. static void
  3639. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3640. std::string captured_authorization;
  3641. auto result = GetThroughRedirectToDifferentPort(
  3642. [&](const Request &req, Response &res) {
  3643. captured_authorization = req.get_header_value("Authorization");
  3644. res.set_content("OK", "text/plain");
  3645. },
  3646. set_auth);
  3647. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3648. EXPECT_EQ(StatusCode::OK_200, result->status);
  3649. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3650. EXPECT_TRUE(captured_authorization.empty());
  3651. }
  3652. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3653. TestDoNotForwardCredentialsOnRedirect(
  3654. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3655. }
  3656. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3657. TestDoNotForwardCredentialsOnRedirect(
  3658. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3659. }
  3660. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3661. std::string captured_cookie;
  3662. auto result = GetThroughRedirectToDifferentPort(
  3663. [&](const Request &req, Response &res) {
  3664. captured_cookie = req.get_header_value("Cookie");
  3665. res.set_content("OK", "text/plain");
  3666. },
  3667. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3668. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3669. EXPECT_EQ(StatusCode::OK_200, result->status);
  3670. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3671. EXPECT_TRUE(captured_cookie.empty());
  3672. }
  3673. TEST(RedirectToSamePort, ForwardCookie) {
  3674. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3675. // header so that ordinary session flows keep working.
  3676. Server svr;
  3677. std::string captured_cookie;
  3678. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3679. res.set_redirect("/target", 302);
  3680. });
  3681. svr.Get("/target", [&](const Request &req, Response &res) {
  3682. captured_cookie = req.get_header_value("Cookie");
  3683. res.set_content("OK", "text/plain");
  3684. });
  3685. auto port = svr.bind_to_any_port(HOST);
  3686. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3687. auto se = detail::scope_exit([&] {
  3688. svr.stop();
  3689. thread.join();
  3690. ASSERT_FALSE(svr.is_running());
  3691. });
  3692. svr.wait_until_ready();
  3693. Client cli(HOST, port);
  3694. cli.set_follow_location(true);
  3695. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3696. auto res = cli.Get("/redir", headers);
  3697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3698. EXPECT_EQ(StatusCode::OK_200, res->status);
  3699. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3700. }
  3701. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3702. // The Location alone names the next target, on any origin.
  3703. Server target_svr;
  3704. std::string cross_target;
  3705. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3706. cross_target = req.target;
  3707. res.set_content("OK", "text/plain");
  3708. });
  3709. auto target_port = target_svr.bind_to_any_port(HOST);
  3710. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3711. Server origin_svr;
  3712. std::string same_target;
  3713. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3714. res.set_redirect(
  3715. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3716. });
  3717. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3718. res.set_redirect("/landing", 302);
  3719. });
  3720. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3721. same_target = req.target;
  3722. res.set_content("OK", "text/plain");
  3723. });
  3724. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3725. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3726. auto se = detail::scope_exit([&] {
  3727. origin_svr.stop();
  3728. origin_thread.join();
  3729. target_svr.stop();
  3730. target_thread.join();
  3731. });
  3732. target_svr.wait_until_ready();
  3733. origin_svr.wait_until_ready();
  3734. Client cli("localhost", origin_port);
  3735. cli.set_follow_location(true);
  3736. Request req;
  3737. req.method = "GET";
  3738. req.params = {{"api_key", "SECRET"}};
  3739. req.path = "/cross";
  3740. auto res = cli.send(req);
  3741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3742. EXPECT_EQ("/landing", cross_target);
  3743. req.path = "/same";
  3744. res = cli.send(req);
  3745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3746. EXPECT_EQ("/landing", same_target);
  3747. }
  3748. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3749. std::string authorization;
  3750. std::string trace_id;
  3751. auto result = GetThroughRedirectToDifferentPort(
  3752. [&](const Request &req, Response &res) {
  3753. authorization = req.get_header_value("Authorization");
  3754. trace_id = req.get_header_value("X-Trace-Id");
  3755. res.set_content("OK", "text/plain");
  3756. },
  3757. [](Client &cli) {
  3758. cli.set_default_headers(
  3759. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3760. });
  3761. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3762. EXPECT_EQ(StatusCode::OK_200, result->status);
  3763. // Like a header given with the request, a default one goes along unless it
  3764. // carries credentials (RFC 9110 15.4).
  3765. EXPECT_TRUE(authorization.empty());
  3766. EXPECT_EQ("42", trace_id);
  3767. }
  3768. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3769. auto result = GetThroughRedirectToDifferentPort(
  3770. [](const Request &, Response &res) {
  3771. res.set_content(std::string(2048, 'x'), "text/plain");
  3772. },
  3773. [](Client &cli) { cli.set_payload_max_length(1024); });
  3774. EXPECT_FALSE(result);
  3775. }
  3776. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3777. auto result = GetThroughRedirectToDifferentPort(
  3778. [](const Request &req, Response &res) {
  3779. // Answer after a second, or once the client gives up.
  3780. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3781. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3782. }
  3783. res.set_content("late", "text/plain");
  3784. },
  3785. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3786. ASSERT_FALSE(result);
  3787. EXPECT_EQ(Error::Read, result.error());
  3788. }
  3789. #ifdef CPPHTTPLIB_SSL_ENABLED
  3790. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3791. auto result = GetThroughRedirectToDifferentPort(
  3792. [](const Request &, Response &res) {
  3793. res.status = StatusCode::Unauthorized_401;
  3794. res.set_header("WWW-Authenticate",
  3795. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3796. },
  3797. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3798. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3799. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3800. }
  3801. #endif
  3802. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3803. Server svr;
  3804. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3805. // Port number that overflows int — should not crash
  3806. res.set_redirect("http://localhost:99999999999999999999/target");
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. Client cli(HOST, port);
  3817. cli.set_follow_location(true);
  3818. auto res = cli.Get("/redir");
  3819. // Should fail gracefully, not crash (no valid response due to bad port)
  3820. EXPECT_FALSE(res);
  3821. }
  3822. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3823. Server svr;
  3824. auto port = svr.bind_to_any_port(HOST);
  3825. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3826. // The server's own port followed by junk must not be followed
  3827. res.set_redirect("http://" + std::string(HOST) + ":" +
  3828. std::to_string(port) + "junk/target");
  3829. });
  3830. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3831. res.set_content("target", "text/plain");
  3832. });
  3833. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. Client cli(HOST, port);
  3841. cli.set_follow_location(true);
  3842. auto res = cli.Get("/redir");
  3843. EXPECT_FALSE(res);
  3844. }
  3845. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3846. Server svr;
  3847. std::atomic<bool> followed{false};
  3848. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3849. res.status = StatusCode::NotModified_304;
  3850. res.set_header("Location", "/target");
  3851. });
  3852. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3853. res.status = StatusCode::UseProxy_305;
  3854. res.set_header("Location", "/target");
  3855. });
  3856. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3857. followed = true;
  3858. res.set_content("target", "text/plain");
  3859. });
  3860. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3861. auto se = detail::scope_exit([&] {
  3862. svr.stop();
  3863. th.join();
  3864. ASSERT_FALSE(svr.is_running());
  3865. });
  3866. svr.wait_until_ready();
  3867. Client cli("localhost", PORT);
  3868. cli.set_follow_location(true);
  3869. auto res = cli.Get("/304");
  3870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3871. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3872. res = cli.Get("/305");
  3873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3874. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3875. EXPECT_FALSE(followed);
  3876. }
  3877. TEST(RedirectFromPageWithContent, Redirect) {
  3878. Server svr;
  3879. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3880. res.set_content("___", "text/plain");
  3881. res.set_redirect("/2");
  3882. });
  3883. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3884. res.set_content("Hello World!", "text/plain");
  3885. });
  3886. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. th.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. Client cli("localhost", PORT);
  3895. cli.set_follow_location(true);
  3896. std::string body;
  3897. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3898. body.append(data, data_length);
  3899. return true;
  3900. });
  3901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3902. EXPECT_EQ(StatusCode::OK_200, res->status);
  3903. EXPECT_EQ("Hello World!", body);
  3904. }
  3905. {
  3906. Client cli("localhost", PORT);
  3907. std::string body;
  3908. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3909. body.append(data, data_length);
  3910. return true;
  3911. });
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::Found_302, res->status);
  3914. EXPECT_EQ("___", body);
  3915. }
  3916. }
  3917. // A server can close the connection after a request with "Connection: close"
  3918. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3919. // redirected request must go out on a new connection.
  3920. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3921. #ifndef _WIN32
  3922. signal(SIGPIPE, SIG_IGN);
  3923. #endif
  3924. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3925. default_socket_options(srv);
  3926. sockaddr_in addr{};
  3927. addr.sin_family = AF_INET;
  3928. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3929. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3930. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3931. ASSERT_EQ(0, ::listen(srv, 2));
  3932. auto send_text = [](socket_t sock, const std::string &text) {
  3933. ::send(sock,
  3934. #ifdef _WIN32
  3935. static_cast<const char *>(text.c_str()),
  3936. static_cast<int>(text.size()),
  3937. #else
  3938. text.c_str(), text.size(),
  3939. #endif
  3940. 0);
  3941. };
  3942. auto reused = false;
  3943. auto server_thread = std::thread([&] {
  3944. char buf[4096];
  3945. auto first = ::accept(srv, nullptr, nullptr);
  3946. if (first == INVALID_SOCKET) { return; }
  3947. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3948. ::recv(first, buf, sizeof(buf), 0);
  3949. send_text(
  3950. first,
  3951. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3952. auto next = first;
  3953. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3954. reused = true;
  3955. } else {
  3956. detail::close_socket(first);
  3957. next = ::accept(srv, nullptr, nullptr);
  3958. if (next == INVALID_SOCKET) { return; }
  3959. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3960. ::recv(next, buf, sizeof(buf), 0);
  3961. }
  3962. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3963. "Connection: close\r\n\r\nok");
  3964. detail::close_socket(next);
  3965. });
  3966. Client cli("127.0.0.1", PORT + 2);
  3967. cli.set_follow_location(true);
  3968. cli.set_read_timeout(5, 0);
  3969. auto res = cli.Get("/1");
  3970. server_thread.join();
  3971. detail::close_socket(srv);
  3972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3973. EXPECT_EQ(StatusCode::OK_200, res->status);
  3974. EXPECT_EQ("ok", res->body);
  3975. EXPECT_FALSE(reused);
  3976. }
  3977. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3978. Server svr;
  3979. auto port_str = std::to_string(PORT);
  3980. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3981. auto expected_host = "[::1]:" + port_str;
  3982. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3983. res.set_content("___", "text/plain");
  3984. // res.set_redirect("/2");
  3985. res.set_redirect(redirect_url);
  3986. });
  3987. svr.Get("/2", [&](const Request &req, Response &res) {
  3988. auto host_header = req.headers.find("Host");
  3989. ASSERT_TRUE(host_header != req.headers.end());
  3990. EXPECT_EQ(expected_host, host_header->second);
  3991. res.set_content("Hello World!", "text/plain");
  3992. });
  3993. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3994. auto se = detail::scope_exit([&] {
  3995. svr.stop();
  3996. th.join();
  3997. ASSERT_FALSE(svr.is_running());
  3998. });
  3999. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4000. // actually starts anything, so the condition !svr.is_running() will
  4001. // always remain true, and the loop never stops.
  4002. // This basically counts how many milliseconds have passed since the
  4003. // call to svr.listen(), and if after 5 seconds nothing started yet
  4004. // aborts the test.
  4005. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4006. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4007. ASSERT_LT(milliseconds, 5000U);
  4008. }
  4009. {
  4010. Client cli("::1", PORT);
  4011. cli.set_follow_location(true);
  4012. std::string body;
  4013. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4014. body.append(data, data_length);
  4015. return true;
  4016. });
  4017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4018. EXPECT_EQ(StatusCode::OK_200, res->status);
  4019. EXPECT_EQ("Hello World!", body);
  4020. }
  4021. {
  4022. Client cli("::1", PORT);
  4023. std::string body;
  4024. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4025. body.append(data, data_length);
  4026. return true;
  4027. });
  4028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4029. EXPECT_EQ(StatusCode::Found_302, res->status);
  4030. EXPECT_EQ("___", body);
  4031. }
  4032. }
  4033. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4034. Server svr;
  4035. svr.Get("/foo", [](const Request &req, Response &res) {
  4036. auto a = req.params.find("a");
  4037. if (a != req.params.end()) {
  4038. res.set_content((*a).second, "text/plain");
  4039. res.status = StatusCode::OK_200;
  4040. } else {
  4041. res.status = StatusCode::BadRequest_400;
  4042. }
  4043. });
  4044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4045. auto se = detail::scope_exit([&] {
  4046. svr.stop();
  4047. thread.join();
  4048. ASSERT_FALSE(svr.is_running());
  4049. });
  4050. svr.wait_until_ready();
  4051. {
  4052. Client cli(HOST, PORT);
  4053. cli.set_path_encode(false);
  4054. auto res = cli.Get("/foo?a=explicitly+encoded");
  4055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4056. EXPECT_EQ(StatusCode::OK_200, res->status);
  4057. // This expects it back with a space, as the `+` won't have been
  4058. // url-encoded, and server-side the params get decoded turning `+`
  4059. // into spaces.
  4060. EXPECT_EQ("explicitly encoded", res->body);
  4061. }
  4062. }
  4063. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4064. // When path encoding is disabled the client must transmit the supplied
  4065. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4066. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4067. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4068. // than a space (0x20). Assert on the raw wire target to catch this.
  4069. Server svr;
  4070. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4071. svr.Get("/foo", [&](const Request &req, Response &res) {
  4072. EXPECT_EQ(expected_target, req.target);
  4073. res.status = StatusCode::OK_200;
  4074. });
  4075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4076. auto se = detail::scope_exit([&] {
  4077. svr.stop();
  4078. thread.join();
  4079. ASSERT_FALSE(svr.is_running());
  4080. });
  4081. svr.wait_until_ready();
  4082. {
  4083. Client cli(HOST, PORT);
  4084. cli.set_path_encode(false);
  4085. auto res = cli.Get(expected_target.c_str());
  4086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4087. EXPECT_EQ(StatusCode::OK_200, res->status);
  4088. }
  4089. }
  4090. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4091. // `open_stream()` used to skip the path encoding that the buffered send
  4092. // path applies, so the same `path` produced different bytes in the request
  4093. // line depending on which API was used. Assert the two agree.
  4094. Server svr;
  4095. std::string target;
  4096. svr.Get(".*", [&](const Request &req, Response &res) {
  4097. target = req.target;
  4098. res.status = StatusCode::OK_200;
  4099. });
  4100. auto port = svr.bind_to_any_port(HOST);
  4101. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. thread.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. struct {
  4109. const char *path;
  4110. const char *expected;
  4111. } cases[] = {
  4112. {"/a b?x=1", "/a%20b?x=1"},
  4113. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4114. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4115. };
  4116. for (const auto &c : cases) {
  4117. Client cli(HOST, port);
  4118. target.clear();
  4119. auto res = cli.Get(c.path);
  4120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4121. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4122. auto buffered_target = target;
  4123. target.clear();
  4124. auto handle = cli.open_stream("GET", c.path);
  4125. EXPECT_TRUE(handle.is_valid())
  4126. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4127. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4128. }
  4129. }
  4130. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4131. // The `set_path_encode(false)` contract — transmit the supplied target
  4132. // verbatim — must hold for the streaming API too.
  4133. Server svr;
  4134. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4135. std::string target;
  4136. svr.Get("/foo", [&](const Request &req, Response &res) {
  4137. target = req.target;
  4138. res.status = StatusCode::OK_200;
  4139. });
  4140. auto port = svr.bind_to_any_port(HOST);
  4141. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4142. auto se = detail::scope_exit([&] {
  4143. svr.stop();
  4144. thread.join();
  4145. ASSERT_FALSE(svr.is_running());
  4146. });
  4147. svr.wait_until_ready();
  4148. {
  4149. Client cli(HOST, port);
  4150. cli.set_path_encode(false);
  4151. auto handle = cli.open_stream("GET", expected_target);
  4152. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4153. EXPECT_EQ(expected_target, target);
  4154. }
  4155. }
  4156. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4157. // With path encoding enabled a CR/LF in the target is percent-encoded
  4158. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4159. // write_request_line still backstops `set_path_encode(false)`, which is
  4160. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4161. Server svr;
  4162. // Captured before routing: the decoded path contains a newline, which a
  4163. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4164. std::string target;
  4165. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4166. target = req.target;
  4167. res.status = StatusCode::OK_200;
  4168. return Server::HandlerResponse::Handled;
  4169. });
  4170. auto port = svr.bind_to_any_port(HOST);
  4171. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4172. auto se = detail::scope_exit([&] {
  4173. svr.stop();
  4174. thread.join();
  4175. ASSERT_FALSE(svr.is_running());
  4176. });
  4177. svr.wait_until_ready();
  4178. {
  4179. Client cli(HOST, port);
  4180. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4181. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4182. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4183. }
  4184. }
  4185. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4186. // Every control character is percent-encoded, not just CR/LF, so the target
  4187. // passes the request-target check in write_request_line.
  4188. Server svr;
  4189. std::string target;
  4190. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4191. target = req.target;
  4192. res.status = StatusCode::OK_200;
  4193. return Server::HandlerResponse::Handled;
  4194. });
  4195. auto port = svr.bind_to_any_port(HOST);
  4196. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4197. auto se = detail::scope_exit([&] {
  4198. svr.stop();
  4199. thread.join();
  4200. ASSERT_FALSE(svr.is_running());
  4201. });
  4202. svr.wait_until_ready();
  4203. {
  4204. Client cli(HOST, port);
  4205. auto res = cli.Get("/a\tb\x1b\x7f");
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ("/a%09b%1B%7F", target);
  4208. }
  4209. }
  4210. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4211. // Nothing may reach the wire: a raw CR/LF target would split the request
  4212. // line and inject headers.
  4213. Server svr;
  4214. // Pre-routing so that "not called" means nothing reached the server at all,
  4215. // rather than merely failing to match a handler pattern.
  4216. auto handler_called = false;
  4217. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4218. handler_called = true;
  4219. res.status = StatusCode::OK_200;
  4220. return Server::HandlerResponse::Handled;
  4221. });
  4222. auto port = svr.bind_to_any_port(HOST);
  4223. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4224. auto se = detail::scope_exit([&] {
  4225. svr.stop();
  4226. thread.join();
  4227. ASSERT_FALSE(svr.is_running());
  4228. });
  4229. svr.wait_until_ready();
  4230. {
  4231. Client cli(HOST, port);
  4232. cli.set_path_encode(false);
  4233. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4234. EXPECT_FALSE(handle.is_valid());
  4235. EXPECT_EQ(Error::Write, handle.error);
  4236. EXPECT_FALSE(handler_called);
  4237. }
  4238. }
  4239. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4240. // Which of the two branches runs is decided by whether the query component
  4241. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4242. // an empty query and must still fall back to building one from
  4243. // `req.params`, while a non-empty query must win over `req.params`.
  4244. Server svr;
  4245. std::string target;
  4246. svr.Get("/foo", [&](const Request &req, Response &res) {
  4247. target = req.target;
  4248. res.status = StatusCode::OK_200;
  4249. });
  4250. auto port = svr.bind_to_any_port(HOST);
  4251. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4252. auto se = detail::scope_exit([&] {
  4253. svr.stop();
  4254. thread.join();
  4255. ASSERT_FALSE(svr.is_running());
  4256. });
  4257. svr.wait_until_ready();
  4258. {
  4259. // Trailing `?` -> empty query component -> `req.params` is used.
  4260. Client cli(HOST, port);
  4261. Request req;
  4262. req.method = "GET";
  4263. req.path = "/foo?";
  4264. req.params.emplace("a", "1");
  4265. target.clear();
  4266. auto res = cli.send(req);
  4267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4268. EXPECT_EQ("/foo?a=1", target);
  4269. }
  4270. {
  4271. // Non-empty query in `req.path` -> `req.params` is not appended.
  4272. Client cli(HOST, port);
  4273. Request req;
  4274. req.method = "GET";
  4275. req.path = "/foo?b=2";
  4276. req.params.emplace("a", "1");
  4277. target.clear();
  4278. auto res = cli.send(req);
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ("/foo?b=2", target);
  4281. }
  4282. }
  4283. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4284. Server svr;
  4285. svr.Get("/", [](const Request &req, Response &) {
  4286. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4287. });
  4288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. thread.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. {
  4296. Client cli(HOST, PORT);
  4297. cli.set_path_encode(false);
  4298. auto res = cli.Get("/?something=%0A");
  4299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4300. EXPECT_EQ(StatusCode::OK_200, res->status);
  4301. }
  4302. }
  4303. TEST(BindServerTest, BindDualStack) {
  4304. Server svr;
  4305. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4306. res.set_content("Hello World!", "text/plain");
  4307. });
  4308. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4309. auto se = detail::scope_exit([&] {
  4310. svr.stop();
  4311. thread.join();
  4312. ASSERT_FALSE(svr.is_running());
  4313. });
  4314. svr.wait_until_ready();
  4315. {
  4316. Client cli("127.0.0.1", PORT);
  4317. auto res = cli.Get("/1");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. EXPECT_EQ("Hello World!", res->body);
  4321. }
  4322. {
  4323. Client cli("::1", PORT);
  4324. auto res = cli.Get("/1");
  4325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ("Hello World!", res->body);
  4328. }
  4329. }
  4330. TEST(BindServerTest, BindAndListenSeparately) {
  4331. Server svr;
  4332. int port = svr.bind_to_any_port("0.0.0.0");
  4333. ASSERT_TRUE(svr.is_valid());
  4334. ASSERT_TRUE(port > 0);
  4335. svr.stop();
  4336. }
  4337. // Reports whether anything is still listening on a loopback port. A plain
  4338. // connect() is used instead of a Client request because a socket left bound by
  4339. // mistake accepts the connection into its backlog and never answers, which
  4340. // would hang the test instead of failing it.
  4341. static bool is_loopback_port_accepting(int port) {
  4342. sockaddr_in addr{};
  4343. addr.sin_family = AF_INET;
  4344. addr.sin_port = htons(static_cast<uint16_t>(port));
  4345. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4346. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4347. EXPECT_NE(sock, INVALID_SOCKET);
  4348. if (sock == INVALID_SOCKET) { return false; }
  4349. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4350. static_cast<socklen_t>(sizeof(addr)));
  4351. detail::close_socket(sock);
  4352. return ret == 0;
  4353. }
  4354. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4355. Server svr;
  4356. auto port = svr.bind_to_any_port("127.0.0.1");
  4357. ASSERT_TRUE(port > 0);
  4358. svr.stop();
  4359. // bind_to_any_port() already called listen(2), so until stop() closed the
  4360. // descriptor the port kept accepting connections into the backlog. ASSERT
  4361. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4362. // below blocks forever in the accept loop.
  4363. ASSERT_FALSE(is_loopback_port_accepting(port));
  4364. // Nothing is left to accept on, so listen_after_bind() must report failure
  4365. // instead of returning success without ever serving.
  4366. EXPECT_FALSE(svr.listen_after_bind());
  4367. // The failed listen marks the server decommissioned, so a waiter returns
  4368. // instead of spinning forever.
  4369. svr.wait_until_ready();
  4370. }
  4371. #ifdef CPPHTTPLIB_SSL_ENABLED
  4372. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4374. CLIENT_CA_CERT_DIR);
  4375. int port = svr.bind_to_any_port("0.0.0.0");
  4376. ASSERT_TRUE(svr.is_valid());
  4377. ASSERT_TRUE(port > 0);
  4378. svr.stop();
  4379. }
  4380. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4381. // or a rejected CustomRoute() registration would not stop the server binding.
  4382. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4384. CLIENT_CA_CERT_DIR);
  4385. ASSERT_TRUE(svr.is_valid());
  4386. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4387. EXPECT_FALSE(svr.is_valid());
  4388. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4389. }
  4390. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4391. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4392. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4393. int port = svr.bind_to_any_port("0.0.0.0");
  4394. ASSERT_TRUE(svr.is_valid());
  4395. ASSERT_TRUE(port > 0);
  4396. svr.stop();
  4397. }
  4398. TEST(BindServerTest, UpdateCertsPem) {
  4399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4400. int port = svr.bind_to_any_port("0.0.0.0");
  4401. ASSERT_TRUE(svr.is_valid());
  4402. ASSERT_TRUE(port > 0);
  4403. // Read PEM files
  4404. std::string cert_pem, key_pem, ca_pem;
  4405. read_file(SERVER_CERT_FILE, cert_pem);
  4406. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4407. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4408. // Update server certificates using PEM API
  4409. ASSERT_TRUE(
  4410. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4411. ASSERT_TRUE(svr.is_valid());
  4412. svr.stop();
  4413. }
  4414. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4415. // Start server with client CA (enables client auth)
  4416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4417. ASSERT_TRUE(svr.is_valid());
  4418. bool handler_called = false;
  4419. svr.Get("/test", [&](const Request &req, Response &res) {
  4420. handler_called = true;
  4421. // Verify client certificate is present
  4422. auto cert = req.peer_cert();
  4423. EXPECT_TRUE(static_cast<bool>(cert));
  4424. res.set_content("ok", "text/plain");
  4425. });
  4426. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4427. auto se = detail::scope_exit([&] {
  4428. svr.stop();
  4429. t.join();
  4430. ASSERT_FALSE(svr.is_running());
  4431. });
  4432. svr.wait_until_ready();
  4433. // Read PEM files
  4434. std::string cert_pem, key_pem, ca_pem;
  4435. read_file(SERVER_CERT_FILE, cert_pem);
  4436. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4437. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4438. // Update server certificates and client CA using PEM API while server running
  4439. ASSERT_TRUE(
  4440. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4441. // Connect with client certificate
  4442. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4443. cli.enable_server_certificate_verification(false);
  4444. cli.set_connection_timeout(30);
  4445. auto res = cli.Get("/test");
  4446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4447. ASSERT_EQ(StatusCode::OK_200, res->status);
  4448. ASSERT_TRUE(handler_called);
  4449. EXPECT_EQ("ok", res->body);
  4450. }
  4451. // Puts a CA that did not sign the client's certificate in the old one's place.
  4452. static bool replace_client_ca(SSLServer &svr) {
  4453. std::string cert_pem, key_pem, ca_pem;
  4454. read_file(SERVER_CERT_FILE, cert_pem);
  4455. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4456. read_file(SERVER_CERT2_FILE, ca_pem);
  4457. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4458. ca_pem.c_str());
  4459. }
  4460. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4462. ASSERT_TRUE(svr.is_valid());
  4463. svr.Get("/test", [](const Request &, Response &res) {
  4464. res.set_content("ok", "text/plain");
  4465. });
  4466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4467. auto se = detail::scope_exit([&] {
  4468. svr.stop();
  4469. t.join();
  4470. ASSERT_FALSE(svr.is_running());
  4471. });
  4472. svr.wait_until_ready();
  4473. auto get = [] {
  4474. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4475. cli.enable_server_certificate_verification(false);
  4476. return cli.Get("/test");
  4477. };
  4478. ASSERT_TRUE(get());
  4479. ASSERT_TRUE(replace_client_ca(svr));
  4480. EXPECT_FALSE(get());
  4481. }
  4482. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4483. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4485. ASSERT_TRUE(svr.is_valid());
  4486. tls::set_verify_callback(svr.tls_context(),
  4487. [](const tls::VerifyContext &) -> bool {
  4488. throw std::runtime_error("verify");
  4489. });
  4490. svr.Get("/test", [](const Request &, Response &res) {
  4491. res.set_content("ok", "text/plain");
  4492. });
  4493. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4494. auto se = detail::scope_exit([&] {
  4495. svr.stop();
  4496. t.join();
  4497. ASSERT_FALSE(svr.is_running());
  4498. });
  4499. svr.wait_until_ready();
  4500. auto get = [] {
  4501. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4502. cli.enable_server_certificate_verification(false);
  4503. return cli.Get("/test");
  4504. };
  4505. EXPECT_FALSE(get());
  4506. // The handshake is over, so an update does not wait for it.
  4507. std::string cert_pem, key_pem;
  4508. read_file(SERVER_CERT_FILE, cert_pem);
  4509. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4510. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4511. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4512. return v.preverify_ok;
  4513. });
  4514. auto res = get();
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. EXPECT_EQ("ok", res->body);
  4517. }
  4518. #endif
  4519. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4520. // Sends each request over a new connection with a client certificate,
  4521. // resuming the session of the one before when there is one.
  4522. class ResumingClient {
  4523. public:
  4524. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4525. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4526. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4527. SSL_FILETYPE_PEM);
  4528. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4529. // callback, not through SSL_get1_session().
  4530. SSL_CTX_set_app_data(ctx_, this);
  4531. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4532. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4533. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4534. auto self = static_cast<ResumingClient *>(
  4535. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4536. SSL_SESSION_free(self->session_);
  4537. self->session_ = session;
  4538. return 1; // Keeps the reference
  4539. });
  4540. }
  4541. ~ResumingClient() {
  4542. SSL_SESSION_free(session_);
  4543. SSL_CTX_free(ctx_);
  4544. }
  4545. // Tells whether the request was answered.
  4546. bool get() {
  4547. auto error = Error::Success;
  4548. auto sock = detail::create_client_socket(
  4549. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4550. /*connection_timeout_sec=*/5, 0,
  4551. /*read_timeout_sec=*/5, 0,
  4552. /*write_timeout_sec=*/5, 0, std::string(), error);
  4553. if (sock == INVALID_SOCKET) { return false; }
  4554. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4555. auto ssl = SSL_new(ctx_);
  4556. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4557. SSL_set_fd(ssl, static_cast<int>(sock));
  4558. if (session_) { SSL_set_session(ssl, session_); }
  4559. if (SSL_connect(ssl) != 1) { return false; }
  4560. reused_ = SSL_session_reused(ssl) == 1;
  4561. // Reading the response also takes in a TLS 1.3 session ticket.
  4562. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4563. "Connection: close\r\n\r\n";
  4564. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4565. std::string res;
  4566. char buf[256];
  4567. int n;
  4568. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4569. res.append(buf, static_cast<size_t>(n));
  4570. }
  4571. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4572. SSL_shutdown(ssl);
  4573. return res.find("200 OK") != std::string::npos;
  4574. }
  4575. // Whether the last connection resumed a session
  4576. bool reused() const { return reused_; }
  4577. private:
  4578. SSL_CTX *ctx_;
  4579. SSL_SESSION *session_ = nullptr;
  4580. bool reused_ = false;
  4581. };
  4582. // A client that resumes its session gets through, but not once the client CA
  4583. // has changed, as a resumed session does not show the certificate again.
  4584. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4586. ASSERT_TRUE(svr.is_valid());
  4587. svr.Get("/test", [](const Request &, Response &res) {
  4588. res.set_content("ok", "text/plain");
  4589. });
  4590. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4591. auto se = detail::scope_exit([&] {
  4592. svr.stop();
  4593. t.join();
  4594. ASSERT_FALSE(svr.is_running());
  4595. });
  4596. svr.wait_until_ready();
  4597. ResumingClient cli;
  4598. ASSERT_TRUE(cli.get());
  4599. ASSERT_TRUE(cli.get());
  4600. EXPECT_TRUE(cli.reused());
  4601. ASSERT_TRUE(replace_client_ca(svr));
  4602. EXPECT_FALSE(cli.get());
  4603. }
  4604. // A resumed session does not show the certificate again, so the server does
  4605. // not resume one with a verify callback to run on it.
  4606. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4608. ASSERT_TRUE(svr.is_valid());
  4609. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4610. return v.preverify_ok;
  4611. });
  4612. svr.Get("/test", [](const Request &, Response &res) {
  4613. res.set_content("ok", "text/plain");
  4614. });
  4615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4616. auto se = detail::scope_exit([&] {
  4617. svr.stop();
  4618. t.join();
  4619. ASSERT_FALSE(svr.is_running());
  4620. });
  4621. svr.wait_until_ready();
  4622. ResumingClient cli;
  4623. ASSERT_TRUE(cli.get());
  4624. ASSERT_TRUE(cli.get());
  4625. EXPECT_FALSE(cli.reused());
  4626. }
  4627. #endif
  4628. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4629. // wolfSSL shares its session cache between contexts, so a resumed session
  4630. // could carry a client certificate checked against another server's CA, or
  4631. // against a client CA since replaced.
  4632. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4634. ASSERT_TRUE(svr.is_valid());
  4635. // Trusts a CA that did not sign the client's certificate.
  4636. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4637. ASSERT_TRUE(other.is_valid());
  4638. for (auto s : {&svr, &other}) {
  4639. s->Get("/test", [](const Request &, Response &res) {
  4640. res.set_content("ok", "text/plain");
  4641. });
  4642. }
  4643. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4644. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4645. auto se = detail::scope_exit([&] {
  4646. other.stop();
  4647. svr.stop();
  4648. t2.join();
  4649. t.join();
  4650. });
  4651. svr.wait_until_ready();
  4652. other.wait_until_ready();
  4653. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4654. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4655. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4656. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4657. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4658. ASSERT_EQ(WOLFSSL_SUCCESS,
  4659. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4660. WOLFSSL_FILETYPE_PEM));
  4661. WOLFSSL_SESSION *session = nullptr;
  4662. auto session_se = detail::scope_exit([&] {
  4663. if (session) { wolfSSL_SESSION_free(session); }
  4664. });
  4665. // A request over a new connection, resuming `session` when there is one and
  4666. // keeping the connection's own in its place. Tells whether it was answered.
  4667. auto get = [&](int port) {
  4668. auto error = Error::Success;
  4669. auto sock = detail::create_client_socket(
  4670. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4671. /*connection_timeout_sec=*/5, 0,
  4672. /*read_timeout_sec=*/5, 0,
  4673. /*write_timeout_sec=*/5, 0, std::string(), error);
  4674. if (sock == INVALID_SOCKET) { return false; }
  4675. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4676. auto ssl = wolfSSL_new(ctx);
  4677. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4678. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4679. if (session) { wolfSSL_set_session(ssl, session); }
  4680. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4681. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4682. "Connection: close\r\n\r\n";
  4683. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4684. std::string res;
  4685. char buf[256];
  4686. int n;
  4687. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4688. res.append(buf, static_cast<size_t>(n));
  4689. }
  4690. wolfSSL_shutdown(ssl);
  4691. if (session) { wolfSSL_SESSION_free(session); }
  4692. session = wolfSSL_get1_session(ssl);
  4693. return res.find("200 OK") != std::string::npos;
  4694. };
  4695. ASSERT_TRUE(get(PORT));
  4696. EXPECT_FALSE(get(PORT + 1));
  4697. ASSERT_TRUE(get(PORT));
  4698. ASSERT_TRUE(replace_client_ca(svr));
  4699. EXPECT_FALSE(get(PORT));
  4700. }
  4701. #endif
  4702. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4704. ASSERT_TRUE(svr.is_valid());
  4705. svr.Get("/test", [](const Request &, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4709. auto se = detail::scope_exit([&] {
  4710. svr.stop();
  4711. t.join();
  4712. ASSERT_FALSE(svr.is_running());
  4713. });
  4714. svr.wait_until_ready();
  4715. // A connection that sends no ClientHello keeps its handshake in progress,
  4716. // once the server has had a moment to start it.
  4717. auto error = Error::Success;
  4718. auto sock = detail::create_client_socket(
  4719. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4720. /*connection_timeout_sec=*/5, 0,
  4721. /*read_timeout_sec=*/5, 0,
  4722. /*write_timeout_sec=*/5, 0, std::string(), error);
  4723. ASSERT_NE(INVALID_SOCKET, sock);
  4724. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4725. std::string cert_pem, key_pem;
  4726. read_file(SERVER_CERT_FILE, cert_pem);
  4727. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4728. auto update = std::async(std::launch::async, [&]() {
  4729. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4730. });
  4731. EXPECT_EQ(std::future_status::timeout,
  4732. update.wait_for(std::chrono::milliseconds(200)));
  4733. detail::close_socket(sock);
  4734. EXPECT_TRUE(update.get());
  4735. SSLClient cli(HOST, PORT);
  4736. cli.enable_server_certificate_verification(false);
  4737. auto res = cli.Get("/test");
  4738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4739. EXPECT_EQ(StatusCode::OK_200, res->status);
  4740. }
  4741. #endif
  4742. TEST(ErrorHandlerTest, ContentLength) {
  4743. Server svr;
  4744. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4745. res.status = StatusCode::OK_200;
  4746. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4747. "text/html"); // <= Content-Length still 13
  4748. });
  4749. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4750. res.set_content("Hello World!\n", "text/plain");
  4751. res.status = 524;
  4752. });
  4753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4754. auto se = detail::scope_exit([&] {
  4755. svr.stop();
  4756. thread.join();
  4757. ASSERT_FALSE(svr.is_running());
  4758. });
  4759. svr.wait_until_ready();
  4760. {
  4761. Client cli(HOST, PORT);
  4762. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4766. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4767. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4768. }
  4769. }
  4770. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4771. TEST(ExceptionTest, WithoutExceptionHandler) {
  4772. Server svr;
  4773. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4774. throw std::runtime_error("exception...");
  4775. });
  4776. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4777. throw std::runtime_error("exception\r\n...");
  4778. });
  4779. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4780. auto se = detail::scope_exit([&] {
  4781. svr.stop();
  4782. listen_thread.join();
  4783. ASSERT_FALSE(svr.is_running());
  4784. });
  4785. svr.wait_until_ready();
  4786. Client cli("localhost", PORT);
  4787. {
  4788. auto res = cli.Get("/exception");
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4791. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4792. }
  4793. {
  4794. auto res = cli.Get("/unknown");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4797. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4798. }
  4799. }
  4800. TEST(ExceptionTest, WithExceptionHandler) {
  4801. Server svr;
  4802. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4803. std::exception_ptr ep) {
  4804. EXPECT_FALSE(ep == nullptr);
  4805. try {
  4806. std::rethrow_exception(ep);
  4807. } catch (std::exception &e) {
  4808. EXPECT_EQ("abc", std::string(e.what()));
  4809. } catch (...) {}
  4810. res.status = StatusCode::InternalServerError_500;
  4811. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4812. "text/html"); // <= Content-Length still 13 at this point
  4813. });
  4814. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4815. res.set_content("Hello World!\n", "text/plain");
  4816. throw std::runtime_error("abc");
  4817. });
  4818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4819. auto se = detail::scope_exit([&] {
  4820. svr.stop();
  4821. thread.join();
  4822. ASSERT_FALSE(svr.is_running());
  4823. });
  4824. svr.wait_until_ready();
  4825. for (size_t i = 0; i < 10; i++) {
  4826. Client cli(HOST, PORT);
  4827. for (size_t j = 0; j < 100; j++) {
  4828. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4831. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4832. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4833. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4834. }
  4835. cli.set_keep_alive(true);
  4836. for (size_t j = 0; j < 100; j++) {
  4837. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4840. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4841. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4842. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4843. }
  4844. }
  4845. }
  4846. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4847. Server svr;
  4848. svr.set_exception_handler(
  4849. [](const Request &, Response &res, std::exception_ptr) {
  4850. res.set_content("oops", "text/plain");
  4851. });
  4852. svr.Get("/throw", [](const Request &, Response &) {
  4853. throw std::runtime_error("throw");
  4854. });
  4855. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4856. res.status = StatusCode::Created_201;
  4857. throw std::runtime_error("created-then-throw");
  4858. });
  4859. auto port = svr.bind_to_any_port(HOST);
  4860. ASSERT_GT(port, 0);
  4861. thread t = thread([&] { svr.listen_after_bind(); });
  4862. auto se = detail::scope_exit([&] {
  4863. svr.stop();
  4864. t.join();
  4865. ASSERT_FALSE(svr.is_running());
  4866. });
  4867. svr.wait_until_ready();
  4868. Client cli(HOST, port);
  4869. for (auto path : {"/throw", "/created-then-throw"}) {
  4870. auto res = cli.Get(path);
  4871. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4872. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4873. }
  4874. }
  4875. TEST(ExceptionTest, AndErrorHandler) {
  4876. Server svr;
  4877. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4878. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4879. });
  4880. svr.set_exception_handler(
  4881. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4882. EXPECT_FALSE(ep == nullptr);
  4883. try {
  4884. std::rethrow_exception(ep);
  4885. } catch (std::exception &e) {
  4886. res.set_content(e.what(), "text/html");
  4887. } catch (...) {}
  4888. res.status = StatusCode::InternalServerError_500;
  4889. });
  4890. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4891. throw std::runtime_error("EXCEPTION");
  4892. });
  4893. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4894. res.set_content("ERROR", "text/html");
  4895. res.status = StatusCode::InternalServerError_500;
  4896. });
  4897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4898. auto se = detail::scope_exit([&] {
  4899. svr.stop();
  4900. thread.join();
  4901. ASSERT_FALSE(svr.is_running());
  4902. });
  4903. svr.wait_until_ready();
  4904. Client cli(HOST, PORT);
  4905. {
  4906. auto res = cli.Get("/exception");
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("EXCEPTION", res->body);
  4910. }
  4911. {
  4912. auto res = cli.Get("/error");
  4913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4914. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4915. EXPECT_EQ("ERROR", res->body);
  4916. }
  4917. {
  4918. auto res = cli.Get("/invalid");
  4919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4921. EXPECT_EQ("NOT_FOUND", res->body);
  4922. }
  4923. }
  4924. #endif
  4925. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4926. // An exception from a user callback outside process_request()'s try/catch
  4927. // used to unwind into the task queue - which does not catch - and terminate
  4928. // the process. Each test below runs the server on a single worker thread: a
  4929. // guard that catches the exception but still loses the thread would otherwise
  4930. // be hidden by a spare worker serving the follow-up request. Note that a
  4931. // regression here aborts the whole test binary rather than failing one test.
  4932. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4933. Server svr;
  4934. svr.new_task_queue = [] { return new ThreadPool(1); };
  4935. std::atomic<int> reported{0};
  4936. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4937. if (err == Error::UserCallbackException) { reported++; }
  4938. });
  4939. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4940. res.set_content_provider(
  4941. 1024, "text/plain",
  4942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4943. sink.write("hello", 5);
  4944. throw std::runtime_error("from the content provider");
  4945. });
  4946. });
  4947. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4948. res.set_content("ok", "text/plain");
  4949. });
  4950. auto port = svr.bind_to_any_port(HOST);
  4951. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4952. auto se = detail::scope_exit([&] {
  4953. svr.stop();
  4954. listen_thread.join();
  4955. ASSERT_FALSE(svr.is_running());
  4956. });
  4957. svr.wait_until_ready();
  4958. {
  4959. Client cli(HOST, port);
  4960. cli.set_read_timeout(5, 0);
  4961. EXPECT_FALSE(cli.Get("/throw"));
  4962. }
  4963. EXPECT_TRUE(svr.is_running());
  4964. EXPECT_EQ(1, reported.load());
  4965. // A request on a fresh connection is still served.
  4966. {
  4967. Client cli(HOST, port);
  4968. auto res = cli.Get("/ok");
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. EXPECT_EQ(StatusCode::OK_200, res->status);
  4971. EXPECT_EQ("ok", res->body);
  4972. }
  4973. }
  4974. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4975. Server svr;
  4976. svr.new_task_queue = [] { return new ThreadPool(1); };
  4977. std::atomic<bool> should_throw{true};
  4978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4979. res.set_content("hi", "text/plain");
  4980. });
  4981. svr.set_post_routing_handler(
  4982. [&](const Request & /*req*/, Response & /*res*/) {
  4983. if (should_throw) {
  4984. throw std::runtime_error("from the post-routing handler");
  4985. }
  4986. });
  4987. auto port = svr.bind_to_any_port(HOST);
  4988. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4989. auto se = detail::scope_exit([&] {
  4990. svr.stop();
  4991. listen_thread.join();
  4992. ASSERT_FALSE(svr.is_running());
  4993. });
  4994. svr.wait_until_ready();
  4995. {
  4996. Client cli(HOST, port);
  4997. cli.set_read_timeout(5, 0);
  4998. EXPECT_FALSE(cli.Get("/hi"));
  4999. }
  5000. EXPECT_TRUE(svr.is_running());
  5001. should_throw = false;
  5002. {
  5003. Client cli(HOST, port);
  5004. auto res = cli.Get("/hi");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. EXPECT_EQ("hi", res->body);
  5008. }
  5009. }
  5010. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5011. // The guard reports the caught exception through the error logger, which is
  5012. // a user callback too. A logger that throws has to be contained as well, or
  5013. // the process would terminate from inside the catch.
  5014. Server svr;
  5015. svr.new_task_queue = [] { return new ThreadPool(1); };
  5016. std::atomic<int> reported{0};
  5017. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5018. if (err == Error::UserCallbackException) {
  5019. reported++;
  5020. throw std::runtime_error("from the error logger");
  5021. }
  5022. });
  5023. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5024. res.set_content_provider(
  5025. 1024, "text/plain",
  5026. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5027. sink.write("hello", 5);
  5028. throw std::runtime_error("from the content provider");
  5029. });
  5030. });
  5031. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5032. res.set_content("ok", "text/plain");
  5033. });
  5034. auto port = svr.bind_to_any_port(HOST);
  5035. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5036. auto se = detail::scope_exit([&] {
  5037. svr.stop();
  5038. listen_thread.join();
  5039. ASSERT_FALSE(svr.is_running());
  5040. });
  5041. svr.wait_until_ready();
  5042. {
  5043. Client cli(HOST, port);
  5044. cli.set_read_timeout(5, 0);
  5045. EXPECT_FALSE(cli.Get("/throw"));
  5046. }
  5047. EXPECT_TRUE(svr.is_running());
  5048. EXPECT_EQ(1, reported.load());
  5049. {
  5050. Client cli(HOST, port);
  5051. auto res = cli.Get("/ok");
  5052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5053. EXPECT_EQ(StatusCode::OK_200, res->status);
  5054. EXPECT_EQ("ok", res->body);
  5055. }
  5056. }
  5057. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5058. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5059. // so the exception unwinds through the ws::WebSocket object on its way to
  5060. // the guard. None of the HTTP cases above cross that.
  5061. Server svr;
  5062. svr.new_task_queue = [] { return new ThreadPool(1); };
  5063. std::atomic<int> reported{0};
  5064. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5065. if (err == Error::UserCallbackException) { reported++; }
  5066. });
  5067. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5068. throw std::runtime_error("from the WebSocket handler");
  5069. });
  5070. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5071. res.set_content("ok", "text/plain");
  5072. });
  5073. auto port = svr.bind_to_any_port(HOST);
  5074. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5075. auto se = detail::scope_exit([&] {
  5076. svr.stop();
  5077. listen_thread.join();
  5078. ASSERT_FALSE(svr.is_running());
  5079. });
  5080. svr.wait_until_ready();
  5081. {
  5082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5083. "/ws");
  5084. auto res = client.connect();
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. // The server dropped the connection instead of dying.
  5087. std::string msg;
  5088. EXPECT_FALSE(client.read(msg));
  5089. client.close();
  5090. }
  5091. EXPECT_TRUE(svr.is_running());
  5092. EXPECT_EQ(1, reported.load());
  5093. {
  5094. Client cli(HOST, port);
  5095. auto res = cli.Get("/ok");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ("ok", res->body);
  5099. }
  5100. }
  5101. #ifdef CPPHTTPLIB_SSL_ENABLED
  5102. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5103. // SSLServer::process_and_close_socket() is a separate overload with its own
  5104. // guard, so it is exercised on its own.
  5105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5106. ASSERT_TRUE(svr.is_valid());
  5107. svr.new_task_queue = [] { return new ThreadPool(1); };
  5108. std::atomic<int> reported{0};
  5109. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5110. if (err == Error::UserCallbackException) { reported++; }
  5111. });
  5112. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5113. res.set_content_provider(
  5114. 1024, "text/plain",
  5115. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5116. sink.write("hello", 5);
  5117. throw std::runtime_error("from the content provider");
  5118. });
  5119. });
  5120. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5121. res.set_content("ok", "text/plain");
  5122. });
  5123. auto port = svr.bind_to_any_port(HOST);
  5124. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5125. auto se = detail::scope_exit([&] {
  5126. svr.stop();
  5127. listen_thread.join();
  5128. ASSERT_FALSE(svr.is_running());
  5129. });
  5130. svr.wait_until_ready();
  5131. {
  5132. SSLClient cli(HOST, port);
  5133. cli.enable_server_certificate_verification(false);
  5134. cli.set_read_timeout(5, 0);
  5135. EXPECT_FALSE(cli.Get("/throw"));
  5136. }
  5137. EXPECT_TRUE(svr.is_running());
  5138. EXPECT_EQ(1, reported.load());
  5139. {
  5140. SSLClient cli(HOST, port);
  5141. cli.enable_server_certificate_verification(false);
  5142. auto res = cli.Get("/ok");
  5143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("ok", res->body);
  5146. }
  5147. }
  5148. #endif
  5149. #endif
  5150. TEST(NoContentTest, ContentLength) {
  5151. Server svr;
  5152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5153. res.status = StatusCode::NoContent_204;
  5154. });
  5155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5156. auto se = detail::scope_exit([&] {
  5157. svr.stop();
  5158. thread.join();
  5159. ASSERT_FALSE(svr.is_running());
  5160. });
  5161. svr.wait_until_ready();
  5162. {
  5163. Client cli(HOST, PORT);
  5164. auto res = cli.Get("/hi");
  5165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5166. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5167. // RFC 9110 8.6: none in a 204 response
  5168. EXPECT_FALSE(res->has_header("Content-Length"));
  5169. }
  5170. }
  5171. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5172. Server svr;
  5173. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5174. res.set_header("Content-Length", "5");
  5175. res.set_content("hello world", "text/plain");
  5176. });
  5177. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5178. // A body that reads as the last chunk, were it taken as chunked
  5179. res.set_header("Transfer-Encoding", "chunked");
  5180. res.set_content("0\r\n\r\n", "text/plain");
  5181. });
  5182. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5183. res.set_header("Content-Length", "2");
  5184. res.set_content_provider(5, "text/plain",
  5185. [](size_t offset, size_t length, DataSink &sink) {
  5186. sink.write(&"hello"[offset], length);
  5187. return true;
  5188. });
  5189. });
  5190. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5191. res.set_header("Content-Length", "1234");
  5192. });
  5193. thread t = thread([&] { svr.listen(HOST, PORT); });
  5194. auto se = detail::scope_exit([&] {
  5195. svr.stop();
  5196. t.join();
  5197. ASSERT_FALSE(svr.is_running());
  5198. });
  5199. svr.wait_until_ready();
  5200. Client cli(HOST, PORT);
  5201. cli.set_read_timeout(1, 0);
  5202. auto expect_body = [&](const Result &res, const std::string &body) {
  5203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5204. EXPECT_EQ(body, res->body);
  5205. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5206. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5207. };
  5208. Headers identity{{"Accept-Encoding", ""}};
  5209. expect_body(cli.Get("/body", identity), "hello world");
  5210. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5211. expect_body(cli.Get("/body",
  5212. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5213. "he");
  5214. expect_body(cli.Get("/provider", identity), "hello");
  5215. expect_body(cli.Get("/empty", identity), "");
  5216. // A HEAD response may give the length of the body a GET would get.
  5217. auto res = cli.Head("/empty");
  5218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5219. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5220. }
  5221. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5222. Server svr;
  5223. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5224. res.set_content("short", "text/plain");
  5225. });
  5226. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5227. res.body += " with a footer";
  5228. res.set_header("Transfer-Encoding", "chunked");
  5229. });
  5230. thread t = thread([&] { svr.listen(HOST, PORT); });
  5231. auto se = detail::scope_exit([&] {
  5232. svr.stop();
  5233. t.join();
  5234. ASSERT_FALSE(svr.is_running());
  5235. });
  5236. svr.wait_until_ready();
  5237. Client cli(HOST, PORT);
  5238. cli.set_read_timeout(1, 0);
  5239. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. EXPECT_EQ("short with a footer", res->body);
  5242. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5243. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5244. }
  5245. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5246. Server svr;
  5247. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5248. res.set_header("Content-Length", "3");
  5249. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5250. sink.write("abc", 3);
  5251. sink.done();
  5252. return true;
  5253. });
  5254. });
  5255. thread t = thread([&] { svr.listen(HOST, PORT); });
  5256. auto se = detail::scope_exit([&] {
  5257. svr.stop();
  5258. t.join();
  5259. ASSERT_FALSE(svr.is_running());
  5260. });
  5261. svr.wait_until_ready();
  5262. Client cli(HOST, PORT);
  5263. cli.set_keep_alive(true);
  5264. auto res = cli.Get("/");
  5265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5266. EXPECT_EQ("abc", res->body);
  5267. EXPECT_FALSE(res->has_header("Content-Length"));
  5268. EXPECT_EQ("close", res->get_header_value("Connection"));
  5269. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5270. // No body to delimit
  5271. auto head = cli.Head("/");
  5272. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5273. EXPECT_FALSE(head->has_header("Connection"));
  5274. }
  5275. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5276. #ifdef CPPHTTPLIB_SSL_ENABLED
  5277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5278. ASSERT_TRUE(svr.is_valid());
  5279. #else
  5280. Server svr;
  5281. #endif
  5282. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5283. if (req.path == "/routing_handler") {
  5284. res.set_header("PRE_ROUTING", "on");
  5285. res.set_content("Routing Handler", "text/plain");
  5286. return httplib::Server::HandlerResponse::Handled;
  5287. }
  5288. return httplib::Server::HandlerResponse::Unhandled;
  5289. });
  5290. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5291. res.set_content("Error", "text/html");
  5292. });
  5293. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5294. if (req.path == "/routing_handler") {
  5295. res.set_header("POST_ROUTING", "on");
  5296. }
  5297. });
  5298. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5299. res.set_content("Hello World!\n", "text/plain");
  5300. });
  5301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5302. auto se = detail::scope_exit([&] {
  5303. svr.stop();
  5304. thread.join();
  5305. ASSERT_FALSE(svr.is_running());
  5306. });
  5307. svr.wait_until_ready();
  5308. {
  5309. #ifdef CPPHTTPLIB_SSL_ENABLED
  5310. SSLClient cli(HOST, PORT);
  5311. cli.enable_server_certificate_verification(false);
  5312. #else
  5313. Client cli(HOST, PORT);
  5314. #endif
  5315. auto res = cli.Get("/routing_handler");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("Routing Handler", res->body);
  5319. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5320. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5321. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5322. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5323. }
  5324. {
  5325. #ifdef CPPHTTPLIB_SSL_ENABLED
  5326. SSLClient cli(HOST, PORT);
  5327. cli.enable_server_certificate_verification(false);
  5328. #else
  5329. Client cli(HOST, PORT);
  5330. #endif
  5331. auto res = cli.Get("/hi");
  5332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. EXPECT_EQ("Hello World!\n", res->body);
  5335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5337. }
  5338. {
  5339. #ifdef CPPHTTPLIB_SSL_ENABLED
  5340. SSLClient cli(HOST, PORT);
  5341. cli.enable_server_certificate_verification(false);
  5342. #else
  5343. Client cli(HOST, PORT);
  5344. #endif
  5345. auto res = cli.Get("/aaa");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5348. EXPECT_EQ("Error", res->body);
  5349. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5350. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5351. }
  5352. }
  5353. TEST(RequestHandlerTest, PreRequestHandler) {
  5354. auto route_path = "/user/:user";
  5355. Server svr;
  5356. svr.Get("/hi", [](const Request &, Response &res) {
  5357. res.set_content("hi", "text/plain");
  5358. });
  5359. svr.Get(route_path, [](const Request &req, Response &res) {
  5360. res.set_content(req.path_params.at("user"), "text/plain");
  5361. });
  5362. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5363. if (req.matched_route == route_path) {
  5364. auto user = req.path_params.at("user");
  5365. if (user != "john") {
  5366. res.status = StatusCode::Forbidden_403;
  5367. res.set_content("error", "text/html");
  5368. return Server::HandlerResponse::Handled;
  5369. }
  5370. }
  5371. return Server::HandlerResponse::Unhandled;
  5372. });
  5373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5374. auto se = detail::scope_exit([&] {
  5375. svr.stop();
  5376. thread.join();
  5377. ASSERT_FALSE(svr.is_running());
  5378. });
  5379. svr.wait_until_ready();
  5380. Client cli(HOST, PORT);
  5381. {
  5382. auto res = cli.Get("/hi");
  5383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. EXPECT_EQ("hi", res->body);
  5386. }
  5387. {
  5388. auto res = cli.Get("/user/john");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ("john", res->body);
  5392. }
  5393. {
  5394. auto res = cli.Get("/user/invalid-user");
  5395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5396. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5397. EXPECT_EQ("error", res->body);
  5398. }
  5399. }
  5400. // The pre-request handler must run before the request body is read, so a
  5401. // rejected request never forces the server to buffer a (potentially large)
  5402. // body. Here the posted body is larger than the payload limit: if the body
  5403. // were read first the server would answer 413, but because the pre-request
  5404. // handler runs first it answers 403 and the body is never read.
  5405. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5406. Server svr;
  5407. svr.set_payload_max_length(8);
  5408. auto handler_ran = false;
  5409. svr.Post("/reject", [&](const Request &req, Response &res) {
  5410. handler_ran = true;
  5411. res.set_content(req.body, "text/plain");
  5412. });
  5413. svr.Post("/accept", [](const Request &req, Response &res) {
  5414. res.set_content(req.body, "text/plain");
  5415. });
  5416. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5417. if (req.matched_route == "/reject") {
  5418. res.status = StatusCode::Forbidden_403;
  5419. res.set_content("denied", "text/plain");
  5420. return Server::HandlerResponse::Handled;
  5421. }
  5422. return Server::HandlerResponse::Unhandled;
  5423. });
  5424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5425. auto se = detail::scope_exit([&] {
  5426. svr.stop();
  5427. thread.join();
  5428. ASSERT_FALSE(svr.is_running());
  5429. });
  5430. svr.wait_until_ready();
  5431. Client cli(HOST, PORT);
  5432. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5433. // rejects with 403 before the body is read, so 413 is never reached.
  5434. {
  5435. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5437. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5438. EXPECT_EQ("denied", res->body);
  5439. EXPECT_FALSE(handler_ran);
  5440. }
  5441. // An approved route still reads the body and enforces the payload limit.
  5442. {
  5443. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5446. }
  5447. }
  5448. TEST(UserDataTest, BasicOperations) {
  5449. httplib::UserData ud;
  5450. // Initially empty
  5451. EXPECT_FALSE(ud.has("key"));
  5452. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5453. // set and get
  5454. ud.set("key", 42);
  5455. EXPECT_TRUE(ud.has("key"));
  5456. auto *p = ud.get<int>("key");
  5457. ASSERT_NE(nullptr, p);
  5458. EXPECT_EQ(42, *p);
  5459. // Type mismatch → nullptr
  5460. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5461. // Overwrite with different type
  5462. ud.set("key", std::string("hello"));
  5463. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5464. auto *s = ud.get<std::string>("key");
  5465. ASSERT_NE(nullptr, s);
  5466. EXPECT_EQ("hello", *s);
  5467. // erase
  5468. ud.erase("key");
  5469. EXPECT_FALSE(ud.has("key"));
  5470. // clear
  5471. ud.set("a", 1);
  5472. ud.set("b", 2);
  5473. ud.clear();
  5474. EXPECT_FALSE(ud.has("a"));
  5475. EXPECT_FALSE(ud.has("b"));
  5476. }
  5477. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5478. struct AuthCtx {
  5479. std::string user_id;
  5480. };
  5481. Server svr;
  5482. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5483. res.user_data.set("auth", AuthCtx{"alice"});
  5484. return Server::HandlerResponse::Unhandled;
  5485. });
  5486. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5487. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5488. ASSERT_NE(nullptr, ctx);
  5489. res.set_content("Hello " + ctx->user_id, "text/plain");
  5490. });
  5491. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5492. auto se = detail::scope_exit([&] {
  5493. svr.stop();
  5494. thread.join();
  5495. ASSERT_FALSE(svr.is_running());
  5496. });
  5497. svr.wait_until_ready();
  5498. Client cli(HOST, PORT);
  5499. auto res = cli.Get("/me");
  5500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. EXPECT_EQ("Hello alice", res->body);
  5503. }
  5504. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5505. struct RoleCtx {
  5506. std::string role;
  5507. };
  5508. Server svr;
  5509. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5510. res.user_data.set("role", RoleCtx{"admin"});
  5511. return Server::HandlerResponse::Unhandled;
  5512. });
  5513. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5514. auto *ctx = res.user_data.get<RoleCtx>("role");
  5515. ASSERT_NE(nullptr, ctx);
  5516. res.set_content(ctx->role, "text/plain");
  5517. });
  5518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5519. auto se = detail::scope_exit([&] {
  5520. svr.stop();
  5521. thread.join();
  5522. ASSERT_FALSE(svr.is_running());
  5523. });
  5524. svr.wait_until_ready();
  5525. Client cli(HOST, PORT);
  5526. auto res = cli.Get("/role");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::OK_200, res->status);
  5529. EXPECT_EQ("admin", res->body);
  5530. }
  5531. TEST(InvalidFormatTest, StatusCode) {
  5532. Server svr;
  5533. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5534. res.set_content("Hello World!\n", "text/plain");
  5535. res.status = 9999; // Status should be a three-digit code...
  5536. });
  5537. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5538. auto se = detail::scope_exit([&] {
  5539. svr.stop();
  5540. thread.join();
  5541. ASSERT_FALSE(svr.is_running());
  5542. });
  5543. svr.wait_until_ready();
  5544. {
  5545. Client cli(HOST, PORT);
  5546. auto res = cli.Get("/hi");
  5547. ASSERT_FALSE(res);
  5548. }
  5549. }
  5550. TEST(URLFragmentTest, WithFragment) {
  5551. Server svr;
  5552. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5553. EXPECT_TRUE(req.target == "/hi");
  5554. });
  5555. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5556. auto se = detail::scope_exit([&] {
  5557. svr.stop();
  5558. thread.join();
  5559. ASSERT_FALSE(svr.is_running());
  5560. });
  5561. svr.wait_until_ready();
  5562. {
  5563. Client cli(HOST, PORT);
  5564. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5565. EXPECT_TRUE(res);
  5566. EXPECT_EQ(StatusCode::OK_200, res->status);
  5567. res = cli.Get("/hi%23key1=val1=key2=val2");
  5568. EXPECT_TRUE(res);
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. }
  5571. }
  5572. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5573. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5574. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5575. Server svr;
  5576. std::vector<std::string> targets;
  5577. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5578. targets.push_back(req.target);
  5579. });
  5580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5581. auto se = detail::scope_exit([&] {
  5582. svr.stop();
  5583. thread.join();
  5584. ASSERT_FALSE(svr.is_running());
  5585. });
  5586. svr.wait_until_ready();
  5587. Client cli(HOST, PORT);
  5588. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5589. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5590. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5591. // A '?' after the '#' belongs to the fragment, not to the query.
  5592. Request req;
  5593. req.method = "GET";
  5594. req.path = "/hi#f?x=1";
  5595. req.params.emplace("a", "1");
  5596. Response res;
  5597. auto error = Error::Success;
  5598. EXPECT_TRUE(cli.send(req, res, error));
  5599. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5600. "/hi?a=1"}),
  5601. targets);
  5602. }
  5603. TEST(HeaderWriter, SetHeaderWriter) {
  5604. Server svr;
  5605. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5606. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5607. return detail::write_headers(strm, hdrs);
  5608. });
  5609. svr.Get("/hi", [](const Request &req, Response &res) {
  5610. auto it = req.headers.find("CustomClientHeader");
  5611. EXPECT_TRUE(it != req.headers.end());
  5612. EXPECT_EQ(it->second, "CustomClientValue");
  5613. res.set_content("Hello World!\n", "text/plain");
  5614. });
  5615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5616. auto se = detail::scope_exit([&] {
  5617. svr.stop();
  5618. thread.join();
  5619. ASSERT_FALSE(svr.is_running());
  5620. });
  5621. svr.wait_until_ready();
  5622. {
  5623. Client cli(HOST, PORT);
  5624. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5625. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5626. return detail::write_headers(strm, hdrs);
  5627. });
  5628. auto res = cli.Get("/hi");
  5629. EXPECT_TRUE(res);
  5630. EXPECT_EQ(StatusCode::OK_200, res->status);
  5631. auto it = res->headers.find("CustomServerHeader");
  5632. EXPECT_TRUE(it != res->headers.end());
  5633. EXPECT_EQ(it->second, "CustomServerValue");
  5634. }
  5635. }
  5636. class ServerTest : public ::testing::Test {
  5637. protected:
  5638. ServerTest()
  5639. : cli_(HOST, PORT)
  5640. #ifdef CPPHTTPLIB_SSL_ENABLED
  5641. ,
  5642. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5643. #endif
  5644. {
  5645. #ifdef CPPHTTPLIB_SSL_ENABLED
  5646. cli_.enable_server_certificate_verification(false);
  5647. #endif
  5648. // Allow LARGE_DATA (100MB) responses
  5649. cli_.set_payload_max_length(200 * 1024 * 1024);
  5650. }
  5651. virtual void SetUp() {
  5652. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5653. svr_.set_payload_max_length(200 * 1024 * 1024);
  5654. svr_.set_mount_point("/", "./www");
  5655. svr_.set_mount_point("/mount", "./www2");
  5656. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5657. svr_.Get("/hi",
  5658. [&](const Request & /*req*/, Response &res) {
  5659. res.set_content("Hello World!", "text/plain");
  5660. })
  5661. .Get("/file_content",
  5662. [&](const Request & /*req*/, Response &res) {
  5663. res.set_file_content("./www/dir/test.html");
  5664. })
  5665. .Get("/file_content_with_content_type",
  5666. [&](const Request & /*req*/, Response &res) {
  5667. res.set_file_content("./www/file", "text/plain");
  5668. })
  5669. .Get("/invalid_file_content",
  5670. [&](const Request & /*req*/, Response &res) {
  5671. res.set_file_content("./www/dir/invalid_file_path");
  5672. })
  5673. .Get("/http_response_splitting",
  5674. [&](const Request & /*req*/, Response &res) {
  5675. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5676. EXPECT_EQ(0U, res.headers.size());
  5677. EXPECT_FALSE(res.has_header("a"));
  5678. res.set_header("a", "1\nSet-Cookie: a=1");
  5679. EXPECT_EQ(0U, res.headers.size());
  5680. EXPECT_FALSE(res.has_header("a"));
  5681. res.set_header("a", "1\rSet-Cookie: a=1");
  5682. EXPECT_EQ(0U, res.headers.size());
  5683. EXPECT_FALSE(res.has_header("a"));
  5684. res.set_header("a\r\nb", "0");
  5685. EXPECT_EQ(0U, res.headers.size());
  5686. EXPECT_FALSE(res.has_header("a"));
  5687. res.set_header("a\rb", "0");
  5688. EXPECT_EQ(0U, res.headers.size());
  5689. EXPECT_FALSE(res.has_header("a"));
  5690. res.set_header("a\nb", "0");
  5691. EXPECT_EQ(0U, res.headers.size());
  5692. EXPECT_FALSE(res.has_header("a"));
  5693. res.set_redirect("1\r\nSet-Cookie: a=1");
  5694. EXPECT_EQ(0U, res.headers.size());
  5695. EXPECT_FALSE(res.has_header("Location"));
  5696. })
  5697. .Get("/slow",
  5698. [&](const Request & /*req*/, Response &res) {
  5699. std::this_thread::sleep_for(std::chrono::seconds(4));
  5700. res.set_content("slow", "text/plain");
  5701. })
  5702. #if 0
  5703. .Post("/slowpost",
  5704. [&](const Request & /*req*/, Response &res) {
  5705. std::this_thread::sleep_for(std::chrono::seconds(2));
  5706. res.set_content("slow", "text/plain");
  5707. })
  5708. #endif
  5709. .Get("/remote_addr",
  5710. [&](const Request &req, Response &res) {
  5711. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5712. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5713. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5714. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5715. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5716. #endif
  5717. res.set_content(req.remote_addr, "text/plain");
  5718. })
  5719. .Get("/local_addr",
  5720. [&](const Request &req, Response &res) {
  5721. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5722. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5723. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5724. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5725. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5726. #endif
  5727. auto local_addr = req.local_addr;
  5728. auto local_port = std::to_string(req.local_port);
  5729. res.set_content(local_addr.append(":").append(local_port),
  5730. "text/plain");
  5731. })
  5732. .Get("/endwith%",
  5733. [&](const Request & /*req*/, Response &res) {
  5734. res.set_content("Hello World!", "text/plain");
  5735. })
  5736. .Get("/a\\+\\+b",
  5737. [&](const Request &req, Response &res) {
  5738. ASSERT_TRUE(req.has_param("a +b"));
  5739. auto val = req.get_param_value("a +b");
  5740. res.set_content(val, "text/plain");
  5741. })
  5742. .Get("/", [&](const Request & /*req*/,
  5743. Response &res) { res.set_redirect("/hi"); })
  5744. .Post("/1",
  5745. [](const Request & /*req*/, Response &res) {
  5746. res.set_redirect("/2", StatusCode::SeeOther_303);
  5747. })
  5748. .Get("/2",
  5749. [](const Request & /*req*/, Response &res) {
  5750. res.set_content("redirected.", "text/plain");
  5751. res.status = StatusCode::OK_200;
  5752. })
  5753. .Post("/person",
  5754. [&](const Request &req, Response &res) {
  5755. if (req.has_param("name") && req.has_param("note")) {
  5756. persons_[req.get_param_value("name")] =
  5757. req.get_param_value("note");
  5758. } else {
  5759. res.status = StatusCode::BadRequest_400;
  5760. }
  5761. })
  5762. .Put("/person",
  5763. [&](const Request &req, Response &res) {
  5764. if (req.has_param("name") && req.has_param("note")) {
  5765. persons_[req.get_param_value("name")] =
  5766. req.get_param_value("note");
  5767. } else {
  5768. res.status = StatusCode::BadRequest_400;
  5769. }
  5770. })
  5771. .Get("/person/(.*)",
  5772. [&](const Request &req, Response &res) {
  5773. string name = req.matches[1];
  5774. if (persons_.find(name) != persons_.end()) {
  5775. auto note = persons_[name];
  5776. res.set_content(note, "text/plain");
  5777. } else {
  5778. res.status = StatusCode::NotFound_404;
  5779. }
  5780. })
  5781. .Delete("/person",
  5782. [&](const Request &req, Response &res) {
  5783. if (req.has_param("name")) {
  5784. string name = req.get_param_value("name");
  5785. if (persons_.find(name) != persons_.end()) {
  5786. persons_.erase(name);
  5787. res.set_content("DELETED", "text/plain");
  5788. } else {
  5789. res.status = StatusCode::NotFound_404;
  5790. }
  5791. } else {
  5792. res.status = StatusCode::BadRequest_400;
  5793. }
  5794. })
  5795. .Post("/x-www-form-urlencoded-json",
  5796. [&](const Request &req, Response &res) {
  5797. auto json = req.get_param_value("json");
  5798. ASSERT_EQ(JSON_DATA, json);
  5799. res.set_content(json, "appliation/json");
  5800. res.status = StatusCode::OK_200;
  5801. })
  5802. .Get("/streamed-chunked",
  5803. [&](const Request & /*req*/, Response &res) {
  5804. res.set_chunked_content_provider(
  5805. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5806. sink.os << "123";
  5807. sink.os << "456";
  5808. sink.os << "789";
  5809. sink.done();
  5810. return true;
  5811. });
  5812. })
  5813. .Get("/streamed-chunked-with-prohibited-trailer",
  5814. [&](const Request & /*req*/, Response &res) {
  5815. auto i = new int(0);
  5816. // Declare both a prohibited trailer (Content-Length) and an
  5817. // allowed one
  5818. res.set_header("Trailer", "Content-Length, X-Allowed");
  5819. res.set_chunked_content_provider(
  5820. "text/plain",
  5821. [i](size_t /*offset*/, DataSink &sink) {
  5822. switch (*i) {
  5823. case 0: sink.os << "123"; break;
  5824. case 1: sink.os << "456"; break;
  5825. case 2: sink.os << "789"; break;
  5826. case 3: {
  5827. sink.done_with_trailer(
  5828. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5829. } break;
  5830. }
  5831. (*i)++;
  5832. return true;
  5833. },
  5834. [i](bool success) {
  5835. EXPECT_TRUE(success);
  5836. delete i;
  5837. });
  5838. })
  5839. .Get("/streamed-chunked2",
  5840. [&](const Request & /*req*/, Response &res) {
  5841. auto i = new int(0);
  5842. res.set_chunked_content_provider(
  5843. "text/plain",
  5844. [i](size_t /*offset*/, DataSink &sink) {
  5845. switch (*i) {
  5846. case 0: sink.os << "123"; break;
  5847. case 1: sink.os << "456"; break;
  5848. case 2: sink.os << "789"; break;
  5849. case 3: sink.done(); break;
  5850. }
  5851. (*i)++;
  5852. return true;
  5853. },
  5854. [i](bool success) {
  5855. EXPECT_TRUE(success);
  5856. delete i;
  5857. });
  5858. })
  5859. .Get("/streamed-chunked-with-trailer",
  5860. [&](const Request & /*req*/, Response &res) {
  5861. auto i = new int(0);
  5862. res.set_header("Trailer", "Dummy1, Dummy2");
  5863. res.set_chunked_content_provider(
  5864. "text/plain",
  5865. [i](size_t /*offset*/, DataSink &sink) {
  5866. switch (*i) {
  5867. case 0: sink.os << "123"; break;
  5868. case 1: sink.os << "456"; break;
  5869. case 2: sink.os << "789"; break;
  5870. case 3: {
  5871. sink.done_with_trailer(
  5872. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5873. } break;
  5874. }
  5875. (*i)++;
  5876. return true;
  5877. },
  5878. [i](bool success) {
  5879. EXPECT_TRUE(success);
  5880. delete i;
  5881. });
  5882. })
  5883. .Get("/streamed",
  5884. [&](const Request & /*req*/, Response &res) {
  5885. res.set_content_provider(
  5886. 6, "text/plain",
  5887. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5888. sink.os << (offset < 3 ? "a" : "b");
  5889. return true;
  5890. });
  5891. })
  5892. .Get("/streamed-without-length",
  5893. [&](const Request & /*req*/, Response &res) {
  5894. auto data = new std::string("abcdefg");
  5895. res.set_content_provider(
  5896. "text/plain",
  5897. [data](size_t offset, DataSink &sink) {
  5898. if (offset < data->size()) {
  5899. sink.os << data->substr(offset);
  5900. }
  5901. sink.done();
  5902. return true;
  5903. },
  5904. [data](bool success) {
  5905. EXPECT_TRUE(success);
  5906. delete data;
  5907. });
  5908. })
  5909. .Get("/streamed-with-range",
  5910. [&](const Request &req, Response &res) {
  5911. auto data = new std::string("abcdefg");
  5912. // An explicit status keeps the server from picking the 206 it
  5913. // would otherwise choose for a ranged request, so the response
  5914. // is not a partial representation.
  5915. auto status = req.get_param_value("status");
  5916. if (status == "200") {
  5917. res.status = StatusCode::OK_200;
  5918. } else if (status == "403") {
  5919. res.status = StatusCode::Forbidden_403;
  5920. }
  5921. res.set_content_provider(
  5922. data->size(), "text/plain",
  5923. [data](size_t offset, size_t length, DataSink &sink) {
  5924. size_t DATA_CHUNK_SIZE = 4;
  5925. const auto &d = *data;
  5926. auto out_len =
  5927. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5928. auto ret =
  5929. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5930. EXPECT_TRUE(ret);
  5931. return true;
  5932. },
  5933. [data, &req](bool success) {
  5934. EXPECT_EQ(success, !req.has_param("error"));
  5935. delete data;
  5936. });
  5937. })
  5938. .Get("/streamed-cancel",
  5939. [&](const Request & /*req*/, Response &res) {
  5940. res.set_content_provider(
  5941. size_t(-1), "text/plain",
  5942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5943. sink.os << "data_chunk";
  5944. return true;
  5945. });
  5946. })
  5947. .Get("/regex-with-delimiter",
  5948. [&](const Request &req, Response & /*res*/) {
  5949. ASSERT_TRUE(req.has_param("key"));
  5950. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5951. })
  5952. .Get("/with-range",
  5953. [&](const Request & /*req*/, Response &res) {
  5954. res.set_content("abcdefg", "text/plain");
  5955. })
  5956. .Get("/test-start-time",
  5957. [&](const Request &req, Response & /*res*/) {
  5958. EXPECT_NE(req.start_time_,
  5959. std::chrono::steady_clock::time_point::min());
  5960. })
  5961. .Get("/with-range-customized-response",
  5962. [&](const Request & /*req*/, Response &res) {
  5963. res.status = StatusCode::BadRequest_400;
  5964. res.set_content(JSON_DATA, "application/json");
  5965. })
  5966. .Post("/chunked",
  5967. [&](const Request &req, Response & /*res*/) {
  5968. EXPECT_EQ(req.body, "dechunked post body");
  5969. })
  5970. .Post("/large-chunked",
  5971. [&](const Request &req, Response & /*res*/) {
  5972. std::string expected(6 * 30 * 1024u, 'a');
  5973. EXPECT_EQ(req.body, expected);
  5974. })
  5975. .Post("/multipart",
  5976. [&](const Request &req, Response & /*res*/) {
  5977. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5978. req.form.get_field_count("text2") +
  5979. req.form.get_field_count("file3") +
  5980. req.form.get_field_count("file4"));
  5981. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5982. req.form.get_file_count("file2"));
  5983. ASSERT_TRUE(!req.form.has_file("???"));
  5984. ASSERT_TRUE(!req.form.has_field("???"));
  5985. ASSERT_TRUE(req.body.empty());
  5986. {
  5987. const auto &text = req.form.get_field("text1");
  5988. EXPECT_EQ("text default", text);
  5989. }
  5990. {
  5991. const auto &text = req.form.get_field("text2");
  5992. EXPECT_EQ("aωb", text);
  5993. }
  5994. {
  5995. const auto &file = req.form.get_file("file1");
  5996. EXPECT_EQ("hello.txt", file.filename);
  5997. EXPECT_EQ("text/plain", file.content_type);
  5998. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5999. }
  6000. {
  6001. const auto &file = req.form.get_file("file2");
  6002. EXPECT_EQ("world.json", file.filename);
  6003. EXPECT_EQ("application/json", file.content_type);
  6004. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6005. }
  6006. {
  6007. const auto &text = req.form.get_field("file3");
  6008. EXPECT_EQ(0u, text.size());
  6009. }
  6010. {
  6011. const auto &text = req.form.get_field("file4");
  6012. EXPECT_EQ(0u, text.size());
  6013. }
  6014. })
  6015. .Post("/multipart/multi_file_values",
  6016. [&](const Request &req, Response & /*res*/) {
  6017. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6018. req.form.get_field_count("multi_text1"));
  6019. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6020. ASSERT_TRUE(!req.form.has_file("???"));
  6021. ASSERT_TRUE(!req.form.has_field("???"));
  6022. ASSERT_TRUE(req.body.empty());
  6023. {
  6024. const auto &text = req.form.get_field("text");
  6025. EXPECT_EQ("default text", text);
  6026. }
  6027. {
  6028. const auto &text1_values = req.form.get_fields("multi_text1");
  6029. EXPECT_EQ(2u, text1_values.size());
  6030. EXPECT_EQ("aaaaa", text1_values[0]);
  6031. EXPECT_EQ("bbbbb", text1_values[1]);
  6032. }
  6033. {
  6034. const auto &file1_values = req.form.get_files("multi_file1");
  6035. EXPECT_EQ(2u, file1_values.size());
  6036. auto file1 = file1_values[0];
  6037. EXPECT_EQ(file1.filename, "hello.txt");
  6038. EXPECT_EQ(file1.content_type, "text/plain");
  6039. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6040. auto file2 = file1_values[1];
  6041. EXPECT_EQ(file2.filename, "world.json");
  6042. EXPECT_EQ(file2.content_type, "application/json");
  6043. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6044. }
  6045. })
  6046. .Post("/empty",
  6047. [&](const Request &req, Response &res) {
  6048. EXPECT_EQ(req.body, "");
  6049. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6050. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6051. res.set_content("empty", "text/plain");
  6052. })
  6053. .Post("/empty-no-content-type",
  6054. [&](const Request &req, Response &res) {
  6055. EXPECT_EQ(req.body, "");
  6056. EXPECT_FALSE(req.has_header("Content-Type"));
  6057. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6058. res.set_content("empty-no-content-type", "text/plain");
  6059. })
  6060. .Post("/path-only",
  6061. [&](const Request &req, Response &res) {
  6062. EXPECT_EQ(req.body, "");
  6063. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6064. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6065. res.set_content("path-only", "text/plain");
  6066. })
  6067. .Post("/path-headers-only",
  6068. [&](const Request &req, Response &res) {
  6069. EXPECT_EQ(req.body, "");
  6070. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6071. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6072. EXPECT_EQ("world", req.get_header_value("hello"));
  6073. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6074. res.set_content("path-headers-only", "text/plain");
  6075. })
  6076. .Post("/post-large",
  6077. [&](const Request &req, Response &res) {
  6078. EXPECT_EQ(req.body, LARGE_DATA);
  6079. res.set_content(req.body, "text/plain");
  6080. })
  6081. .Post("/post-loopback",
  6082. [&](const Request &, Response &res,
  6083. ContentReader const &content_reader) {
  6084. std::string body;
  6085. content_reader([&](const char *data, size_t data_length) {
  6086. body.append(data, data_length);
  6087. return true;
  6088. });
  6089. res.set_content(body, "text/plain");
  6090. })
  6091. .Put("/put-loopback",
  6092. [&](const Request &, Response &res,
  6093. ContentReader const &content_reader) {
  6094. std::string body;
  6095. content_reader([&](const char *data, size_t data_length) {
  6096. body.append(data, data_length);
  6097. return true;
  6098. });
  6099. res.set_content(body, "text/plain");
  6100. })
  6101. .Patch("/patch-loopback",
  6102. [&](const Request &, Response &res,
  6103. ContentReader const &content_reader) {
  6104. std::string body;
  6105. content_reader([&](const char *data, size_t data_length) {
  6106. body.append(data, data_length);
  6107. return true;
  6108. });
  6109. res.set_content(body, "text/plain");
  6110. })
  6111. .Put("/empty-no-content-type",
  6112. [&](const Request &req, Response &res) {
  6113. EXPECT_EQ(req.body, "");
  6114. EXPECT_FALSE(req.has_header("Content-Type"));
  6115. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6116. res.set_content("empty-no-content-type", "text/plain");
  6117. })
  6118. .Put("/put",
  6119. [&](const Request &req, Response &res) {
  6120. EXPECT_EQ(req.body, "PUT");
  6121. res.set_content(req.body, "text/plain");
  6122. })
  6123. .Put("/put-large",
  6124. [&](const Request &req, Response &res) {
  6125. EXPECT_EQ(req.body, LARGE_DATA);
  6126. res.set_content(req.body, "text/plain");
  6127. })
  6128. .Patch("/patch",
  6129. [&](const Request &req, Response &res) {
  6130. EXPECT_EQ(req.body, "PATCH");
  6131. res.set_content(req.body, "text/plain");
  6132. })
  6133. .Delete("/delete",
  6134. [&](const Request & /*req*/, Response &res) {
  6135. res.set_content("DELETE", "text/plain");
  6136. })
  6137. .Delete("/delete-body",
  6138. [&](const Request &req, Response &res) {
  6139. EXPECT_EQ(req.body, "content");
  6140. res.set_content(req.body, "text/plain");
  6141. })
  6142. .Options(R"(\*)",
  6143. [&](const Request & /*req*/, Response &res) {
  6144. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6145. })
  6146. .CustomRoute("PROPFIND", "/dav/:id",
  6147. [&](const Request &req, Response &res) {
  6148. res.set_header("x-body-size",
  6149. std::to_string(req.body.size()));
  6150. res.set_header("x-matched-route", req.matched_route);
  6151. res.set_header("x-dav-id", req.path_params.at("id"));
  6152. res.status = StatusCode::MultiStatus_207;
  6153. res.set_content(req.body, "application/xml");
  6154. })
  6155. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6156. [&](const Request &req, Response &res) {
  6157. res.set_header("x-dav-match", req.matches[1]);
  6158. res.status = StatusCode::MultiStatus_207;
  6159. })
  6160. .CustomRoute("MKCOL", "/dav-mkcol",
  6161. [&](const Request &req, Response &res) {
  6162. EXPECT_TRUE(req.body.empty());
  6163. res.status = StatusCode::Created_201;
  6164. })
  6165. .CustomRoute(
  6166. "REPORT", "/dav-report",
  6167. [&](const Request & /*req*/, Response &res,
  6168. const ContentReader &content_reader) {
  6169. std::string body;
  6170. content_reader([&](const char *data, size_t data_length) {
  6171. body.append(data, data_length);
  6172. return true;
  6173. });
  6174. res.set_header("x-body-size", std::to_string(body.size()));
  6175. res.status = StatusCode::MultiStatus_207;
  6176. res.set_content(body, "application/xml");
  6177. })
  6178. .Get("/request-target",
  6179. [&](const Request &req, Response & /*res*/) {
  6180. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6181. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6182. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6183. })
  6184. .Get("/long-query-value",
  6185. [&](const Request &req, Response & /*res*/) {
  6186. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6187. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6188. })
  6189. .Get("/too-long-query-value",
  6190. [&](const Request &req, Response & /*res*/) {
  6191. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6192. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6193. })
  6194. .Get("/array-param",
  6195. [&](const Request &req, Response & /*res*/) {
  6196. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6197. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6198. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6199. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6200. })
  6201. .Get("/array-param-values",
  6202. [&](const Request &req, Response & /*res*/) {
  6203. auto values = req.get_param_values("array");
  6204. EXPECT_EQ(3u, values.size());
  6205. EXPECT_EQ("value1", values[0]);
  6206. EXPECT_EQ("value2", values[1]);
  6207. EXPECT_EQ("value3", values[2]);
  6208. auto empty = req.get_param_values("nonexistent");
  6209. EXPECT_TRUE(empty.empty());
  6210. })
  6211. .Post("/validate-no-multiple-headers",
  6212. [&](const Request &req, Response & /*res*/) {
  6213. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6214. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6215. })
  6216. .Post("/content_receiver",
  6217. [&](const Request &req, Response &res,
  6218. const ContentReader &content_reader) {
  6219. if (req.is_multipart_form_data()) {
  6220. std::vector<FormData> items;
  6221. content_reader(
  6222. [&](const FormData &file) {
  6223. items.push_back(file);
  6224. return true;
  6225. },
  6226. [&](const char *data, size_t data_length) {
  6227. items.back().content.append(data, data_length);
  6228. return true;
  6229. });
  6230. EXPECT_EQ(5u, items.size());
  6231. {
  6232. const auto &file = get_file_value(items, "text1");
  6233. EXPECT_TRUE(file.filename.empty());
  6234. EXPECT_EQ("text default", file.content);
  6235. }
  6236. {
  6237. const auto &file = get_file_value(items, "text2");
  6238. EXPECT_TRUE(file.filename.empty());
  6239. EXPECT_EQ("aωb", file.content);
  6240. }
  6241. {
  6242. const auto &file = get_file_value(items, "file1");
  6243. EXPECT_EQ("hello.txt", file.filename);
  6244. EXPECT_EQ("text/plain", file.content_type);
  6245. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6246. }
  6247. {
  6248. const auto &file = get_file_value(items, "file2");
  6249. EXPECT_EQ("world.json", file.filename);
  6250. EXPECT_EQ("application/json", file.content_type);
  6251. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6252. }
  6253. {
  6254. const auto &file = get_file_value(items, "file3");
  6255. EXPECT_TRUE(file.filename.empty());
  6256. EXPECT_EQ("application/octet-stream", file.content_type);
  6257. EXPECT_EQ(0u, file.content.size());
  6258. }
  6259. } else {
  6260. std::string body;
  6261. content_reader([&](const char *data, size_t data_length) {
  6262. EXPECT_EQ(7U, data_length);
  6263. body.append(data, data_length);
  6264. return true;
  6265. });
  6266. EXPECT_EQ(body, "content");
  6267. res.set_content(body, "text/plain");
  6268. }
  6269. })
  6270. .Put("/content_receiver",
  6271. [&](const Request & /*req*/, Response &res,
  6272. const ContentReader &content_reader) {
  6273. std::string body;
  6274. content_reader([&](const char *data, size_t data_length) {
  6275. body.append(data, data_length);
  6276. return true;
  6277. });
  6278. EXPECT_EQ(body, "content");
  6279. res.set_content(body, "text/plain");
  6280. })
  6281. .Patch("/content_receiver",
  6282. [&](const Request & /*req*/, Response &res,
  6283. const ContentReader &content_reader) {
  6284. std::string body;
  6285. content_reader([&](const char *data, size_t data_length) {
  6286. body.append(data, data_length);
  6287. return true;
  6288. });
  6289. EXPECT_EQ(body, "content");
  6290. res.set_content(body, "text/plain");
  6291. })
  6292. .Post("/query-string-and-body",
  6293. [&](const Request &req, Response & /*res*/) {
  6294. ASSERT_TRUE(req.has_param("key"));
  6295. EXPECT_EQ(req.get_param_value("key"), "value");
  6296. EXPECT_EQ(req.body, "content");
  6297. })
  6298. .Get("/last-request",
  6299. [&](const Request &req, Response & /*res*/) {
  6300. EXPECT_EQ("close", req.get_header_value("Connection"));
  6301. })
  6302. .Get(R"(/redirect/(\d+))",
  6303. [&](const Request &req, Response &res) {
  6304. auto num = std::stoi(req.matches[1]) + 1;
  6305. std::string url = "/redirect/" + std::to_string(num);
  6306. res.set_redirect(url);
  6307. })
  6308. .Post("/binary",
  6309. [&](const Request &req, Response &res) {
  6310. EXPECT_EQ(4U, req.body.size());
  6311. EXPECT_EQ("application/octet-stream",
  6312. req.get_header_value("Content-Type"));
  6313. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6314. res.set_content(req.body, "application/octet-stream");
  6315. })
  6316. .Put("/binary",
  6317. [&](const Request &req, Response &res) {
  6318. EXPECT_EQ(4U, req.body.size());
  6319. EXPECT_EQ("application/octet-stream",
  6320. req.get_header_value("Content-Type"));
  6321. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6322. res.set_content(req.body, "application/octet-stream");
  6323. })
  6324. .Patch("/binary",
  6325. [&](const Request &req, Response &res) {
  6326. EXPECT_EQ(4U, req.body.size());
  6327. EXPECT_EQ("application/octet-stream",
  6328. req.get_header_value("Content-Type"));
  6329. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6330. res.set_content(req.body, "application/octet-stream");
  6331. })
  6332. .Delete("/binary",
  6333. [&](const Request &req, Response &res) {
  6334. EXPECT_EQ(4U, req.body.size());
  6335. EXPECT_EQ("application/octet-stream",
  6336. req.get_header_value("Content-Type"));
  6337. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6338. res.set_content(req.body, "application/octet-stream");
  6339. })
  6340. .Get("/issue1772",
  6341. [&](const Request & /*req*/, Response &res) {
  6342. res.status = 401;
  6343. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6344. })
  6345. .Delete("/issue609",
  6346. [](const httplib::Request &, httplib::Response &res,
  6347. const httplib::ContentReader &) {
  6348. res.set_content("ok", "text/plain");
  6349. })
  6350. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6351. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6352. .Get("/compress",
  6353. [&](const Request & /*req*/, Response &res) {
  6354. res.set_content(
  6355. "12345678901234567890123456789012345678901234567890123456789"
  6356. "01234567890123456789012345678901234567890",
  6357. "text/plain");
  6358. })
  6359. .Get("/compress-with-charset",
  6360. [&](const Request & /*req*/, Response &res) {
  6361. res.set_content(
  6362. "12345678901234567890123456789012345678901234567890123456789"
  6363. "01234567890123456789012345678901234567890",
  6364. "application/json; charset=utf-8");
  6365. })
  6366. .Get("/nocompress",
  6367. [&](const Request & /*req*/, Response &res) {
  6368. res.set_content(
  6369. "12345678901234567890123456789012345678901234567890123456789"
  6370. "01234567890123456789012345678901234567890",
  6371. "application/octet-stream");
  6372. })
  6373. .Post("/compress-multipart",
  6374. [&](const Request &req, Response & /*res*/) {
  6375. EXPECT_EQ(2u, req.form.fields.size());
  6376. ASSERT_TRUE(!req.form.has_field("???"));
  6377. {
  6378. const auto &text = req.form.get_field("key1");
  6379. EXPECT_EQ("test", text);
  6380. }
  6381. {
  6382. const auto &text = req.form.get_field("key2");
  6383. EXPECT_EQ("--abcdefg123", text);
  6384. }
  6385. })
  6386. #endif
  6387. ;
  6388. persons_["john"] = "programmer";
  6389. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6390. svr_.wait_until_ready();
  6391. }
  6392. virtual void TearDown() {
  6393. svr_.stop();
  6394. if (!request_threads_.empty()) {
  6395. std::this_thread::sleep_for(std::chrono::seconds(1));
  6396. for (auto &t : request_threads_) {
  6397. t.join();
  6398. }
  6399. }
  6400. t_.join();
  6401. }
  6402. map<string, string> persons_;
  6403. #ifdef CPPHTTPLIB_SSL_ENABLED
  6404. SSLClient cli_;
  6405. SSLServer svr_;
  6406. #else
  6407. Client cli_;
  6408. Server svr_;
  6409. #endif
  6410. thread t_;
  6411. std::vector<thread> request_threads_;
  6412. };
  6413. TEST_F(ServerTest, GetMethod200) {
  6414. auto res = cli_.Get("/hi");
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ("HTTP/1.1", res->version);
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. EXPECT_EQ("OK", res->reason);
  6419. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6420. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6421. EXPECT_EQ("Hello World!", res->body);
  6422. }
  6423. TEST_F(ServerTest, GetEmptyFile) {
  6424. auto res = cli_.Get("/empty_file");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6428. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6429. EXPECT_EQ("", res->body);
  6430. }
  6431. TEST_F(ServerTest, GetFileContent) {
  6432. auto res = cli_.Get("/file_content");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6436. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6437. EXPECT_EQ("test.html", res->body);
  6438. }
  6439. TEST_F(ServerTest, GetFileContentWithRange) {
  6440. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6443. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6444. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6445. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6446. EXPECT_EQ("est", res->body);
  6447. }
  6448. TEST_F(ServerTest, GetFileContentWithContentType) {
  6449. auto res = cli_.Get("/file_content_with_content_type");
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6453. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6454. EXPECT_EQ("file\n", res->body);
  6455. }
  6456. TEST_F(ServerTest, GetInvalidFileContent) {
  6457. auto res = cli_.Get("/invalid_file_content");
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6460. }
  6461. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6462. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. EXPECT_EQ("HTTP/1.1", res->version);
  6465. EXPECT_EQ(StatusCode::OK_200, res->status);
  6466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6467. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6468. EXPECT_EQ("Hello World!", res->body);
  6469. }
  6470. TEST_F(ServerTest, GetMethod302) {
  6471. auto res = cli_.Get("/");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::Found_302, res->status);
  6474. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6475. }
  6476. TEST_F(ServerTest, GetMethod302Redirect) {
  6477. cli_.set_follow_location(true);
  6478. auto res = cli_.Get("/");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::OK_200, res->status);
  6481. EXPECT_EQ("Hello World!", res->body);
  6482. EXPECT_EQ("/hi", res->location);
  6483. }
  6484. TEST_F(ServerTest, GetMethod404) {
  6485. auto res = cli_.Get("/invalid");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6488. }
  6489. TEST_F(ServerTest, HeadMethod200) {
  6490. auto res = cli_.Head("/hi");
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::OK_200, res->status);
  6493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6494. EXPECT_TRUE(res->body.empty());
  6495. }
  6496. TEST_F(ServerTest, HeadMethod200Static) {
  6497. auto res = cli_.Head("/mount/dir/index.html");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6501. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6502. EXPECT_TRUE(res->body.empty());
  6503. }
  6504. TEST_F(ServerTest, HeadMethod404) {
  6505. auto res = cli_.Head("/invalid");
  6506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6508. EXPECT_TRUE(res->body.empty());
  6509. }
  6510. TEST_F(ServerTest, GetMethodPersonJohn) {
  6511. auto res = cli_.Get("/person/john");
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6515. EXPECT_EQ("programmer", res->body);
  6516. }
  6517. TEST_F(ServerTest, PostMethod1) {
  6518. auto res = cli_.Get("/person/john1");
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6521. res = cli_.Post("/person", "name=john1&note=coder",
  6522. "application/x-www-form-urlencoded");
  6523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6524. ASSERT_EQ(StatusCode::OK_200, res->status);
  6525. res = cli_.Get("/person/john1");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. ASSERT_EQ(StatusCode::OK_200, res->status);
  6528. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6529. ASSERT_EQ("coder", res->body);
  6530. }
  6531. TEST_F(ServerTest, PostMethod2) {
  6532. auto res = cli_.Get("/person/john2");
  6533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6534. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6535. Params params;
  6536. params.emplace("name", "john2");
  6537. params.emplace("note", "coder");
  6538. res = cli_.Post("/person", params);
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. ASSERT_EQ(StatusCode::OK_200, res->status);
  6541. res = cli_.Get("/person/john2");
  6542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6543. ASSERT_EQ(StatusCode::OK_200, res->status);
  6544. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6545. ASSERT_EQ("coder", res->body);
  6546. }
  6547. TEST_F(ServerTest, PutMethod3) {
  6548. auto res = cli_.Get("/person/john3");
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6551. Params params;
  6552. params.emplace("name", "john3");
  6553. params.emplace("note", "coder");
  6554. res = cli_.Put("/person", params);
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. ASSERT_EQ(StatusCode::OK_200, res->status);
  6557. res = cli_.Get("/person/john3");
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. ASSERT_EQ(StatusCode::OK_200, res->status);
  6560. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6561. ASSERT_EQ("coder", res->body);
  6562. }
  6563. TEST_F(ServerTest, DeleteMethod1) {
  6564. auto res = cli_.Get("/person/john4");
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6567. Params params;
  6568. params.emplace("name", "john4");
  6569. params.emplace("note", "coder");
  6570. res = cli_.Post("/person", params);
  6571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6572. ASSERT_EQ(StatusCode::OK_200, res->status);
  6573. res = cli_.Get("/person/john4");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. ASSERT_EQ(StatusCode::OK_200, res->status);
  6576. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. ASSERT_EQ("coder", res->body);
  6578. Params delete_params;
  6579. delete_params.emplace("name", "john4");
  6580. res = cli_.Delete("/person", delete_params);
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. ASSERT_EQ(StatusCode::OK_200, res->status);
  6583. ASSERT_EQ("DELETED", res->body);
  6584. res = cli_.Get("/person/john4");
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6587. }
  6588. TEST_F(ServerTest, DeleteMethod2) {
  6589. auto res = cli_.Get("/person/john5");
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6592. Params params;
  6593. params.emplace("name", "john5");
  6594. params.emplace("note", "developer");
  6595. res = cli_.Post("/person", params);
  6596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6597. ASSERT_EQ(StatusCode::OK_200, res->status);
  6598. res = cli_.Get("/person/john5");
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. ASSERT_EQ(StatusCode::OK_200, res->status);
  6601. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6602. ASSERT_EQ("developer", res->body);
  6603. Params delete_params;
  6604. delete_params.emplace("name", "john5");
  6605. Headers headers;
  6606. headers.emplace("Custom-Header", "test-value");
  6607. res = cli_.Delete("/person", headers, delete_params);
  6608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6609. ASSERT_EQ(StatusCode::OK_200, res->status);
  6610. ASSERT_EQ("DELETED", res->body);
  6611. res = cli_.Get("/person/john5");
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6614. }
  6615. TEST_F(ServerTest, DeleteMethod3) {
  6616. auto res = cli_.Get("/person/john6");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6619. Params params;
  6620. params.emplace("name", "john6");
  6621. params.emplace("note", "tester");
  6622. res = cli_.Post("/person", params);
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. ASSERT_EQ(StatusCode::OK_200, res->status);
  6625. res = cli_.Get("/person/john6");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. ASSERT_EQ(StatusCode::OK_200, res->status);
  6628. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6629. ASSERT_EQ("tester", res->body);
  6630. Params delete_params;
  6631. delete_params.emplace("name", "john6");
  6632. Headers headers;
  6633. headers.emplace("Custom-Header", "test-value");
  6634. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6636. ASSERT_EQ(StatusCode::OK_200, res->status);
  6637. ASSERT_EQ("DELETED", res->body);
  6638. res = cli_.Get("/person/john6");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6641. }
  6642. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6643. Params params;
  6644. params.emplace("json", JSON_DATA);
  6645. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. ASSERT_EQ(StatusCode::OK_200, res->status);
  6648. ASSERT_EQ(JSON_DATA, res->body);
  6649. }
  6650. TEST_F(ServerTest, PostEmptyContent) {
  6651. auto res = cli_.Post("/empty", "", "text/plain");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. ASSERT_EQ(StatusCode::OK_200, res->status);
  6654. ASSERT_EQ("empty", res->body);
  6655. }
  6656. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6657. auto res = cli_.Post("/empty-no-content-type");
  6658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6659. ASSERT_EQ(StatusCode::OK_200, res->status);
  6660. ASSERT_EQ("empty-no-content-type", res->body);
  6661. }
  6662. TEST_F(ServerTest, PostPathOnly) {
  6663. auto res = cli_.Post("/path-only");
  6664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6665. ASSERT_EQ(StatusCode::OK_200, res->status);
  6666. ASSERT_EQ("path-only", res->body);
  6667. }
  6668. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6669. auto res = cli_.Post("/path-headers-only",
  6670. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6672. ASSERT_EQ(StatusCode::OK_200, res->status);
  6673. ASSERT_EQ("path-headers-only", res->body);
  6674. }
  6675. TEST_F(ServerTest, PostLarge) {
  6676. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. ASSERT_EQ(StatusCode::OK_200, res->status);
  6679. EXPECT_EQ(LARGE_DATA, res->body);
  6680. }
  6681. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6682. auto res = cli_.Put("/empty-no-content-type");
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. ASSERT_EQ(StatusCode::OK_200, res->status);
  6685. ASSERT_EQ("empty-no-content-type", res->body);
  6686. }
  6687. TEST_F(ServerTest, GetMethodDir) {
  6688. auto res = cli_.Get("/dir/");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6692. auto body = R"(<html>
  6693. <head>
  6694. </head>
  6695. <body>
  6696. <a href="/dir/test.html">Test</a>
  6697. <a href="/hi">hi</a>
  6698. </body>
  6699. </html>
  6700. )";
  6701. EXPECT_EQ(body, res->body);
  6702. }
  6703. TEST_F(ServerTest, GetMethodDirTest) {
  6704. auto res = cli_.Get("/dir/test.html");
  6705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6706. EXPECT_EQ(StatusCode::OK_200, res->status);
  6707. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6708. EXPECT_EQ("test.html", res->body);
  6709. }
  6710. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6711. auto res = cli_.Get("/dir/../dir/test.html");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6714. }
  6715. TEST_F(ServerTest, GetMethodInvalidPath) {
  6716. auto res = cli_.Get("/dir/../test.html");
  6717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6719. }
  6720. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6721. auto res = cli_.Get("/../www/dir/test.html");
  6722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6724. }
  6725. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6726. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6729. }
  6730. TEST_F(ServerTest, GetMethodDirMountTest) {
  6731. auto res = cli_.Get("/mount/dir/test.html");
  6732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6733. EXPECT_EQ(StatusCode::OK_200, res->status);
  6734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6735. EXPECT_EQ("test.html", res->body);
  6736. }
  6737. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6738. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6741. }
  6742. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6743. auto res = cli_.Get("/mount/dir/../test.html");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6746. }
  6747. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6748. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6751. }
  6752. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6753. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6756. }
  6757. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6758. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6761. }
  6762. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6763. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6766. }
  6767. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6768. auto res = cli_.Get("/mount/dir");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6771. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6772. }
  6773. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6774. auto res = cli_.Get("//dir");
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6777. EXPECT_FALSE(res->has_header("Location"));
  6778. }
  6779. TEST_F(ServerTest, PostMethod303) {
  6780. auto res = cli_.Post("/1", "body", "text/plain");
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6783. EXPECT_EQ("/2", res->get_header_value("Location"));
  6784. }
  6785. TEST_F(ServerTest, PostMethod303Redirect) {
  6786. cli_.set_follow_location(true);
  6787. auto res = cli_.Post("/1", "body", "text/plain");
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. EXPECT_EQ("redirected.", res->body);
  6791. EXPECT_EQ("/2", res->location);
  6792. }
  6793. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6794. auto res = cli_.Get("/dir/test.abcde");
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6798. EXPECT_EQ("abcde", res->body);
  6799. }
  6800. TEST_F(ServerTest, StaticFileRange) {
  6801. auto res =
  6802. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6805. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6806. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6807. EXPECT_EQ(true, res->has_header("Content-Range"));
  6808. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6809. EXPECT_EQ(std::string("cd"), res->body);
  6810. }
  6811. TEST_F(ServerTest, StaticFileRanges) {
  6812. auto res = cli_.Get("/dir/test.abcde",
  6813. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6816. EXPECT_TRUE(
  6817. res->get_header_value("Content-Type")
  6818. .find(
  6819. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6820. 0);
  6821. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6822. }
  6823. TEST_F(ServerTest, StaticFileRangeHead) {
  6824. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6827. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6828. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6829. EXPECT_EQ(true, res->has_header("Content-Range"));
  6830. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6831. }
  6832. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6833. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6838. EXPECT_EQ(true, res->has_header("Content-Range"));
  6839. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6840. res->get_header_value("Content-Range"));
  6841. EXPECT_EQ("LAST\n", res->body);
  6842. }
  6843. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6844. auto res =
  6845. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6849. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6850. EXPECT_EQ(true, res->has_header("Content-Range"));
  6851. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6852. }
  6853. TEST_F(ServerTest, StaticFileBigFile) {
  6854. auto res = cli_.Get("/dir/1MB.txt");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6858. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6859. }
  6860. TEST_F(ServerTest, InvalidBaseDirMount) {
  6861. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6862. }
  6863. TEST_F(ServerTest, Binary) {
  6864. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6865. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6866. "application/octet-stream");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. ASSERT_EQ(StatusCode::OK_200, res->status);
  6869. ASSERT_EQ(4U, res->body.size());
  6870. res = cli_.Put("/binary", binary.data(), binary.size(),
  6871. "application/octet-stream");
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. ASSERT_EQ(StatusCode::OK_200, res->status);
  6874. ASSERT_EQ(4U, res->body.size());
  6875. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6876. "application/octet-stream");
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. ASSERT_EQ(StatusCode::OK_200, res->status);
  6879. ASSERT_EQ(4U, res->body.size());
  6880. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6881. "application/octet-stream");
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. ASSERT_EQ(StatusCode::OK_200, res->status);
  6884. ASSERT_EQ(4U, res->body.size());
  6885. }
  6886. TEST_F(ServerTest, BinaryString) {
  6887. auto binary = std::string("\x00\x01\x02\x03", 4);
  6888. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. ASSERT_EQ(StatusCode::OK_200, res->status);
  6891. ASSERT_EQ(4U, res->body.size());
  6892. res = cli_.Put("/binary", binary, "application/octet-stream");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. ASSERT_EQ(StatusCode::OK_200, res->status);
  6895. ASSERT_EQ(4U, res->body.size());
  6896. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6898. ASSERT_EQ(StatusCode::OK_200, res->status);
  6899. ASSERT_EQ(4U, res->body.size());
  6900. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. ASSERT_EQ(StatusCode::OK_200, res->status);
  6903. ASSERT_EQ(4U, res->body.size());
  6904. }
  6905. TEST_F(ServerTest, EmptyRequest) {
  6906. auto res = cli_.Get("");
  6907. ASSERT_TRUE(!res);
  6908. EXPECT_EQ(Error::Connection, res.error());
  6909. }
  6910. TEST_F(ServerTest, LongRequest) {
  6911. std::string request;
  6912. for (size_t i = 0; i < 545; i++) {
  6913. request += "/TooLongRequest";
  6914. }
  6915. request += "OK";
  6916. auto res = cli_.Get(request.c_str());
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6919. }
  6920. TEST_F(ServerTest, TooLongRequest) {
  6921. std::string request;
  6922. for (size_t i = 0; i < 546; i++) {
  6923. request += "/TooLongRequest";
  6924. }
  6925. request += "_NG";
  6926. auto start = std::chrono::high_resolution_clock::now();
  6927. cli_.set_keep_alive(true);
  6928. auto res = cli_.Get(request.c_str());
  6929. auto end = std::chrono::high_resolution_clock::now();
  6930. auto elapsed =
  6931. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6932. .count();
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6935. EXPECT_LE(elapsed, 1000);
  6936. EXPECT_EQ("close", res->get_header_value("Connection"));
  6937. EXPECT_FALSE(cli_.is_socket_open());
  6938. }
  6939. TEST_F(ServerTest, AlmostTooLongRequest) {
  6940. // test for #2046 - URI length check shouldn't include other content on req
  6941. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6942. // leading /, space, HTTP/1.1)
  6943. std::string request =
  6944. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6945. auto res = cli_.Get(request.c_str());
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6948. }
  6949. TEST_F(ServerTest, LongHeader) {
  6950. Request req;
  6951. req.method = "GET";
  6952. req.path = "/hi";
  6953. std::string host_and_port;
  6954. host_and_port += HOST;
  6955. host_and_port += ":";
  6956. host_and_port += std::to_string(PORT);
  6957. req.headers.emplace("Host", host_and_port.c_str());
  6958. req.headers.emplace("Accept", "*/*");
  6959. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6960. req.headers.emplace(
  6961. "Header-Name",
  6962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6990. "@@@@@@@@@@@@@@@@");
  6991. auto res = std::make_shared<Response>();
  6992. auto error = Error::Success;
  6993. auto ret = cli_.send(req, *res, error);
  6994. ASSERT_TRUE(ret);
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. }
  6997. TEST_F(ServerTest, LongQueryValue) {
  6998. auto start = std::chrono::high_resolution_clock::now();
  6999. cli_.set_keep_alive(true);
  7000. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7001. auto end = std::chrono::high_resolution_clock::now();
  7002. auto elapsed =
  7003. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7004. .count();
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7007. EXPECT_LE(elapsed, 1000);
  7008. EXPECT_EQ("close", res->get_header_value("Connection"));
  7009. EXPECT_FALSE(cli_.is_socket_open());
  7010. }
  7011. TEST_F(ServerTest, TooLongQueryValue) {
  7012. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7013. ASSERT_FALSE(res);
  7014. EXPECT_EQ(Error::Read, res.error());
  7015. }
  7016. TEST_F(ServerTest, TooLongHeader) {
  7017. Request req;
  7018. req.method = "GET";
  7019. req.path = "/hi";
  7020. std::string host_and_port;
  7021. host_and_port += HOST;
  7022. host_and_port += ":";
  7023. host_and_port += std::to_string(PORT);
  7024. req.headers.emplace("Host", host_and_port.c_str());
  7025. req.headers.emplace("Accept", "*/*");
  7026. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7027. req.headers.emplace(
  7028. "Header-Name",
  7029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7057. "@@@@@@@@@@@@@@@@@");
  7058. auto res = std::make_shared<Response>();
  7059. auto error = Error::Success;
  7060. auto ret = cli_.send(req, *res, error);
  7061. ASSERT_TRUE(ret);
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. }
  7064. TEST_F(ServerTest, HeaderCountAtLimit) {
  7065. // Test with headers just under the 100 limit
  7066. httplib::Headers headers;
  7067. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7068. // This should keep us just under the 100 header limit
  7069. for (int i = 0; i < 95; i++) {
  7070. std::string name = "X-Test-Header-" + std::to_string(i);
  7071. std::string value = "value" + std::to_string(i);
  7072. headers.emplace(name, value);
  7073. }
  7074. // This should work fine as we're under the limit
  7075. auto res = cli_.Get("/hi", headers);
  7076. EXPECT_TRUE(res);
  7077. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7078. }
  7079. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7080. // Test with many headers to exceed the 100 limit
  7081. httplib::Headers headers;
  7082. // Add 150 headers to definitely exceed the 100 limit
  7083. for (int i = 0; i < 150; i++) {
  7084. std::string name = "X-Test-Header-" + std::to_string(i);
  7085. std::string value = "value" + std::to_string(i);
  7086. headers.emplace(name, value);
  7087. }
  7088. // This should fail due to exceeding header count limit
  7089. cli_.set_keep_alive(true);
  7090. auto res = cli_.Get("/hi", headers);
  7091. // The server should respond with 400 Bad Request
  7092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7093. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7094. EXPECT_EQ("close", res->get_header_value("Connection"));
  7095. EXPECT_FALSE(cli_.is_socket_open());
  7096. }
  7097. TEST_F(ServerTest, PercentEncoding) {
  7098. auto res = cli_.Get("/e%6edwith%");
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::OK_200, res->status);
  7101. }
  7102. TEST_F(ServerTest, PercentEncodingUnicode) {
  7103. auto res = cli_.Get("/e%u006edwith%");
  7104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7105. EXPECT_EQ(StatusCode::OK_200, res->status);
  7106. }
  7107. TEST_F(ServerTest, InvalidPercentEncoding) {
  7108. auto res = cli_.Get("/%endwith%");
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7111. }
  7112. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7113. auto res = cli_.Get("/%uendwith%");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7116. }
  7117. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7118. auto res = cli_.Get("/hello?aaa=bbb%");
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7121. }
  7122. TEST_F(ServerTest, PlusSignEncoding) {
  7123. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::OK_200, res->status);
  7126. EXPECT_EQ("a +b", res->body);
  7127. }
  7128. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7129. // This test simulates a potential DoS attack using many headers
  7130. // to verify our security fix prevents memory exhaustion
  7131. httplib::Headers attack_headers;
  7132. // Attempt to add many headers like an attacker would (200 headers to far
  7133. // exceed limit)
  7134. for (int i = 0; i < 200; i++) {
  7135. std::string name = "X-Attack-Header-" + std::to_string(i);
  7136. std::string value = "attack_payload_" + std::to_string(i);
  7137. attack_headers.emplace(name, value);
  7138. }
  7139. // Try to POST with excessive headers
  7140. cli_.set_keep_alive(true);
  7141. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7142. // Should either fail or return 400 Bad Request due to security limit
  7143. if (res) {
  7144. // If we get a response, it should be 400 Bad Request
  7145. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7146. EXPECT_EQ("close", res->get_header_value("Connection"));
  7147. }
  7148. EXPECT_FALSE(cli_.is_socket_open());
  7149. }
  7150. TEST_F(ServerTest, MultipartFormData) {
  7151. UploadFormDataItems items = {
  7152. {"text1", "text default", "", ""},
  7153. {"text2", "aωb", "", ""},
  7154. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7155. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7156. {"file3", "", "", "application/octet-stream"},
  7157. {"file4", "", "", " application/json tmp-string "}};
  7158. auto res = cli_.Post("/multipart", items);
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::OK_200, res->status);
  7161. }
  7162. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7163. UploadFormDataItems items = {
  7164. {"text", "default text", "", ""},
  7165. {"multi_text1", "aaaaa", "", ""},
  7166. {"multi_text1", "bbbbb", "", ""},
  7167. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7168. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7169. "application/json"},
  7170. };
  7171. auto res = cli_.Post("/multipart/multi_file_values", items);
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::OK_200, res->status);
  7174. }
  7175. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7176. auto res = cli_.Get("/hi");
  7177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7178. EXPECT_EQ(StatusCode::OK_200, res->status);
  7179. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7180. EXPECT_EQ("Hello World!", res->body);
  7181. }
  7182. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7183. Request req;
  7184. req.method = "POST";
  7185. req.path = "/chunked";
  7186. std::string host_and_port;
  7187. host_and_port += HOST;
  7188. host_and_port += ":";
  7189. host_and_port += std::to_string(PORT);
  7190. req.headers.emplace("Host", host_and_port.c_str());
  7191. req.headers.emplace("Accept", "*/*");
  7192. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7193. req.headers.emplace("Content-Type", "text/plain");
  7194. req.headers.emplace("Content-Length", "0");
  7195. req.headers.emplace(
  7196. "Transfer-Encoding",
  7197. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7198. // Client does not chunk, so make a chunked body manually.
  7199. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7200. auto res = std::make_shared<Response>();
  7201. auto error = Error::Success;
  7202. auto ret = cli_.send(req, *res, error);
  7203. ASSERT_TRUE(ret);
  7204. EXPECT_EQ(StatusCode::OK_200, res->status);
  7205. }
  7206. template <typename ClientT>
  7207. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7208. int expected_status) {
  7209. Request req;
  7210. req.method = "POST";
  7211. req.path = "/chunked";
  7212. std::string host_and_port;
  7213. host_and_port += HOST;
  7214. host_and_port += ":";
  7215. host_and_port += std::to_string(PORT);
  7216. req.headers.emplace("Host", host_and_port.c_str());
  7217. req.headers.emplace("Content-Length", "0");
  7218. req.headers.emplace("Transfer-Encoding", "chunked");
  7219. req.body = body;
  7220. auto res = std::make_shared<Response>();
  7221. auto error = Error::Success;
  7222. ASSERT_TRUE(cli.send(req, *res, error));
  7223. EXPECT_EQ(expected_status, res->status);
  7224. }
  7225. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7226. // rather than treat them as valid lengths.
  7227. template <typename ClientT>
  7228. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7229. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7230. }
  7231. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7232. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7233. }
  7234. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7235. expect_chunked_body_rejected(
  7236. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7237. }
  7238. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7239. // chunk-size line carries no CR, LF or other control character ahead of its
  7240. // terminator. Such a line must be refused rather than read as extension text.
  7241. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7242. expect_chunked_body_rejected(
  7243. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7244. }
  7245. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7246. expect_chunked_body_rejected(
  7247. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7248. }
  7249. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7250. expect_chunked_body_rejected(
  7251. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7252. }
  7253. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7254. // The literal stays split: a hex escape consumes every hex digit that
  7255. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7256. expect_chunked_body_rejected(
  7257. cli_, "4;a\x01"
  7258. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7259. }
  7260. // The bytes around chunk data are no payload, so they cannot ride on the
  7261. // payload limit
  7262. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7263. // Small enough that the whole request is sent before the server turns it
  7264. // down, yet past the limit by the last chunks
  7265. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7266. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7267. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7268. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7269. SCOPED_TRACE(size_line.substr(0, 2));
  7270. std::string body;
  7271. for (auto c : std::string("dechunked post body")) {
  7272. body += size_line + "\r\n" + c + "\r\n";
  7273. }
  7274. body += "0\r\n\r\n";
  7275. expect_chunked_body_rejected(cli_, body.c_str());
  7276. }
  7277. }
  7278. TEST_F(ServerTest, AcceptsChunkExtension) {
  7279. expect_chunked_body_status(cli_,
  7280. "4;name=value\r\ndech\r\n"
  7281. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7282. "0;last\r\n\r\n",
  7283. StatusCode::OK_200);
  7284. }
  7285. TEST_F(ServerTest, GetStreamed2) {
  7286. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7289. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7290. EXPECT_EQ(true, res->has_header("Content-Range"));
  7291. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7292. EXPECT_EQ(std::string("ab"), res->body);
  7293. }
  7294. TEST_F(ServerTest, GetStreamed) {
  7295. auto res = cli_.Get("/streamed");
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7299. EXPECT_EQ(std::string("aaabbb"), res->body);
  7300. }
  7301. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7302. auto res = cli_.Get("/streamed-without-length",
  7303. Headers{make_range_header({{0, -1}})});
  7304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7305. EXPECT_EQ(StatusCode::OK_200, res->status);
  7306. EXPECT_EQ(false, res->has_header("Content-Length"));
  7307. EXPECT_EQ(false, res->has_header("Content-Range"));
  7308. EXPECT_EQ(std::string("abcdefg"), res->body);
  7309. }
  7310. TEST_F(ServerTest, GetStreamedWithRange1) {
  7311. auto res =
  7312. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7315. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7316. EXPECT_EQ(true, res->has_header("Content-Range"));
  7317. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7318. EXPECT_EQ(std::string("def"), res->body);
  7319. }
  7320. TEST_F(ServerTest, GetStreamedWithRange2) {
  7321. auto res =
  7322. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7325. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7326. EXPECT_EQ(true, res->has_header("Content-Range"));
  7327. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7328. EXPECT_EQ(std::string("bcdefg"), res->body);
  7329. }
  7330. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7331. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7334. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7335. EXPECT_EQ(true, res->has_header("Content-Range"));
  7336. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7337. EXPECT_EQ(std::string("efg"), res->body);
  7338. }
  7339. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7340. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7341. // the entire representation.
  7342. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7343. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7345. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7346. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7347. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7348. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7349. }
  7350. }
  7351. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7352. auto res =
  7353. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7356. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7357. EXPECT_EQ(false, res->has_header("Content-Range"));
  7358. EXPECT_EQ(0U, res->body.size());
  7359. }
  7360. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7361. // Only a 206 is served as a partial representation. Under any other status
  7362. // `apply_ranges()` reported the full content length, so the body must match
  7363. // that header, and the content provider must never be asked for an offset
  7364. // outside the representation.
  7365. auto check = [&](int status, const char *range) {
  7366. auto path =
  7367. std::string("/streamed-with-range?status=") + std::to_string(status);
  7368. auto ctx = path + " Range: " + range;
  7369. auto res = cli_.Get(path, Headers{{"Range", range}});
  7370. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7371. EXPECT_EQ(status, res->status) << ctx;
  7372. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7374. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7375. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7376. };
  7377. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7378. check(403, "bytes=3-5");
  7379. // The offset is far past the representation.
  7380. check(403, "bytes=100000-100200");
  7381. // `first_pos` is still -1 here, and the bounds asserts in
  7382. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7383. check(403, "bytes=-3");
  7384. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7385. // multipart branch would have written one that is empty.
  7386. check(403, "bytes=1-2, 4-5");
  7387. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7388. // covers the whole representation.
  7389. check(200, "bytes=3-5");
  7390. check(200, "bytes=1-2, 4-5");
  7391. }
  7392. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7393. auto res =
  7394. cli_.Get("/streamed-with-range",
  7395. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7396. "92233720368547758079223372036854775807"}});
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7399. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7400. EXPECT_EQ(false, res->has_header("Content-Range"));
  7401. EXPECT_EQ(0U, res->body.size());
  7402. }
  7403. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7404. auto res = cli_.Get(
  7405. "/with-range",
  7406. Headers{{"Range",
  7407. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7408. {"Accept-Encoding", ""}});
  7409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7410. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7411. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7412. EXPECT_EQ(true, res->has_header("Content-Range"));
  7413. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7414. EXPECT_EQ(std::string("abcdefg"), res->body);
  7415. }
  7416. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7417. auto res = cli_.Get("/with-range", Headers{
  7418. {"Range", "bytes=0-"},
  7419. {"Accept-Encoding", ""},
  7420. });
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7423. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7424. EXPECT_EQ(true, res->has_header("Content-Range"));
  7425. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7426. EXPECT_EQ(std::string("abcdefg"), res->body);
  7427. }
  7428. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7429. auto res = cli_.Get("/streamed-with-range",
  7430. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7433. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7434. EXPECT_EQ(false, res->has_header("Content-Range"));
  7435. EXPECT_EQ(267U, res->body.size());
  7436. // Check that both range contents are present
  7437. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7438. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7439. // Check that Content-Range headers are present for both ranges
  7440. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7441. std::string::npos);
  7442. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7443. std::string::npos);
  7444. }
  7445. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7446. Ranges ranges;
  7447. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7448. ranges.emplace_back(0, -1);
  7449. }
  7450. auto res = cli_.Get("/streamed-with-range?error",
  7451. Headers{{make_range_header(ranges)}});
  7452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7453. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7454. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7455. EXPECT_EQ(false, res->has_header("Content-Range"));
  7456. EXPECT_EQ(0U, res->body.size());
  7457. }
  7458. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7459. auto res = cli_.Get("/streamed-with-range",
  7460. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7463. EXPECT_EQ(5U, res->body.size());
  7464. // Check that overlapping ranges are coalesced into a single range
  7465. EXPECT_EQ("bcdef", res->body);
  7466. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7467. // Should be single range, not multipart
  7468. EXPECT_TRUE(res->has_header("Content-Range"));
  7469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7470. }
  7471. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7472. auto res = cli_.Get("/streamed-with-range",
  7473. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7476. EXPECT_EQ(268U, res->body.size());
  7477. // Check that both range contents are present
  7478. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7479. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7480. // Check that Content-Range headers are present for both ranges
  7481. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7482. std::string::npos);
  7483. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7484. std::string::npos);
  7485. }
  7486. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7487. auto res = cli_.Get("/streamed-with-range",
  7488. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7491. EXPECT_EQ(269U, res->body.size());
  7492. // Check that both duplicate range contents are present
  7493. size_t first_abc = res->body.find("abc\r\n");
  7494. EXPECT_TRUE(first_abc != std::string::npos);
  7495. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7496. EXPECT_TRUE(second_abc != std::string::npos);
  7497. // Check that Content-Range headers are present for both ranges
  7498. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7499. EXPECT_TRUE(first_range != std::string::npos);
  7500. size_t second_range =
  7501. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7502. EXPECT_TRUE(second_range != std::string::npos);
  7503. }
  7504. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7505. auto res =
  7506. cli_.Get("/streamed-with-range?error",
  7507. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7510. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7511. EXPECT_EQ(false, res->has_header("Content-Range"));
  7512. EXPECT_EQ(0U, res->body.size());
  7513. }
  7514. TEST_F(ServerTest, GetStreamedEndless) {
  7515. uint64_t offset = 0;
  7516. auto res = cli_.Get("/streamed-cancel",
  7517. [&](const char * /*data*/, uint64_t data_length) {
  7518. if (offset < 100) {
  7519. offset += data_length;
  7520. return true;
  7521. }
  7522. return false;
  7523. });
  7524. ASSERT_TRUE(!res);
  7525. EXPECT_EQ(Error::Canceled, res.error());
  7526. }
  7527. TEST_F(ServerTest, ClientStop) {
  7528. std::atomic_size_t count{4};
  7529. std::vector<std::thread> threads;
  7530. for (auto i = count.load(); i != 0; --i) {
  7531. threads.emplace_back([&]() {
  7532. auto res = cli_.Get("/streamed-cancel",
  7533. [&](const char *, uint64_t) { return true; });
  7534. --count;
  7535. ASSERT_TRUE(!res);
  7536. EXPECT_TRUE(res.error() == Error::Canceled ||
  7537. res.error() == Error::Read || res.error() == Error::Write);
  7538. });
  7539. }
  7540. std::this_thread::sleep_for(std::chrono::seconds(2));
  7541. while (count != 0) {
  7542. cli_.stop();
  7543. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7544. }
  7545. for (auto &t : threads) {
  7546. t.join();
  7547. }
  7548. }
  7549. TEST_F(ServerTest, GetWithRange1) {
  7550. auto res = cli_.Get("/with-range", Headers{
  7551. make_range_header({{3, 5}}),
  7552. {"Accept-Encoding", ""},
  7553. });
  7554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7556. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7557. EXPECT_EQ(true, res->has_header("Content-Range"));
  7558. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7559. EXPECT_EQ(std::string("def"), res->body);
  7560. }
  7561. TEST_F(ServerTest, GetWithRange2) {
  7562. auto res = cli_.Get("/with-range", Headers{
  7563. make_range_header({{1, -1}}),
  7564. {"Accept-Encoding", ""},
  7565. });
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7568. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7569. EXPECT_EQ(true, res->has_header("Content-Range"));
  7570. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7571. EXPECT_EQ(std::string("bcdefg"), res->body);
  7572. }
  7573. TEST_F(ServerTest, GetWithRange3) {
  7574. auto res = cli_.Get("/with-range", Headers{
  7575. make_range_header({{0, 0}}),
  7576. {"Accept-Encoding", ""},
  7577. });
  7578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7580. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7581. EXPECT_EQ(true, res->has_header("Content-Range"));
  7582. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7583. EXPECT_EQ(std::string("a"), res->body);
  7584. }
  7585. TEST_F(ServerTest, GetWithRange4) {
  7586. auto res = cli_.Get("/with-range", Headers{
  7587. make_range_header({{-1, 2}}),
  7588. {"Accept-Encoding", ""},
  7589. });
  7590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7592. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7593. EXPECT_EQ(true, res->has_header("Content-Range"));
  7594. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7595. EXPECT_EQ(std::string("fg"), res->body);
  7596. }
  7597. TEST_F(ServerTest, GetWithRange5) {
  7598. auto res = cli_.Get("/with-range", Headers{
  7599. make_range_header({{0, 5}}),
  7600. {"Accept-Encoding", ""},
  7601. });
  7602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7604. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7605. EXPECT_EQ(true, res->has_header("Content-Range"));
  7606. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7607. EXPECT_EQ(std::string("abcdef"), res->body);
  7608. }
  7609. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7610. auto res =
  7611. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7614. }
  7615. TEST_F(ServerTest, GetWithRangeMultipart) {
  7616. auto res =
  7617. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7620. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7621. EXPECT_EQ(false, res->has_header("Content-Range"));
  7622. EXPECT_EQ(267U, res->body.size());
  7623. }
  7624. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7625. auto res = cli_.Get("/with-range",
  7626. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7628. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7629. }
  7630. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7631. auto res = cli_.Get("/with-range-customized-response",
  7632. Headers{{make_range_header({{1, 2}})}});
  7633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7634. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7635. EXPECT_EQ(true, res->has_header("Content-Length"));
  7636. EXPECT_EQ(false, res->has_header("Content-Range"));
  7637. EXPECT_EQ(JSON_DATA, res->body);
  7638. }
  7639. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7640. auto res = cli_.Get("/with-range-customized-response",
  7641. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7644. EXPECT_EQ(true, res->has_header("Content-Length"));
  7645. EXPECT_EQ(false, res->has_header("Content-Range"));
  7646. EXPECT_EQ(JSON_DATA, res->body);
  7647. }
  7648. TEST_F(ServerTest, Issue1772) {
  7649. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7652. }
  7653. TEST_F(ServerTest, Issue609) {
  7654. auto res = cli_.Delete("/issue609");
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. EXPECT_EQ(std::string("ok"), res->body);
  7658. }
  7659. TEST_F(ServerTest, GetStreamedChunked) {
  7660. auto res = cli_.Get("/streamed-chunked");
  7661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7662. EXPECT_EQ(StatusCode::OK_200, res->status);
  7663. EXPECT_EQ(std::string("123456789"), res->body);
  7664. }
  7665. TEST_F(ServerTest, GetStreamedChunked2) {
  7666. auto res = cli_.Get("/streamed-chunked2");
  7667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. EXPECT_EQ(std::string("123456789"), res->body);
  7670. }
  7671. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7672. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ(std::string("123456789"), res->body);
  7676. EXPECT_TRUE(res->has_header("Trailer"));
  7677. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7678. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7679. // Trailers are now stored separately from headers (security fix)
  7680. EXPECT_EQ(2U, res->trailers.size());
  7681. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7682. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7683. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7684. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7685. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7686. // Verify trailers are NOT in headers (security verification)
  7687. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7688. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7689. }
  7690. TEST_F(ServerTest, LargeChunkedPost) {
  7691. Request req;
  7692. req.method = "POST";
  7693. req.path = "/large-chunked";
  7694. std::string host_and_port;
  7695. host_and_port += HOST;
  7696. host_and_port += ":";
  7697. host_and_port += std::to_string(PORT);
  7698. req.headers.emplace("Host", host_and_port.c_str());
  7699. req.headers.emplace("Accept", "*/*");
  7700. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7701. req.headers.emplace("Content-Type", "text/plain");
  7702. req.headers.emplace("Content-Length", "0");
  7703. req.headers.emplace("Transfer-Encoding", "chunked");
  7704. std::string long_string(30 * 1024u, 'a');
  7705. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7706. // Attempt to make a large enough post to exceed OS buffers, to test that
  7707. // the server handles short reads if the full chunk data isn't available.
  7708. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7709. auto res = std::make_shared<Response>();
  7710. auto error = Error::Success;
  7711. auto ret = cli_.send(req, *res, error);
  7712. ASSERT_TRUE(ret);
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. }
  7715. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7716. auto res = cli_.Get("/remote_addr");
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7720. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7721. }
  7722. TEST_F(ServerTest, GetMethodLocalAddr) {
  7723. auto res = cli_.Get("/local_addr");
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::OK_200, res->status);
  7726. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7727. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7728. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7729. }
  7730. TEST_F(ServerTest, HTTPResponseSplitting) {
  7731. auto res = cli_.Get("/http_response_splitting");
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. }
  7735. TEST_F(ServerTest, SlowRequest) {
  7736. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7737. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7738. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7739. }
  7740. #if 0
  7741. TEST_F(ServerTest, SlowPost) {
  7742. char buffer[64 * 1024];
  7743. memset(buffer, 0x42, sizeof(buffer));
  7744. auto res = cli_.Post(
  7745. "/slowpost", 64 * 1024 * 1024,
  7746. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7747. auto ret = sink.write(buffer, sizeof(buffer));
  7748. EXPECT_TRUE(ret);
  7749. return true;
  7750. },
  7751. "text/plain");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. }
  7755. TEST_F(ServerTest, SlowPostFail) {
  7756. char buffer[64 * 1024];
  7757. memset(buffer, 0x42, sizeof(buffer));
  7758. cli_.set_write_timeout(std::chrono::seconds(0));
  7759. auto res = cli_.Post(
  7760. "/slowpost", 64 * 1024 * 1024,
  7761. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7762. sink.write(buffer, sizeof(buffer));
  7763. return true;
  7764. },
  7765. "text/plain");
  7766. ASSERT_TRUE(!res);
  7767. EXPECT_EQ(Error::Write, res.error());
  7768. }
  7769. #endif
  7770. TEST_F(ServerTest, Put) {
  7771. auto res = cli_.Put("/put", "PUT", "text/plain");
  7772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7773. EXPECT_EQ(StatusCode::OK_200, res->status);
  7774. EXPECT_EQ("PUT", res->body);
  7775. }
  7776. TEST_F(ServerTest, PutWithContentProvider) {
  7777. auto res = cli_.Put(
  7778. "/put", 3,
  7779. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7780. sink.os << "PUT";
  7781. return true;
  7782. },
  7783. "text/plain");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. EXPECT_EQ("PUT", res->body);
  7787. }
  7788. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7789. auto res = cli_.Post(
  7790. "/post", 42,
  7791. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7792. return false;
  7793. },
  7794. "text/plain");
  7795. ASSERT_TRUE(!res);
  7796. EXPECT_EQ(Error::Canceled, res.error());
  7797. }
  7798. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7799. auto res = cli_.Put(
  7800. "/put",
  7801. [](size_t /*offset*/, DataSink &sink) {
  7802. sink.os << "PUT";
  7803. sink.done();
  7804. return true;
  7805. },
  7806. "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, PostWithContentProviderWithoutLengthAbort) {
  7812. auto res = cli_.Post(
  7813. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7814. "text/plain");
  7815. ASSERT_TRUE(!res);
  7816. EXPECT_EQ(Error::Canceled, res.error());
  7817. }
  7818. TEST_F(ServerTest, PostLoopBack) {
  7819. std::string body;
  7820. auto res = cli_.Post(
  7821. "/post-loopback", 9,
  7822. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7823. EXPECT_EQ(9u, length);
  7824. sink.write("123", 3);
  7825. sink.write("456", 3);
  7826. sink.write("789", 3);
  7827. return true;
  7828. },
  7829. "text/plain",
  7830. [&body](const char *data, size_t data_length) {
  7831. body.append(data, data_length);
  7832. return true;
  7833. });
  7834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7835. EXPECT_EQ(StatusCode::OK_200, res->status);
  7836. EXPECT_EQ("123456789", body);
  7837. }
  7838. TEST_F(ServerTest, PutLoopBack) {
  7839. std::string body;
  7840. auto res = cli_.Put(
  7841. "/put-loopback", 9,
  7842. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7843. EXPECT_EQ(9u, length);
  7844. sink.write("123", 3);
  7845. sink.write("456", 3);
  7846. sink.write("789", 3);
  7847. return true;
  7848. },
  7849. "text/plain",
  7850. [&body](const char *data, size_t data_length) {
  7851. body.append(data, data_length);
  7852. return true;
  7853. });
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. EXPECT_EQ("123456789", body);
  7857. }
  7858. TEST_F(ServerTest, PatchLoopBack) {
  7859. std::string body;
  7860. auto res = cli_.Patch(
  7861. "/patch-loopback", 9,
  7862. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7863. EXPECT_EQ(9u, length);
  7864. sink.write("123", 3);
  7865. sink.write("456", 3);
  7866. sink.write("789", 3);
  7867. return true;
  7868. },
  7869. "text/plain",
  7870. [&body](const char *data, size_t data_length) {
  7871. body.append(data, data_length);
  7872. return true;
  7873. });
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. EXPECT_EQ("123456789", body);
  7877. }
  7878. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7879. std::string body;
  7880. auto res = cli_.Post(
  7881. "/post-loopback",
  7882. [](size_t /*offset*/, DataSink &sink) {
  7883. sink.write("123", 3);
  7884. sink.write("456", 3);
  7885. sink.write("789", 3);
  7886. sink.done();
  7887. return true;
  7888. },
  7889. "text/plain",
  7890. [&body](const char *data, size_t data_length) {
  7891. body.append(data, data_length);
  7892. return true;
  7893. });
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. EXPECT_EQ("123456789", body);
  7897. }
  7898. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7899. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7900. cli_.set_compress(true);
  7901. auto res = cli_.Put(
  7902. "/put", 3,
  7903. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7904. sink.os << "PUT";
  7905. return true;
  7906. },
  7907. "text/plain");
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. EXPECT_EQ("PUT", res->body);
  7911. }
  7912. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7913. cli_.set_compress(true);
  7914. auto res = cli_.Post(
  7915. "/post", 42,
  7916. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7917. return false;
  7918. },
  7919. "text/plain");
  7920. ASSERT_TRUE(!res);
  7921. EXPECT_EQ(Error::Canceled, res.error());
  7922. }
  7923. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7924. cli_.set_compress(true);
  7925. auto res = cli_.Put(
  7926. "/put",
  7927. [](size_t /*offset*/, DataSink &sink) {
  7928. sink.os << "PUT";
  7929. sink.done();
  7930. return true;
  7931. },
  7932. "text/plain");
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::OK_200, res->status);
  7935. EXPECT_EQ("PUT", res->body);
  7936. }
  7937. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7938. cli_.set_compress(true);
  7939. auto res = cli_.Post(
  7940. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7941. "text/plain");
  7942. ASSERT_TRUE(!res);
  7943. EXPECT_EQ(Error::Canceled, res.error());
  7944. }
  7945. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7946. cli_.set_compress(true);
  7947. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ(StatusCode::OK_200, res->status);
  7950. EXPECT_EQ(LARGE_DATA, res->body);
  7951. }
  7952. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7953. #ifdef CPPHTTPLIB_SSL_ENABLED
  7954. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7955. Client cli(s.c_str());
  7956. cli.enable_server_certificate_verification(false);
  7957. #else
  7958. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7959. Client cli(s.c_str());
  7960. #endif
  7961. cli.set_compress(true);
  7962. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_EQ(LARGE_DATA, res->body);
  7966. // The compressed size should be less than a 10th of the original. May vary
  7967. // depending on the zlib library.
  7968. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7969. static_cast<uint64_t>(10 * 1024 * 1024));
  7970. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7971. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7972. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7973. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7974. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7975. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7976. #endif
  7977. }
  7978. TEST_F(ServerTest, PutContentWithDeflate) {
  7979. cli_.set_compress(false);
  7980. Headers headers;
  7981. headers.emplace("Content-Encoding", "deflate");
  7982. // PUT in deflate format:
  7983. auto res = cli_.Put("/put", headers,
  7984. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. EXPECT_EQ("PUT", res->body);
  7988. }
  7989. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7990. Headers headers;
  7991. headers.emplace("Accept-Encoding", "gzip, deflate");
  7992. auto res = cli_.Get("/streamed-chunked", headers);
  7993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7994. EXPECT_EQ(StatusCode::OK_200, res->status);
  7995. EXPECT_EQ(std::string("123456789"), res->body);
  7996. }
  7997. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7998. Headers headers;
  7999. headers.emplace("Accept-Encoding", "gzip, deflate");
  8000. auto res = cli_.Get("/streamed-chunked2", headers);
  8001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8002. EXPECT_EQ(StatusCode::OK_200, res->status);
  8003. EXPECT_EQ(std::string("123456789"), res->body);
  8004. }
  8005. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8006. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. }
  8010. TEST(GzipDecompressor, ChunkedDecompression) {
  8011. std::string data;
  8012. for (size_t i = 0; i < 32 * 1024; ++i) {
  8013. data.push_back(static_cast<char>('a' + i % 26));
  8014. }
  8015. std::string compressed_data;
  8016. {
  8017. httplib::detail::gzip_compressor compressor;
  8018. bool result = compressor.compress(
  8019. data.data(), data.size(),
  8020. /*last=*/true,
  8021. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8022. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8023. compressed_data_size);
  8024. return true;
  8025. });
  8026. ASSERT_TRUE(result);
  8027. }
  8028. std::string decompressed_data;
  8029. {
  8030. httplib::detail::gzip_decompressor decompressor;
  8031. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8032. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8033. size_t chunk_size = 130;
  8034. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8035. chunk_begin += chunk_size) {
  8036. size_t current_chunk_size =
  8037. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8038. bool result = decompressor.decompress(
  8039. compressed_data.data() + chunk_begin, current_chunk_size,
  8040. [&](const char *decompressed_data_chunk,
  8041. size_t decompressed_data_chunk_size) {
  8042. decompressed_data.insert(decompressed_data.size(),
  8043. decompressed_data_chunk,
  8044. decompressed_data_chunk_size);
  8045. return true;
  8046. });
  8047. ASSERT_TRUE(result);
  8048. }
  8049. }
  8050. ASSERT_EQ(data, decompressed_data);
  8051. }
  8052. TEST(GzipDecompressor, DeflateDecompression) {
  8053. std::string original_text = "Raw deflate without gzip";
  8054. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8055. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8056. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8057. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8058. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8059. std::string decompressed_data;
  8060. {
  8061. httplib::detail::gzip_decompressor decompressor;
  8062. bool result = decompressor.decompress(
  8063. compressed_data.data(), compressed_data.size(),
  8064. [&](const char *decompressed_data_chunk,
  8065. size_t decompressed_data_chunk_size) {
  8066. decompressed_data.insert(decompressed_data.size(),
  8067. decompressed_data_chunk,
  8068. decompressed_data_chunk_size);
  8069. return true;
  8070. });
  8071. ASSERT_TRUE(result);
  8072. }
  8073. ASSERT_EQ(original_text, decompressed_data);
  8074. }
  8075. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8076. std::string original_text = "Raw deflate without gzip";
  8077. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8078. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8079. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8080. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8081. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8082. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8083. std::string decompressed_data;
  8084. {
  8085. httplib::detail::gzip_decompressor decompressor;
  8086. bool result = decompressor.decompress(
  8087. compressed_data.data(), compressed_data.size(),
  8088. [&](const char *decompressed_data_chunk,
  8089. size_t decompressed_data_chunk_size) {
  8090. decompressed_data.insert(decompressed_data.size(),
  8091. decompressed_data_chunk,
  8092. decompressed_data_chunk_size);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(result);
  8096. }
  8097. ASSERT_EQ(original_text, decompressed_data);
  8098. }
  8099. #endif
  8100. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8101. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8102. Headers headers;
  8103. headers.emplace("Accept-Encoding", "br");
  8104. auto res = cli_.Get("/streamed-chunked", headers);
  8105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8106. EXPECT_EQ(StatusCode::OK_200, res->status);
  8107. EXPECT_EQ(std::string("123456789"), res->body);
  8108. }
  8109. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8110. Headers headers;
  8111. headers.emplace("Accept-Encoding", "br");
  8112. auto res = cli_.Get("/streamed-chunked2", headers);
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. EXPECT_EQ(std::string("123456789"), res->body);
  8116. }
  8117. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8118. cli_.set_compress(true);
  8119. auto res = cli_.Put(
  8120. "/put", 3,
  8121. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8122. sink.os << "PUT";
  8123. return true;
  8124. },
  8125. "text/plain");
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. EXPECT_EQ("PUT", res->body);
  8129. }
  8130. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8131. cli_.set_compress(true);
  8132. auto res = cli_.Put(
  8133. "/put",
  8134. [](size_t /*offset*/, DataSink &sink) {
  8135. sink.os << "PUT";
  8136. sink.done();
  8137. return true;
  8138. },
  8139. "text/plain");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. EXPECT_EQ("PUT", res->body);
  8143. }
  8144. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8145. cli_.set_compress(true);
  8146. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8148. EXPECT_EQ(StatusCode::OK_200, res->status);
  8149. EXPECT_EQ(LARGE_DATA, res->body);
  8150. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8151. }
  8152. #endif
  8153. TEST_F(ServerTest, Patch) {
  8154. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. EXPECT_EQ(StatusCode::OK_200, res->status);
  8157. EXPECT_EQ("PATCH", res->body);
  8158. }
  8159. TEST_F(ServerTest, Delete) {
  8160. auto res = cli_.Delete("/delete");
  8161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8162. EXPECT_EQ(StatusCode::OK_200, res->status);
  8163. EXPECT_EQ("DELETE", res->body);
  8164. }
  8165. TEST_F(ServerTest, DeleteContentReceiver) {
  8166. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::OK_200, res->status);
  8169. EXPECT_EQ("content", res->body);
  8170. }
  8171. TEST_F(ServerTest, Options) {
  8172. auto res = cli_.Options("*");
  8173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8174. EXPECT_EQ(StatusCode::OK_200, res->status);
  8175. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8176. EXPECT_TRUE(res->body.empty());
  8177. }
  8178. TEST_F(ServerTest, URL) {
  8179. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::OK_200, res->status);
  8182. }
  8183. TEST_F(ServerTest, ArrayParam) {
  8184. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8186. EXPECT_EQ(StatusCode::OK_200, res->status);
  8187. }
  8188. TEST_F(ServerTest, ArrayParamValues) {
  8189. auto res =
  8190. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. }
  8194. TEST_F(ServerTest, NoMultipleHeaders) {
  8195. Headers headers = {{"Content-Length", "5"}};
  8196. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8197. "text/plain");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. }
  8201. TEST_F(ServerTest, PostContentReceiver) {
  8202. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8204. ASSERT_EQ(StatusCode::OK_200, res->status);
  8205. ASSERT_EQ("content", res->body);
  8206. }
  8207. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8208. UploadFormDataItems items = {
  8209. {"text1", "text default", "", ""},
  8210. {"text2", "aωb", "", ""},
  8211. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8212. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8213. {"file3", "", "", "application/octet-stream"},
  8214. };
  8215. auto res = cli_.Post("/content_receiver", items);
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. }
  8219. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8220. UploadFormDataItems items = {
  8221. {"text1", "text default", "", ""},
  8222. {"text2", "aωb", "", ""},
  8223. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8224. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8225. {"file3", "", "", "application/octet-stream"},
  8226. };
  8227. auto boundary = std::string("+++++");
  8228. std::string body;
  8229. for (const auto &item : items) {
  8230. body += "--" + boundary + "\r\n";
  8231. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8232. if (!item.filename.empty()) {
  8233. body += "; filename=\"" + item.filename + "\"";
  8234. }
  8235. body += "\r\n";
  8236. if (!item.content_type.empty()) {
  8237. body += "Content-Type: " + item.content_type + "\r\n";
  8238. }
  8239. body += "\r\n";
  8240. body += item.content + "\r\n";
  8241. }
  8242. body += "--" + boundary + "--\r\n";
  8243. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8244. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::OK_200, res->status);
  8247. }
  8248. TEST(MultipartFormDataTest, FieldEscaping) {
  8249. Server svr;
  8250. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8251. const ContentReader &content_reader) {
  8252. ASSERT_TRUE(req.is_multipart_form_data());
  8253. std::vector<FormData> received;
  8254. content_reader(
  8255. [&](const FormData &file) {
  8256. received.push_back(file);
  8257. return true;
  8258. },
  8259. [&](const char *data, size_t data_length) {
  8260. received.back().content.append(data, data_length);
  8261. return true;
  8262. });
  8263. // '"', CR and LF in names and filenames are escaped following the
  8264. // WHATWG HTML standard, so each part still parses as a single part
  8265. // with no injected headers. Content types get CR/LF escaped too,
  8266. // while '"' (legal there, e.g. quoted charset) is preserved.
  8267. ASSERT_EQ(4U, received.size());
  8268. EXPECT_EQ("na%22me", received[0].name);
  8269. EXPECT_EQ("quoted name", received[0].content);
  8270. EXPECT_EQ("file", received[1].name);
  8271. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8272. received[1].filename);
  8273. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8274. EXPECT_EQ("injected", received[1].content);
  8275. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8276. EXPECT_EQ("my%22file.txt", received[2].filename);
  8277. EXPECT_EQ("cr lf name", received[2].content);
  8278. EXPECT_EQ("typed", received[3].name);
  8279. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8280. received[3].content_type);
  8281. EXPECT_EQ("typed content", received[3].content);
  8282. });
  8283. auto port = svr.bind_to_any_port("localhost");
  8284. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8285. auto se = detail::scope_exit([&] {
  8286. svr.stop();
  8287. t.join();
  8288. ASSERT_FALSE(svr.is_running());
  8289. });
  8290. svr.wait_until_ready();
  8291. Client cli("localhost", port);
  8292. UploadFormDataItems items = {
  8293. {"na\"me", "quoted name", "", ""},
  8294. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8295. "application/octet-stream"},
  8296. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8297. {"typed", "typed content", "",
  8298. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8299. };
  8300. auto res = cli.Post("/post", items);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. }
  8304. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8305. const UploadFormDataItems items = {
  8306. {"name1", "Content 1", "", ""},
  8307. {"name2", "Content 2", "file2.txt", "text/plain"},
  8308. };
  8309. Server svr;
  8310. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8311. const ContentReader &content_reader) {
  8312. ASSERT_TRUE(req.is_multipart_form_data());
  8313. std::vector<FormData> received;
  8314. content_reader(
  8315. [&](const FormData &file) {
  8316. received.push_back(file);
  8317. return true;
  8318. },
  8319. [&](const char *data, size_t data_length) {
  8320. received.back().content.append(data, data_length);
  8321. return true;
  8322. });
  8323. ASSERT_EQ(2U, received.size());
  8324. EXPECT_EQ("name1", received[0].name);
  8325. EXPECT_EQ("Content 1", received[0].content);
  8326. EXPECT_EQ("name2", received[1].name);
  8327. EXPECT_EQ("Content 2", received[1].content);
  8328. EXPECT_EQ("file2.txt", received[1].filename);
  8329. EXPECT_EQ("text/plain", received[1].content_type);
  8330. });
  8331. auto port = svr.bind_to_any_port("localhost");
  8332. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8333. auto se = detail::scope_exit([&] {
  8334. svr.stop();
  8335. t.join();
  8336. ASSERT_FALSE(svr.is_running());
  8337. });
  8338. svr.wait_until_ready();
  8339. Client cli("localhost", port);
  8340. // Whole-body serialization with a generated boundary
  8341. {
  8342. MultipartFormDataWriter writer;
  8343. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8344. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8345. writer.content_type());
  8346. auto body = writer.serialize(items);
  8347. EXPECT_EQ(body.size(), writer.content_length(items));
  8348. auto res = cli.Post("/post", body, writer.content_type());
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_EQ(StatusCode::OK_200, res->status);
  8351. }
  8352. // Per-part framing with a custom boundary via a content provider
  8353. {
  8354. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8355. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8356. MultipartFormDataWriter writer("custom-boundary_123");
  8357. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8358. std::string body;
  8359. for (const auto &item : items) {
  8360. body += writer.item_begin(item);
  8361. body += item.content;
  8362. body += MultipartFormDataWriter::item_end();
  8363. }
  8364. body += writer.finish();
  8365. EXPECT_EQ(body.size(), writer.content_length(items));
  8366. auto res = cli.Post(
  8367. "/post", body.size(),
  8368. [&](size_t offset, size_t length, DataSink &sink) {
  8369. sink.write(body.data() + offset, length);
  8370. return true;
  8371. },
  8372. writer.content_type());
  8373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8374. EXPECT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. }
  8377. TEST_F(ServerTest, PostContentReceiverGzip) {
  8378. cli_.set_compress(true);
  8379. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. ASSERT_EQ(StatusCode::OK_200, res->status);
  8382. ASSERT_EQ("content", res->body);
  8383. }
  8384. TEST_F(ServerTest, PutContentReceiver) {
  8385. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. ASSERT_EQ(StatusCode::OK_200, res->status);
  8388. ASSERT_EQ("content", res->body);
  8389. }
  8390. TEST_F(ServerTest, PatchContentReceiver) {
  8391. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8393. ASSERT_EQ(StatusCode::OK_200, res->status);
  8394. ASSERT_EQ("content", res->body);
  8395. }
  8396. template <typename ClientType>
  8397. void TestWithHeadersAndContentReceiver(
  8398. ClientType &cli,
  8399. std::function<Result(ClientType &, const std::string &, const Headers &,
  8400. const std::string &, const std::string &,
  8401. ContentReceiver, DownloadProgress)>
  8402. request_func) {
  8403. Headers headers;
  8404. headers.emplace("X-Custom-Header", "test-value");
  8405. std::string received_body;
  8406. auto res = request_func(
  8407. cli, "/content_receiver", headers, "content", "application/json",
  8408. [&](const char *data, size_t data_length) {
  8409. received_body.append(data, data_length);
  8410. return true;
  8411. },
  8412. nullptr);
  8413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. EXPECT_EQ("content", received_body);
  8416. }
  8417. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8418. #ifdef CPPHTTPLIB_SSL_ENABLED
  8419. using ClientT = SSLClient;
  8420. #else
  8421. using ClientT = Client;
  8422. #endif
  8423. TestWithHeadersAndContentReceiver<ClientT>(
  8424. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8425. const std::string &body, const std::string &content_type,
  8426. ContentReceiver receiver, DownloadProgress progress) {
  8427. return cli.Post(path, headers, body, content_type, receiver, progress);
  8428. });
  8429. }
  8430. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8431. #ifdef CPPHTTPLIB_SSL_ENABLED
  8432. using ClientT = SSLClient;
  8433. #else
  8434. using ClientT = Client;
  8435. #endif
  8436. TestWithHeadersAndContentReceiver<ClientT>(
  8437. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8438. const std::string &body, const std::string &content_type,
  8439. ContentReceiver receiver, DownloadProgress progress) {
  8440. return cli.Put(path, headers, body, content_type, receiver, progress);
  8441. });
  8442. }
  8443. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8444. #ifdef CPPHTTPLIB_SSL_ENABLED
  8445. using ClientT = SSLClient;
  8446. #else
  8447. using ClientT = Client;
  8448. #endif
  8449. TestWithHeadersAndContentReceiver<ClientT>(
  8450. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8451. const std::string &body, const std::string &content_type,
  8452. ContentReceiver receiver, DownloadProgress progress) {
  8453. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8454. });
  8455. }
  8456. template <typename ClientType>
  8457. void TestWithHeadersAndContentReceiverWithProgress(
  8458. ClientType &cli,
  8459. std::function<Result(ClientType &, const std::string &, const Headers &,
  8460. const std::string &, const std::string &,
  8461. ContentReceiver, DownloadProgress)>
  8462. request_func) {
  8463. Headers headers;
  8464. headers.emplace("X-Test-Header", "progress-test");
  8465. std::string received_body;
  8466. auto progress_called = false;
  8467. auto res = request_func(
  8468. cli, "/content_receiver", headers, "content", "text/plain",
  8469. [&](const char *data, size_t data_length) {
  8470. received_body.append(data, data_length);
  8471. return true;
  8472. },
  8473. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8474. progress_called = true;
  8475. return true;
  8476. });
  8477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8478. EXPECT_EQ(StatusCode::OK_200, res->status);
  8479. EXPECT_EQ("content", received_body);
  8480. EXPECT_TRUE(progress_called);
  8481. }
  8482. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8483. #ifdef CPPHTTPLIB_SSL_ENABLED
  8484. using ClientT = SSLClient;
  8485. #else
  8486. using ClientT = Client;
  8487. #endif
  8488. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8489. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8490. const std::string &body, const std::string &content_type,
  8491. ContentReceiver receiver, DownloadProgress progress) {
  8492. return cli.Post(path, headers, body, content_type, receiver, progress);
  8493. });
  8494. }
  8495. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8496. #ifdef CPPHTTPLIB_SSL_ENABLED
  8497. using ClientT = SSLClient;
  8498. #else
  8499. using ClientT = Client;
  8500. #endif
  8501. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8502. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8503. const std::string &body, const std::string &content_type,
  8504. ContentReceiver receiver, DownloadProgress progress) {
  8505. return cli.Put(path, headers, body, content_type, receiver, progress);
  8506. });
  8507. }
  8508. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8509. #ifdef CPPHTTPLIB_SSL_ENABLED
  8510. using ClientT = SSLClient;
  8511. #else
  8512. using ClientT = Client;
  8513. #endif
  8514. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8515. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8516. const std::string &body, const std::string &content_type,
  8517. ContentReceiver receiver, DownloadProgress progress) {
  8518. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8519. });
  8520. }
  8521. template <typename ClientType>
  8522. void TestWithHeadersAndContentReceiverError(
  8523. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8524. const Headers &, const std::string &,
  8525. const std::string &, ContentReceiver)>
  8526. request_func) {
  8527. Headers headers;
  8528. headers.emplace("X-Error-Test", "true");
  8529. std::string received_body;
  8530. auto receiver_failed = false;
  8531. auto res =
  8532. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8533. [&](const char *data, size_t data_length) {
  8534. received_body.append(data, data_length);
  8535. receiver_failed = true;
  8536. return false;
  8537. });
  8538. ASSERT_FALSE(res);
  8539. EXPECT_TRUE(receiver_failed);
  8540. }
  8541. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8542. #ifdef CPPHTTPLIB_SSL_ENABLED
  8543. using ClientT = SSLClient;
  8544. #else
  8545. using ClientT = Client;
  8546. #endif
  8547. TestWithHeadersAndContentReceiverError<ClientT>(
  8548. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8549. const std::string &body, const std::string &content_type,
  8550. ContentReceiver receiver) {
  8551. return cli.Post(path, headers, body, content_type, receiver);
  8552. });
  8553. }
  8554. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8555. #ifdef CPPHTTPLIB_SSL_ENABLED
  8556. using ClientT = SSLClient;
  8557. #else
  8558. using ClientT = Client;
  8559. #endif
  8560. TestWithHeadersAndContentReceiverError<ClientT>(
  8561. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8562. const std::string &body, const std::string &content_type,
  8563. ContentReceiver receiver) {
  8564. return cli.Put(path, headers, body, content_type, receiver);
  8565. });
  8566. }
  8567. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8568. #ifdef CPPHTTPLIB_SSL_ENABLED
  8569. using ClientT = SSLClient;
  8570. #else
  8571. using ClientT = Client;
  8572. #endif
  8573. TestWithHeadersAndContentReceiverError<ClientT>(
  8574. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8575. const std::string &body, const std::string &content_type,
  8576. ContentReceiver receiver) {
  8577. return cli.Patch(path, headers, body, content_type, receiver);
  8578. });
  8579. }
  8580. TEST_F(ServerTest, PostQueryStringAndBody) {
  8581. auto res =
  8582. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. ASSERT_EQ(StatusCode::OK_200, res->status);
  8585. }
  8586. TEST_F(ServerTest, HTTP2Magic) {
  8587. Request req;
  8588. req.method = "PRI";
  8589. req.path = "*";
  8590. req.body = "SM";
  8591. auto res = std::make_shared<Response>();
  8592. auto error = Error::Success;
  8593. auto ret = cli_.send(req, *res, error);
  8594. ASSERT_TRUE(ret);
  8595. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8596. }
  8597. TEST_F(ServerTest, KeepAlive) {
  8598. auto res = cli_.Get("/hi");
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::OK_200, res->status);
  8601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8602. EXPECT_EQ("Hello World!", res->body);
  8603. res = cli_.Get("/hi");
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(StatusCode::OK_200, res->status);
  8606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("Hello World!", res->body);
  8608. res = cli_.Get("/hi");
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(StatusCode::OK_200, res->status);
  8611. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8612. EXPECT_EQ("Hello World!", res->body);
  8613. res = cli_.Get("/not-exist");
  8614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8616. res = cli_.Post("/empty", "", "text/plain");
  8617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8618. EXPECT_EQ(StatusCode::OK_200, res->status);
  8619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8620. EXPECT_EQ("empty", res->body);
  8621. EXPECT_EQ("close", res->get_header_value("Connection"));
  8622. res = cli_.Post(
  8623. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8624. "text/plain");
  8625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8626. EXPECT_EQ(StatusCode::OK_200, res->status);
  8627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8628. EXPECT_EQ("empty", res->body);
  8629. cli_.set_keep_alive(false);
  8630. res = cli_.Get("/last-request");
  8631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8632. EXPECT_EQ(StatusCode::OK_200, res->status);
  8633. EXPECT_EQ("close", res->get_header_value("Connection"));
  8634. }
  8635. TEST_F(ServerTest, TooManyRedirect) {
  8636. cli_.set_follow_location(true);
  8637. auto res = cli_.Get("/redirect/0");
  8638. ASSERT_TRUE(!res);
  8639. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8640. }
  8641. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8642. Request req;
  8643. req.method = "FOOBAR";
  8644. req.path = "/hi";
  8645. cli_.set_keep_alive(true);
  8646. auto res = cli_.send(req);
  8647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8648. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8649. EXPECT_EQ("close", res->get_header_value("Connection"));
  8650. EXPECT_FALSE(cli_.is_socket_open());
  8651. }
  8652. TEST_F(ServerTest, CustomRouteReadsBody) {
  8653. const std::string xml =
  8654. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8655. Request req;
  8656. req.method = "PROPFIND";
  8657. req.path = "/dav/dir";
  8658. req.set_header("Depth", "1");
  8659. req.body = xml;
  8660. auto res = cli_.send(req);
  8661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8662. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8663. EXPECT_EQ(xml, res->body);
  8664. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8665. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8666. }
  8667. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8668. Request req;
  8669. req.method = "PROPFIND";
  8670. req.path = "/dav/42";
  8671. auto res = cli_.send(req);
  8672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8673. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8674. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8675. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8676. }
  8677. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8678. Request req;
  8679. req.method = "PROPFIND";
  8680. req.path = "/dav-re/123";
  8681. auto res = cli_.send(req);
  8682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8683. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8684. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8685. }
  8686. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8687. Request req;
  8688. req.method = "MKCOL";
  8689. req.path = "/dav-mkcol";
  8690. auto res = cli_.send(req);
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::Created_201, res->status);
  8693. }
  8694. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8695. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8696. Request req;
  8697. req.method = "REPORT";
  8698. req.path = "/dav-report";
  8699. req.body = xml;
  8700. auto res = cli_.send(req);
  8701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8702. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8703. EXPECT_EQ(xml, res->body);
  8704. }
  8705. // A content reader route must fire even when the request carries no body,
  8706. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8707. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8708. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8709. Request req;
  8710. req.method = "REPORT";
  8711. req.path = "/dav-report";
  8712. auto res = cli_.send(req);
  8713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8714. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8715. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8716. }
  8717. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8718. Request req;
  8719. req.method = "PROPFIND";
  8720. req.path = "/not-dav";
  8721. auto res = cli_.send(req);
  8722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8724. }
  8725. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8726. Request req;
  8727. req.method = "UNLOCK";
  8728. req.path = "/dav/dir";
  8729. cli_.set_keep_alive(true);
  8730. auto res = cli_.send(req);
  8731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8732. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8733. EXPECT_EQ("close", res->get_header_value("Connection"));
  8734. EXPECT_FALSE(cli_.is_socket_open());
  8735. }
  8736. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8737. // The mount point serves this path, but only for GET and HEAD.
  8738. auto get_res = cli_.Get("/dir/index.html");
  8739. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8740. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8741. Request req;
  8742. req.method = "PROPFIND";
  8743. req.path = "/dir/index.html";
  8744. auto res = cli_.send(req);
  8745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8746. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8747. }
  8748. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8749. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8750. cli_.set_keep_alive(true);
  8751. for (auto i = 0; i < 2; i++) {
  8752. Request req;
  8753. req.method = "PROPFIND";
  8754. req.path = "/dav/dir";
  8755. req.body = xml;
  8756. auto res = cli_.send(req);
  8757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8758. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8759. EXPECT_EQ(xml, res->body);
  8760. EXPECT_TRUE(cli_.is_socket_open());
  8761. }
  8762. // A built-in method must still be served on the same connection.
  8763. cli_.set_keep_alive(false);
  8764. auto res = cli_.Get("/hi");
  8765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8766. EXPECT_EQ(StatusCode::OK_200, res->status);
  8767. EXPECT_EQ("close", res->get_header_value("Connection"));
  8768. }
  8769. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8770. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8771. Request req;
  8772. req.method = "PROPFIND";
  8773. req.path = "/dav/dir";
  8774. req.set_header("Expect", "100-continue");
  8775. req.body = xml;
  8776. auto res = cli_.send(req);
  8777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8778. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8779. EXPECT_EQ(xml, res->body);
  8780. }
  8781. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8782. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8783. TEST_F(ServerTest, Gzip) {
  8784. Headers headers;
  8785. headers.emplace("Accept-Encoding", "gzip, deflate");
  8786. auto res = cli_.Get("/compress", headers);
  8787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8788. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8789. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8790. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8791. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8792. "7890123456789012345678901234567890",
  8793. res->body);
  8794. EXPECT_EQ(StatusCode::OK_200, res->status);
  8795. }
  8796. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8797. Headers headers;
  8798. headers.emplace("Accept-Encoding", "gzip, deflate");
  8799. auto res = cli_.Get("/compress-with-charset", headers);
  8800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8801. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8802. EXPECT_EQ("application/json; charset=utf-8",
  8803. res->get_header_value("Content-Type"));
  8804. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8805. "7890123456789012345678901234567890",
  8806. res->body);
  8807. EXPECT_EQ(StatusCode::OK_200, res->status);
  8808. }
  8809. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8810. Headers headers;
  8811. headers.emplace("Accept-Encoding", "");
  8812. auto res = cli_.Get("/compress", headers);
  8813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8814. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8816. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8817. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8818. "7890123456789012345678901234567890",
  8819. res->body);
  8820. EXPECT_EQ(StatusCode::OK_200, res->status);
  8821. }
  8822. TEST_F(ServerTest, GzipWithContentReceiver) {
  8823. Headers headers;
  8824. headers.emplace("Accept-Encoding", "gzip, deflate");
  8825. std::string body;
  8826. auto res =
  8827. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8828. EXPECT_EQ(100U, data_length);
  8829. body.append(data, data_length);
  8830. return true;
  8831. });
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8835. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8836. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8837. "7890123456789012345678901234567890",
  8838. body);
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. }
  8841. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8842. Headers headers;
  8843. headers.emplace("Accept-Encoding", "gzip, deflate");
  8844. cli_.set_decompress(false);
  8845. auto res = cli_.Get("/compress", headers);
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8849. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8850. EXPECT_EQ(33U, res->body.size());
  8851. EXPECT_EQ(StatusCode::OK_200, res->status);
  8852. }
  8853. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8854. Headers headers;
  8855. headers.emplace("Accept-Encoding", "");
  8856. std::string body;
  8857. auto res =
  8858. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8859. EXPECT_EQ(100U, data_length);
  8860. body.append(data, data_length);
  8861. return true;
  8862. });
  8863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8864. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8866. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8867. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8868. "7890123456789012345678901234567890",
  8869. body);
  8870. EXPECT_EQ(StatusCode::OK_200, res->status);
  8871. }
  8872. TEST_F(ServerTest, NoGzip) {
  8873. Headers headers;
  8874. headers.emplace("Accept-Encoding", "gzip, deflate");
  8875. auto res = cli_.Get("/nocompress", headers);
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8878. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8879. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8880. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8881. "7890123456789012345678901234567890",
  8882. res->body);
  8883. EXPECT_EQ(StatusCode::OK_200, res->status);
  8884. }
  8885. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8886. Headers headers;
  8887. headers.emplace("Accept-Encoding", "gzip, deflate");
  8888. std::string body;
  8889. auto res = cli_.Get("/nocompress", headers,
  8890. [&](const char *data, size_t data_length) {
  8891. EXPECT_EQ(100U, data_length);
  8892. body.append(data, data_length);
  8893. return true;
  8894. });
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8897. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8898. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8899. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8900. "7890123456789012345678901234567890",
  8901. body);
  8902. EXPECT_EQ(StatusCode::OK_200, res->status);
  8903. }
  8904. TEST_F(ServerTest, MultipartFormDataGzip) {
  8905. UploadFormDataItems items = {
  8906. {"key1", "test", "", ""},
  8907. {"key2", "--abcdefg123", "", ""},
  8908. };
  8909. cli_.set_compress(true);
  8910. auto res = cli_.Post("/compress-multipart", items);
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. #endif
  8915. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8916. // Static file compression is opt-in, so these run their own server rather than
  8917. // flipping it on for the shared ServerTest fixture, which would silently
  8918. // rewrite what every other static file test is asserting.
  8919. class StaticFileCompressionTest : public ::testing::Test {
  8920. protected:
  8921. void TearDown() override {
  8922. if (t_.joinable()) {
  8923. svr_.stop();
  8924. t_.join();
  8925. }
  8926. }
  8927. int start(const std::function<void(Server &)> &configure = nullptr) {
  8928. // Serves the same tree as a directory of build-time compressed assets
  8929. // would be served: the mount point names the coding the files are already
  8930. // stored in. Registered before "/" so it is the one that matches.
  8931. svr_.set_mount_point("/pre-encoded", "./www",
  8932. {{"Content-Encoding", "gzip"}});
  8933. svr_.set_mount_point("/", "./www");
  8934. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8935. res.set_file_content("./www/dir/index.html", "text/html");
  8936. });
  8937. svr_.Get("/pre-encoded-file-content",
  8938. [](const Request & /*req*/, Response &res) {
  8939. res.set_header("Content-Encoding", "gzip");
  8940. res.set_file_content("./www/dir/index.html", "text/html");
  8941. });
  8942. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8943. res.set_content_provider(
  8944. 6, "text/plain",
  8945. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8946. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8947. return true;
  8948. });
  8949. });
  8950. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8951. res.set_content_provider(
  8952. 1000, "text/plain",
  8953. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8954. if (offset < 100) {
  8955. std::string data(100, 'A');
  8956. sink.write(data.data(), data.size());
  8957. return true;
  8958. }
  8959. std::this_thread::sleep_for(std::chrono::seconds(2));
  8960. std::string data(900, 'B');
  8961. sink.write(data.data(), data.size());
  8962. return true;
  8963. });
  8964. });
  8965. if (configure) { configure(svr_); }
  8966. auto port = svr_.bind_to_any_port(HOST);
  8967. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8968. svr_.wait_until_ready();
  8969. return port;
  8970. }
  8971. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8972. // Every file under ./www except 1MB.txt is smaller than the default
  8973. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8974. // it out of the way.
  8975. static void enable_without_floor(Server &svr) {
  8976. svr.set_static_file_compression(true);
  8977. svr.set_static_file_compression_min_length(0);
  8978. }
  8979. Server svr_;
  8980. std::thread t_;
  8981. };
  8982. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8983. auto port = start();
  8984. Client cli(HOST, port);
  8985. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_EQ(StatusCode::OK_200, res->status);
  8988. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8989. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8990. EXPECT_EQ(1048576U, res->body.size());
  8991. }
  8992. TEST_F(StaticFileCompressionTest, MountPoint) {
  8993. auto port = start(enable);
  8994. Client cli(HOST, port);
  8995. cli.set_decompress(false);
  8996. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8998. EXPECT_EQ(StatusCode::OK_200, res->status);
  8999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9000. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9001. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9002. // The response stays self-delimiting: a length, not a chunked body.
  9003. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9004. EXPECT_EQ(std::to_string(res->body.size()),
  9005. res->get_header_value("Content-Length"));
  9006. EXPECT_LT(res->body.size(), 1048576U);
  9007. EXPECT_FALSE(res->body.empty());
  9008. }
  9009. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9010. auto port = start(enable);
  9011. Client cli(HOST, port);
  9012. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9014. EXPECT_EQ(StatusCode::OK_200, res->status);
  9015. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9016. EXPECT_EQ(1048576U, res->body.size());
  9017. }
  9018. TEST_F(StaticFileCompressionTest, FileContent) {
  9019. auto port = start(enable_without_floor);
  9020. Client cli(HOST, port);
  9021. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9023. EXPECT_EQ(StatusCode::OK_200, res->status);
  9024. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9025. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9026. EXPECT_EQ(104U, res->body.size());
  9027. }
  9028. // A handler that serves an already-encoded file names the coding itself. The
  9029. // file-backed path decided its coding from Accept-Encoding and the content
  9030. // type alone, so it compressed the stored bytes a second time and appended a
  9031. // second Content-Encoding field line.
  9032. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9033. auto port = start(enable_without_floor);
  9034. Client cli(HOST, port);
  9035. cli.set_decompress(false);
  9036. auto res = cli.Get("/pre-encoded-file-content",
  9037. Headers{{"Accept-Encoding", "gzip"}});
  9038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9039. EXPECT_EQ(StatusCode::OK_200, res->status);
  9040. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9041. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9042. // Vary belongs to a coding the server chose, and it chose none here.
  9043. EXPECT_FALSE(res->has_header("Vary"));
  9044. // The file travels exactly as it is stored on disk.
  9045. EXPECT_EQ(104U, res->body.size());
  9046. }
  9047. // The 1MB file clears the default floor, so this one runs the configuration a
  9048. // deployment would actually have.
  9049. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9050. auto port = start(enable);
  9051. Client cli(HOST, port);
  9052. cli.set_decompress(false);
  9053. auto res =
  9054. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9058. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9059. EXPECT_FALSE(res->has_header("Vary"));
  9060. EXPECT_EQ(1048576U, res->body.size());
  9061. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9062. }
  9063. TEST_F(StaticFileCompressionTest, Head) {
  9064. auto port = start(enable);
  9065. Client cli(HOST, port);
  9066. cli.set_decompress(false);
  9067. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9068. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9069. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::OK_200, res->status);
  9072. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9073. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9074. // HEAD still reports the size a GET would return.
  9075. EXPECT_EQ(get->get_header_value("Content-Length"),
  9076. res->get_header_value("Content-Length"));
  9077. EXPECT_TRUE(res->body.empty());
  9078. }
  9079. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9080. auto port = start(enable);
  9081. Client cli(HOST, port);
  9082. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9083. {"Accept-Encoding", "gzip"}});
  9084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9086. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9087. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9088. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9089. EXPECT_EQ("cd", res->body);
  9090. }
  9091. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9092. auto port = start(enable);
  9093. Client cli(HOST, port);
  9094. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9096. EXPECT_EQ(StatusCode::OK_200, res->status);
  9097. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9098. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9099. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9100. }
  9101. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9102. auto port = start(enable);
  9103. Client cli(HOST, port);
  9104. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9106. EXPECT_EQ(StatusCode::OK_200, res->status);
  9107. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9108. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9109. EXPECT_TRUE(res->body.empty());
  9110. }
  9111. TEST_F(StaticFileCompressionTest, MinLength) {
  9112. auto port = start(enable);
  9113. Client cli(HOST, port);
  9114. // 104 bytes, well under the default floor. Compressing it would add the
  9115. // gzip header and trailer to a body that already fits in one packet.
  9116. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9118. EXPECT_EQ(StatusCode::OK_200, res->status);
  9119. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9120. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9121. }
  9122. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9123. auto port = start([](Server &svr) {
  9124. svr.set_static_file_compression(true);
  9125. svr.set_static_file_compression_min_length(1);
  9126. });
  9127. Client cli(HOST, port);
  9128. cli.set_decompress(false);
  9129. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9131. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9132. // A 9-byte file comes back larger than it went in, because gzip's header and
  9133. // trailer outweigh anything deflate can save. That is the end of the range
  9134. // the floor exists to keep out.
  9135. EXPECT_GT(res->body.size(), 9U);
  9136. }
  9137. TEST_F(StaticFileCompressionTest, MaxLength) {
  9138. auto port = start([](Server &svr) {
  9139. svr.set_static_file_compression(true);
  9140. svr.set_static_file_compression_min_length(0);
  9141. svr.set_static_file_compression_max_length(1024);
  9142. });
  9143. Client cli(HOST, port);
  9144. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9145. // defines `small` as a macro on Windows.
  9146. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9147. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9148. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9149. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9150. // Under it: compressed.
  9151. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9152. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9153. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9154. }
  9155. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9156. auto port = start(enable_without_floor);
  9157. Client cli(HOST, port);
  9158. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9159. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9160. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9161. auto identity_etag = identity->get_header_value("ETag");
  9162. ASSERT_FALSE(identity_etag.empty());
  9163. auto gzipped =
  9164. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9165. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9166. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9167. auto gzip_etag = gzipped->get_header_value("ETag");
  9168. ASSERT_FALSE(gzip_etag.empty());
  9169. // Two representations, two validators.
  9170. EXPECT_NE(identity_etag, gzip_etag);
  9171. // Each one revalidates against the request that would produce it...
  9172. auto fresh =
  9173. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9174. {"If-None-Match", gzip_etag}});
  9175. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9176. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9177. auto fresh_identity =
  9178. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9179. {"If-None-Match", identity_etag}});
  9180. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9181. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9182. // ...and not against the other representation.
  9183. auto crossed =
  9184. cli.Get("/dir/index.html",
  9185. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9186. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9187. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9188. }
  9189. // The opt-in covers responses the server reads off disk itself. A caller's own
  9190. // known-length provider keeps its Content-Length and, more importantly, keeps
  9191. // delivering incrementally: routing it through a compressor would hold every
  9192. // write back until zlib's window filled.
  9193. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9194. auto port = start(enable);
  9195. Client cli(HOST, port);
  9196. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9198. EXPECT_EQ(StatusCode::OK_200, res->status);
  9199. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9200. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9201. EXPECT_EQ("aaabbb", res->body);
  9202. }
  9203. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9204. auto port = start(enable);
  9205. Client cli(HOST, port);
  9206. cli.set_read_timeout(1, 0);
  9207. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9208. Headers{{"Accept-Encoding", "gzip"}});
  9209. ASSERT_TRUE(handle.is_valid());
  9210. // The provider writes 100 bytes and then stalls for longer than the read
  9211. // timeout. Those first bytes have to arrive anyway: run the response through
  9212. // a compressor and zlib holds them until its window fills, so the read would
  9213. // come back empty instead.
  9214. char buf[256];
  9215. auto n = handle.read(buf, sizeof(buf));
  9216. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9217. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9218. }
  9219. #endif
  9220. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9221. TEST_F(ServerTest, Brotli) {
  9222. Headers headers;
  9223. headers.emplace("Accept-Encoding", "br");
  9224. auto res = cli_.Get("/compress", headers);
  9225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9226. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9228. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9229. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9230. "7890123456789012345678901234567890",
  9231. res->body);
  9232. EXPECT_EQ(StatusCode::OK_200, res->status);
  9233. }
  9234. #endif
  9235. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9236. TEST_F(ServerTest, Zstd) {
  9237. Headers headers;
  9238. headers.emplace("Accept-Encoding", "zstd");
  9239. auto res = cli_.Get("/compress", headers);
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9242. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9243. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9244. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9245. "7890123456789012345678901234567890",
  9246. res->body);
  9247. EXPECT_EQ(StatusCode::OK_200, res->status);
  9248. }
  9249. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9250. Headers headers;
  9251. headers.emplace("Accept-Encoding", "");
  9252. auto res = cli_.Get("/compress", headers);
  9253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9254. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9256. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9257. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9258. "7890123456789012345678901234567890",
  9259. res->body);
  9260. EXPECT_EQ(StatusCode::OK_200, res->status);
  9261. }
  9262. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9263. Headers headers;
  9264. headers.emplace("Accept-Encoding", "zstd");
  9265. std::string body;
  9266. auto res =
  9267. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9268. EXPECT_EQ(100U, data_length);
  9269. body.append(data, data_length);
  9270. return true;
  9271. });
  9272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9273. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9274. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9275. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9276. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9277. "7890123456789012345678901234567890",
  9278. body);
  9279. EXPECT_EQ(StatusCode::OK_200, res->status);
  9280. }
  9281. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9282. Headers headers;
  9283. headers.emplace("Accept-Encoding", "zstd");
  9284. cli_.set_decompress(false);
  9285. auto res = cli_.Get("/compress", headers);
  9286. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9287. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9288. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9289. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9291. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9293. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9294. EXPECT_EQ(StatusCode::OK_200, res->status);
  9295. ASSERT_EQ(26U, res->body.size());
  9296. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9297. 0);
  9298. }
  9299. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9300. Headers headers;
  9301. headers.emplace("Accept-Encoding", "");
  9302. std::string body;
  9303. auto res =
  9304. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9305. EXPECT_EQ(100U, data_length);
  9306. body.append(data, data_length);
  9307. return true;
  9308. });
  9309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9310. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9312. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9313. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9314. "7890123456789012345678901234567890",
  9315. body);
  9316. EXPECT_EQ(StatusCode::OK_200, res->status);
  9317. }
  9318. TEST_F(ServerTest, NoZstd) {
  9319. Headers headers;
  9320. headers.emplace("Accept-Encoding", "zstd");
  9321. auto res = cli_.Get("/nocompress", headers);
  9322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9323. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9324. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9325. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9326. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9327. "7890123456789012345678901234567890",
  9328. res->body);
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. }
  9331. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9332. Headers headers;
  9333. headers.emplace("Accept-Encoding", "zstd");
  9334. std::string body;
  9335. auto res = cli_.Get("/nocompress", headers,
  9336. [&](const char *data, size_t data_length) {
  9337. EXPECT_EQ(100U, data_length);
  9338. body.append(data, data_length);
  9339. return true;
  9340. });
  9341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9342. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9343. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9344. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9345. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9346. "7890123456789012345678901234567890",
  9347. body);
  9348. EXPECT_EQ(StatusCode::OK_200, res->status);
  9349. }
  9350. // TODO: How to enable zstd ??
  9351. TEST_F(ServerTest, MultipartFormDataZstd) {
  9352. UploadFormDataItems items = {
  9353. {"key1", "test", "", ""},
  9354. {"key2", "--abcdefg123", "", ""},
  9355. };
  9356. Headers headers;
  9357. headers.emplace("Accept-Encoding", "zstd");
  9358. cli_.set_compress(true);
  9359. auto res = cli_.Post("/compress-multipart", headers, items);
  9360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9361. EXPECT_EQ(StatusCode::OK_200, res->status);
  9362. }
  9363. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9364. Headers headers;
  9365. headers.emplace("Accept-Encoding", "zstd");
  9366. cli_.set_compress(true);
  9367. auto res = cli_.Put(
  9368. "/put", headers, 3,
  9369. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9370. sink.os << "PUT";
  9371. return true;
  9372. },
  9373. "text/plain");
  9374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9375. EXPECT_EQ(StatusCode::OK_200, res->status);
  9376. EXPECT_EQ("PUT", res->body);
  9377. }
  9378. // Pre-compression logging tests
  9379. TEST_F(ServerTest, PreCompressionLogging) {
  9380. // Test data for compression (matches the actual /compress endpoint content)
  9381. const std::string test_content =
  9382. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9383. "3456789012345678901234567890";
  9384. // Variables to capture logging data
  9385. std::string pre_compression_body;
  9386. std::string pre_compression_content_type;
  9387. std::string pre_compression_content_encoding;
  9388. std::string post_compression_body;
  9389. std::string post_compression_content_type;
  9390. std::string post_compression_content_encoding;
  9391. // Set up pre-compression logger
  9392. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9393. const Response &res) {
  9394. pre_compression_body = res.body;
  9395. pre_compression_content_type = res.get_header_value("Content-Type");
  9396. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9397. });
  9398. // Set up post-compression logger
  9399. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9400. post_compression_body = res.body;
  9401. post_compression_content_type = res.get_header_value("Content-Type");
  9402. post_compression_content_encoding =
  9403. res.get_header_value("Content-Encoding");
  9404. });
  9405. // Test with gzip compression
  9406. Headers headers;
  9407. headers.emplace("Accept-Encoding", "gzip");
  9408. auto res = cli_.Get("/compress", headers);
  9409. // Verify response was compressed
  9410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9411. EXPECT_EQ(StatusCode::OK_200, res->status);
  9412. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9413. // Verify pre-compression logger captured uncompressed content
  9414. EXPECT_EQ(test_content, pre_compression_body);
  9415. EXPECT_EQ("text/plain", pre_compression_content_type);
  9416. EXPECT_TRUE(pre_compression_content_encoding
  9417. .empty()); // No encoding header before compression
  9418. // Verify post-compression logger captured compressed content
  9419. EXPECT_NE(test_content,
  9420. post_compression_body); // Should be different after compression
  9421. EXPECT_EQ("text/plain", post_compression_content_type);
  9422. EXPECT_EQ("gzip", post_compression_content_encoding);
  9423. // Verify compressed content is smaller
  9424. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9425. }
  9426. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9427. const std::string test_content =
  9428. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9429. "3456789012345678901234567890";
  9430. std::string pre_compression_body;
  9431. std::string post_compression_body;
  9432. svr_.set_pre_compression_logger(
  9433. [&](const Request & /*req*/, const Response &res) {
  9434. pre_compression_body = res.body;
  9435. });
  9436. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9437. post_compression_body = res.body;
  9438. });
  9439. Headers headers;
  9440. headers.emplace("Accept-Encoding", "br");
  9441. auto res = cli_.Get("/compress", headers);
  9442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9443. EXPECT_EQ(StatusCode::OK_200, res->status);
  9444. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9445. // Verify pre-compression content is uncompressed
  9446. EXPECT_EQ(test_content, pre_compression_body);
  9447. // Verify post-compression content is compressed
  9448. EXPECT_NE(test_content, post_compression_body);
  9449. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9450. }
  9451. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9452. const std::string test_content =
  9453. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9454. "3456789012345678901234567890";
  9455. std::string pre_compression_body;
  9456. std::string post_compression_body;
  9457. svr_.set_pre_compression_logger(
  9458. [&](const Request & /*req*/, const Response &res) {
  9459. pre_compression_body = res.body;
  9460. });
  9461. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9462. post_compression_body = res.body;
  9463. });
  9464. // Request without compression (use /nocompress endpoint)
  9465. Headers headers;
  9466. auto res = cli_.Get("/nocompress", headers);
  9467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9468. EXPECT_EQ(StatusCode::OK_200, res->status);
  9469. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9470. // Pre-compression logger should not be called when no compression is applied
  9471. EXPECT_TRUE(
  9472. pre_compression_body.empty()); // Pre-compression logger not called
  9473. EXPECT_EQ(
  9474. test_content,
  9475. post_compression_body); // Post-compression logger captures final content
  9476. }
  9477. TEST_F(ServerTest, LoggerSeesContentLength) {
  9478. size_t logged_content_length = 0;
  9479. std::string logged_content_length_header;
  9480. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9481. logged_content_length = res.content_length_;
  9482. logged_content_length_header = res.get_header_value("Content-Length");
  9483. });
  9484. auto res = cli_.Get("/nocompress");
  9485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9486. EXPECT_EQ(StatusCode::OK_200, res->status);
  9487. EXPECT_EQ(res->body.size(), logged_content_length);
  9488. EXPECT_EQ(std::to_string(logged_content_length),
  9489. logged_content_length_header);
  9490. }
  9491. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9492. const std::string test_content =
  9493. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9494. "3456789012345678901234567890";
  9495. std::string pre_compression_body;
  9496. bool pre_logger_called = false;
  9497. // Set only pre-compression logger
  9498. svr_.set_pre_compression_logger(
  9499. [&](const Request & /*req*/, const Response &res) {
  9500. pre_compression_body = res.body;
  9501. pre_logger_called = true;
  9502. });
  9503. Headers headers;
  9504. headers.emplace("Accept-Encoding", "gzip");
  9505. auto res = cli_.Get("/compress", headers);
  9506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9507. EXPECT_EQ(StatusCode::OK_200, res->status);
  9508. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9509. // Verify pre-compression logger was called
  9510. EXPECT_TRUE(pre_logger_called);
  9511. EXPECT_EQ(test_content, pre_compression_body);
  9512. }
  9513. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9514. {
  9515. // Test with Expect: 100-continue header - success case
  9516. // Server returns 100 Continue, client sends body, server returns 200 OK
  9517. Request req;
  9518. req.method = "POST";
  9519. req.path = "/post-large";
  9520. req.set_header("Expect", "100-continue");
  9521. req.body = LARGE_DATA;
  9522. Response res;
  9523. auto error = Error::Success;
  9524. cli_.set_keep_alive(true);
  9525. auto ret = cli_.send(req, res, error);
  9526. EXPECT_TRUE(ret);
  9527. EXPECT_EQ(StatusCode::OK_200, res.status);
  9528. EXPECT_EQ(LARGE_DATA, res.body);
  9529. }
  9530. {
  9531. // Test with Expect: 100-continue header - error case
  9532. // Client should not send the body when server returns an error
  9533. Request req;
  9534. req.method = "POST";
  9535. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9536. req.set_header("Expect", "100-continue");
  9537. req.body = LARGE_DATA;
  9538. Response res;
  9539. auto error = Error::Success;
  9540. auto start = std::chrono::high_resolution_clock::now();
  9541. cli_.set_keep_alive(true);
  9542. auto ret = cli_.send(req, res, error);
  9543. auto end = std::chrono::high_resolution_clock::now();
  9544. auto elapsed =
  9545. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9546. .count();
  9547. // With Expect: 100-continue, request completes successfully but with error
  9548. EXPECT_TRUE(ret);
  9549. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9550. EXPECT_EQ("close", res.get_header_value("Connection"));
  9551. EXPECT_FALSE(cli_.is_socket_open());
  9552. EXPECT_LE(elapsed, 2000);
  9553. }
  9554. {
  9555. // Send an extra GET request to ensure error recovery without hanging
  9556. Request req;
  9557. req.method = "GET";
  9558. req.path = "/hi";
  9559. auto start = std::chrono::high_resolution_clock::now();
  9560. auto res = cli_.send(req);
  9561. auto end = std::chrono::high_resolution_clock::now();
  9562. auto elapsed =
  9563. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9564. .count();
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. EXPECT_EQ(StatusCode::OK_200, res->status);
  9567. EXPECT_EQ("Hello World!", res->body);
  9568. EXPECT_LE(elapsed, 500);
  9569. }
  9570. }
  9571. TEST(ZstdDecompressor, ChunkedDecompression) {
  9572. std::string data;
  9573. for (size_t i = 0; i < 32 * 1024; ++i) {
  9574. data.push_back(static_cast<char>('a' + i % 26));
  9575. }
  9576. std::string compressed_data;
  9577. {
  9578. httplib::detail::zstd_compressor compressor;
  9579. bool result = compressor.compress(
  9580. data.data(), data.size(),
  9581. /*last=*/true,
  9582. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9583. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9584. compressed_data_size);
  9585. return true;
  9586. });
  9587. ASSERT_TRUE(result);
  9588. }
  9589. std::string decompressed_data;
  9590. {
  9591. httplib::detail::zstd_decompressor decompressor;
  9592. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9593. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9594. size_t chunk_size = 130;
  9595. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9596. chunk_begin += chunk_size) {
  9597. size_t current_chunk_size =
  9598. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9599. bool result = decompressor.decompress(
  9600. compressed_data.data() + chunk_begin, current_chunk_size,
  9601. [&](const char *decompressed_data_chunk,
  9602. size_t decompressed_data_chunk_size) {
  9603. decompressed_data.insert(decompressed_data.size(),
  9604. decompressed_data_chunk,
  9605. decompressed_data_chunk_size);
  9606. return true;
  9607. });
  9608. ASSERT_TRUE(result);
  9609. }
  9610. }
  9611. ASSERT_EQ(data, decompressed_data);
  9612. }
  9613. TEST(ZstdDecompressor, Decompress) {
  9614. std::string original_text = "Compressed with ZSTD";
  9615. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9616. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9617. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9618. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9619. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9620. std::string decompressed_data;
  9621. {
  9622. httplib::detail::zstd_decompressor decompressor;
  9623. bool result = decompressor.decompress(
  9624. compressed_data.data(), compressed_data.size(),
  9625. [&](const char *decompressed_data_chunk,
  9626. size_t decompressed_data_chunk_size) {
  9627. decompressed_data.insert(decompressed_data.size(),
  9628. decompressed_data_chunk,
  9629. decompressed_data_chunk_size);
  9630. return true;
  9631. });
  9632. ASSERT_TRUE(result);
  9633. }
  9634. ASSERT_EQ(original_text, decompressed_data);
  9635. }
  9636. #endif
  9637. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9638. // separate chunks so that the server sees each part in its own read(). Used to
  9639. // place a read boundary at a specific offset of a request body.
  9640. static bool send_request_in_parts(time_t read_timeout_sec,
  9641. const std::vector<std::string> &parts,
  9642. std::string *resp = nullptr,
  9643. int port = PORT) {
  9644. auto error = Error::Success;
  9645. auto client_sock = detail::create_client_socket(
  9646. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9647. /*connection_timeout_sec=*/5, 0,
  9648. /*read_timeout_sec=*/5, 0,
  9649. /*write_timeout_sec=*/5, 0, std::string(), error);
  9650. if (client_sock == INVALID_SOCKET) { return false; }
  9651. auto ret = detail::process_client_socket(
  9652. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9653. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9654. for (size_t i = 0; i < parts.size(); i++) {
  9655. const auto &part = parts[i];
  9656. if (part.size() !=
  9657. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9658. return false;
  9659. }
  9660. if (i + 1 < parts.size()) {
  9661. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9662. }
  9663. }
  9664. char buf[512];
  9665. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9666. while (line_reader.getline()) {
  9667. if (resp) { *resp += line_reader.ptr(); }
  9668. }
  9669. return true;
  9670. });
  9671. detail::close_socket(client_sock);
  9672. return ret;
  9673. }
  9674. // Sends a raw request to a server listening at HOST:PORT.
  9675. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9676. std::string *resp = nullptr, int port = PORT) {
  9677. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9678. }
  9679. #ifdef CPPHTTPLIB_SSL_ENABLED
  9680. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9682. ASSERT_TRUE(svr.is_valid());
  9683. svr.set_read_timeout(1, 0);
  9684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9685. auto se = detail::scope_exit([&] {
  9686. svr.stop();
  9687. t.join();
  9688. ASSERT_FALSE(svr.is_running());
  9689. });
  9690. svr.wait_until_ready();
  9691. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9692. // keeps each wait well within the read timeout. The server gives up a
  9693. // second in, so the bytes sent after that fail.
  9694. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9695. parts.resize(26, std::string(1, '\0'));
  9696. EXPECT_FALSE(send_request_in_parts(5, parts));
  9697. }
  9698. #endif
  9699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9700. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9701. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9702. const std::vector<std::string> &parts,
  9703. std::string *resp = nullptr,
  9704. int port = PORT) {
  9705. auto error = Error::Success;
  9706. auto sock = detail::create_client_socket(
  9707. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9708. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9709. /*write_timeout_sec=*/5, 0, std::string(), error);
  9710. if (sock == INVALID_SOCKET) { return false; }
  9711. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9712. auto ctx = SSL_CTX_new(TLS_client_method());
  9713. auto ssl = SSL_new(ctx);
  9714. auto ssl_se = detail::scope_exit([&] {
  9715. SSL_free(ssl);
  9716. SSL_CTX_free(ctx);
  9717. });
  9718. SSL_set_fd(ssl, static_cast<int>(sock));
  9719. if (SSL_connect(ssl) != 1) { return false; }
  9720. for (size_t i = 0; i < parts.size(); i++) {
  9721. const auto &part = parts[i];
  9722. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9723. static_cast<int>(part.size())) {
  9724. return false;
  9725. }
  9726. if (i + 1 < parts.size()) {
  9727. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9728. }
  9729. }
  9730. char buf[512];
  9731. int n;
  9732. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9733. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9734. }
  9735. return true;
  9736. }
  9737. #endif
  9738. // The request line, then a header value a byte at a time.
  9739. static std::vector<std::string> slow_request_head_parts() {
  9740. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9741. parts.resize(26, "a");
  9742. parts.emplace_back("\r\n\r\n");
  9743. return parts;
  9744. }
  9745. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9746. // within the one-second read timeout. The server gives up a second in, before
  9747. // the head is complete.
  9748. static void
  9749. expect_slow_request_head_dropped(Server &svr,
  9750. const std::function<std::string()> &send) {
  9751. std::atomic<bool> handled(false);
  9752. svr.Get("/", [&](const Request &, Response &res) {
  9753. handled = true;
  9754. res.set_content("ok", "text/plain");
  9755. });
  9756. svr.set_read_timeout(1, 0);
  9757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9758. auto se = detail::scope_exit([&] {
  9759. svr.stop();
  9760. t.join();
  9761. ASSERT_FALSE(svr.is_running());
  9762. });
  9763. svr.wait_until_ready();
  9764. auto resp = send();
  9765. EXPECT_FALSE(handled);
  9766. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9767. }
  9768. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9769. Server svr;
  9770. expect_slow_request_head_dropped(svr, [] {
  9771. std::string resp;
  9772. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9773. return resp;
  9774. });
  9775. }
  9776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9777. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9779. ASSERT_TRUE(svr.is_valid());
  9780. expect_slow_request_head_dropped(svr, [] {
  9781. std::string resp;
  9782. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9783. return resp;
  9784. });
  9785. }
  9786. #endif
  9787. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9788. Server svr;
  9789. std::string header_value;
  9790. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9791. header_value = req.get_header_value("foo");
  9792. res.set_content("ok", "text/plain");
  9793. });
  9794. thread t = thread([&] { svr.listen(HOST, PORT); });
  9795. auto se = detail::scope_exit([&] {
  9796. svr.stop();
  9797. t.join();
  9798. ASSERT_FALSE(svr.is_running());
  9799. });
  9800. svr.wait_until_ready();
  9801. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9802. // like characters are not treated the same - use vertical tab and escape.
  9803. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9804. "foo: \t \v bar \x1B\t \r\n"
  9805. "Connection: close\r\n"
  9806. "\r\n";
  9807. std::string res;
  9808. ASSERT_TRUE(send_request(5, req, &res));
  9809. EXPECT_EQ(header_value, "");
  9810. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9811. }
  9812. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9813. Server svr;
  9814. std::string received;
  9815. svr.Get("/order", [&](const Request &req, Response &res) {
  9816. received = entries_to_string(req.headers);
  9817. res.set_content("ok", "text/plain");
  9818. });
  9819. auto port = svr.bind_to_any_port(HOST);
  9820. thread t = thread([&] { svr.listen_after_bind(); });
  9821. auto se = detail::scope_exit([&] {
  9822. svr.stop();
  9823. t.join();
  9824. ASSERT_FALSE(svr.is_running());
  9825. });
  9826. svr.wait_until_ready();
  9827. const std::string req = "GET /order HTTP/1.1\r\n"
  9828. "Host: localhost\r\n"
  9829. "X-First: 1\r\n"
  9830. "X-Dup: a\r\n"
  9831. "X-Second: 2\r\n"
  9832. "X-Dup: b\r\n"
  9833. "Connection: close\r\n"
  9834. "\r\n";
  9835. std::string res;
  9836. ASSERT_TRUE(send_request(5, req, &res, port));
  9837. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9838. EXPECT_EQ(
  9839. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9840. received);
  9841. }
  9842. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9843. Server svr;
  9844. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9845. res.set_header("Set-Cookie", "first=1");
  9846. res.set_header("X-Between", "y");
  9847. res.set_header("Set-Cookie", "second=2");
  9848. res.set_content("ok", "text/plain");
  9849. });
  9850. auto port = svr.bind_to_any_port(HOST);
  9851. thread t = thread([&] { svr.listen_after_bind(); });
  9852. auto se = detail::scope_exit([&] {
  9853. svr.stop();
  9854. t.join();
  9855. ASSERT_FALSE(svr.is_running());
  9856. });
  9857. svr.wait_until_ready();
  9858. Client cli(HOST, port);
  9859. auto res = cli.Get("/cookies");
  9860. ASSERT_TRUE(res);
  9861. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9862. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9863. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9864. }
  9865. // A stream may send a byte at a time with a small extension on each chunk,
  9866. // however long it runs
  9867. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9868. Server svr;
  9869. svr.Post("/count", [](const Request &req, Response &res) {
  9870. res.set_content(std::to_string(req.body.size()), "text/plain");
  9871. });
  9872. auto port = svr.bind_to_any_port(HOST);
  9873. ASSERT_LT(0, port);
  9874. thread t = thread([&] { svr.listen_after_bind(); });
  9875. auto se = detail::scope_exit([&] {
  9876. svr.stop();
  9877. t.join();
  9878. ASSERT_FALSE(svr.is_running());
  9879. });
  9880. svr.wait_until_ready();
  9881. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9882. "\r\nTransfer-Encoding: chunked\r\n"
  9883. "Connection: close\r\n\r\n";
  9884. for (auto i = 0; i < 4096; i++) {
  9885. req += "1;a=b\r\nx\r\n";
  9886. }
  9887. req += "0\r\n\r\n";
  9888. std::string res;
  9889. ASSERT_TRUE(send_request(5, req, &res, port));
  9890. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9891. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9892. }
  9893. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9894. Server svr;
  9895. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9896. auto i = new int(0);
  9897. res.set_header("Trailer", "X-Safe, X-Reflected");
  9898. res.set_chunked_content_provider(
  9899. "text/plain",
  9900. [i](size_t /*offset*/, DataSink &sink) {
  9901. if (*i == 0) {
  9902. sink.os << "body";
  9903. } else {
  9904. Headers trailer;
  9905. // A valid trailer that must survive.
  9906. trailer.emplace("X-Safe", "safe");
  9907. // Attacker-controlled value carrying CR/LF (response splitting).
  9908. trailer.emplace("X-Reflected",
  9909. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9910. // Attacker-controlled name carrying CR/LF.
  9911. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9912. sink.done_with_trailer(trailer);
  9913. }
  9914. (*i)++;
  9915. return true;
  9916. },
  9917. [i](bool /*success*/) { delete i; });
  9918. });
  9919. thread t = thread([&] { svr.listen(HOST, PORT); });
  9920. auto se = detail::scope_exit([&] {
  9921. svr.stop();
  9922. t.join();
  9923. ASSERT_FALSE(svr.is_running());
  9924. });
  9925. svr.wait_until_ready();
  9926. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9927. "Host: " + HOST +
  9928. "\r\n"
  9929. "Connection: close\r\n"
  9930. "\r\n";
  9931. std::string res;
  9932. ASSERT_TRUE(send_request(5, req, &res));
  9933. // The injected fields must not appear anywhere in the raw response.
  9934. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9935. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9936. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9937. // Invalid trailers are dropped entirely, matching set_header().
  9938. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9939. // The valid trailer still passes through.
  9940. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9941. }
  9942. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9943. // A custom header writer gets only the fields the default one writes
  9944. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9945. std::string s;
  9946. for (const auto &h : hdrs) {
  9947. s += h.first + ": " + h.second + "\r\n";
  9948. }
  9949. s += "\r\n";
  9950. return strm.write(s.data(), s.size());
  9951. };
  9952. for (auto custom_writer : {false, true}) {
  9953. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9954. Server svr;
  9955. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9956. svr.set_post_routing_handler([](const Request &, Response &res) {
  9957. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9958. });
  9959. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9960. // res.headers is a public field an application can populate directly,
  9961. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9962. // A valid header that must survive.
  9963. res.headers.emplace("X-Safe", "safe");
  9964. // Attacker-controlled value carrying CR/LF (response splitting).
  9965. res.headers.emplace("X-Reflected",
  9966. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9967. // Attacker-controlled name carrying CR/LF.
  9968. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9969. res.set_content("body", "text/plain");
  9970. });
  9971. thread t = thread([&] { svr.listen(HOST, PORT); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. ASSERT_FALSE(svr.is_running());
  9976. });
  9977. svr.wait_until_ready();
  9978. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9979. "Host: " + HOST +
  9980. "\r\n"
  9981. "Connection: close\r\n"
  9982. "\r\n";
  9983. std::string res;
  9984. ASSERT_TRUE(send_request(5, req, &res));
  9985. // The injected fields must not appear anywhere in the raw response.
  9986. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9987. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9988. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9989. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9990. // Invalid headers are dropped entirely, matching set_header().
  9991. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9992. // The valid header still passes through.
  9993. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9994. }
  9995. }
  9996. // Forward declaration: in split builds split.py strips `inline` and moves the
  9997. // definition into httplib.cc, so detail::write_request_line is not visible from
  9998. // the public httplib.h. Re-declaring it here lets the tests link against the
  9999. // symbol in both header-only and split builds.
  10000. namespace httplib {
  10001. namespace detail {
  10002. ssize_t write_request_line(Stream &strm, const std::string &method,
  10003. const std::string &path);
  10004. } // namespace detail
  10005. } // namespace httplib
  10006. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10007. // A well-formed target is written verbatim.
  10008. {
  10009. detail::BufferStream strm;
  10010. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10011. EXPECT_GT(n, 0);
  10012. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10013. }
  10014. // A target carrying CR/LF, SP or other control octets must be rejected
  10015. // before anything reaches the wire, otherwise it splits the request line and
  10016. // injects a header or a whole request.
  10017. const std::string evil_targets[] = {
  10018. "/a\r\nInjected: pwned",
  10019. "/a\rInjected",
  10020. "/a\nInjected",
  10021. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10022. "/a b",
  10023. "/a\tb",
  10024. "/a\x7f",
  10025. };
  10026. for (const auto &evil : evil_targets) {
  10027. detail::BufferStream strm;
  10028. auto n = detail::write_request_line(strm, "GET", evil);
  10029. EXPECT_LT(n, 0);
  10030. EXPECT_TRUE(strm.get_buffer().empty());
  10031. }
  10032. }
  10033. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10034. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10035. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10036. // target reaches write_request. The client must fail cleanly with
  10037. // Error::Write instead of putting a request-line-less, header-injecting
  10038. // request on the wire.
  10039. Server svr;
  10040. svr.Get("/a", [](const Request &, Response &res) {
  10041. res.set_content("ok", "text/plain");
  10042. });
  10043. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10044. auto se = detail::scope_exit([&] {
  10045. svr.stop();
  10046. thread.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. });
  10049. svr.wait_until_ready();
  10050. {
  10051. Client cli(HOST, PORT);
  10052. cli.set_path_encode(false);
  10053. // The request is rejected before anything is written, so the connection
  10054. // stays silent and the subsequent response read would otherwise block for
  10055. // the full default read timeout. Shorten it -- the assertion is on the
  10056. // error, not the timeout.
  10057. cli.set_read_timeout(1, 0);
  10058. auto res = cli.Get("/a\r\nInjected: pwned");
  10059. EXPECT_FALSE(res);
  10060. EXPECT_EQ(Error::Write, res.error());
  10061. }
  10062. }
  10063. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10064. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10065. // including extension methods.
  10066. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10067. for (const auto &method : good_methods) {
  10068. detail::BufferStream strm;
  10069. auto n = detail::write_request_line(strm, method, "/");
  10070. EXPECT_GT(n, 0);
  10071. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10072. }
  10073. // A method carrying CR/LF would split the request line and smuggle a whole
  10074. // request ahead of the real one. A space or an empty method corrupts the
  10075. // request line. All must be rejected before anything reaches the wire.
  10076. const std::string evil_methods[] = {
  10077. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10078. "GET\r\nInjected: pwned",
  10079. "GET\r",
  10080. "GET\n",
  10081. "GE T",
  10082. "",
  10083. };
  10084. for (const auto &evil : evil_methods) {
  10085. detail::BufferStream strm;
  10086. auto n = detail::write_request_line(strm, evil, "/");
  10087. EXPECT_LT(n, 0);
  10088. EXPECT_TRUE(strm.get_buffer().empty());
  10089. }
  10090. }
  10091. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10092. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10093. // through Client::send must fail with Error::Write and no request, neither
  10094. // the smuggled one nor the real one, may reach the server.
  10095. Server svr;
  10096. std::atomic<int> request_count(0);
  10097. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10098. request_count++;
  10099. res.status = StatusCode::OK_200;
  10100. return Server::HandlerResponse::Handled;
  10101. });
  10102. auto port = svr.bind_to_any_port(HOST);
  10103. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. thread.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. {
  10111. Client cli(HOST, port);
  10112. const std::string evil_methods[] = {
  10113. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10114. "GE T",
  10115. "",
  10116. };
  10117. for (const auto &evil : evil_methods) {
  10118. Request req;
  10119. req.method = evil;
  10120. req.path = "/";
  10121. auto res = cli.send(req);
  10122. EXPECT_FALSE(res);
  10123. EXPECT_EQ(Error::Write, res.error());
  10124. }
  10125. auto handle =
  10126. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10127. EXPECT_FALSE(handle.is_valid());
  10128. EXPECT_EQ(Error::Write, handle.error);
  10129. // A valid request on the same client still goes through.
  10130. auto res = cli.Get("/");
  10131. ASSERT_TRUE(res);
  10132. EXPECT_EQ(StatusCode::OK_200, res->status);
  10133. }
  10134. EXPECT_EQ(1, request_count.load());
  10135. }
  10136. // Sends a raw request and verifies that there isn't a crash or exception.
  10137. static void test_raw_request(const std::string &req,
  10138. std::string *out = nullptr) {
  10139. Server svr;
  10140. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10141. res.set_content("ok", "text/plain");
  10142. });
  10143. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10144. res.set_content("ok", "text/plain");
  10145. });
  10146. svr.Get("/header_field_value_check",
  10147. [&](const Request & /*req*/, Response &res) {
  10148. res.set_content("ok", "text/plain");
  10149. });
  10150. svr.CustomRoute("PROPFIND", "/dav",
  10151. [&](const Request & /*req*/, Response &res) {
  10152. res.status = StatusCode::MultiStatus_207;
  10153. });
  10154. // Server read timeout must be longer than the client read timeout for the
  10155. // bug to reproduce, probably to force the server to process a request
  10156. // without a trailing blank line.
  10157. const time_t client_read_timeout_sec = 1;
  10158. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10159. bool listen_thread_ok = false;
  10160. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. t.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. EXPECT_TRUE(listen_thread_ok);
  10166. });
  10167. svr.wait_until_ready();
  10168. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10169. }
  10170. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10171. // A certain header line causes an exception if the header property is parsed
  10172. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10173. test_raw_request(
  10174. "GET /hi HTTP/1.1\r\n"
  10175. " : "
  10176. " "
  10177. " ");
  10178. }
  10179. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10180. // A certain header line causes an exception if the header property *name* is
  10181. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10182. // greedy matcher and requires backtracking when there are a lot of ":"
  10183. // characters.
  10184. // This occurs with libc++ but not libstdc++.
  10185. test_raw_request(
  10186. "GET /hi HTTP/1.1\r\n"
  10187. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10188. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10189. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10190. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10191. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10192. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10193. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10194. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10195. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10196. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10197. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10198. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10199. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10200. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10201. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10202. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10203. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10204. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10205. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10206. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10207. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10208. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10209. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10210. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10211. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10212. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10213. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10214. "&&&%%%");
  10215. }
  10216. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10217. // Make sure this doesn't crash the server.
  10218. // In a previous version of the header line regex, the "\r" rendered the line
  10219. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10220. // a new position where the leading white space ended and the field value
  10221. // began.
  10222. // The crash occurs with libc++ but not libstdc++.
  10223. test_raw_request("GET /hi HTTP/1.1\r\n"
  10224. "a:" +
  10225. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10226. "\r\n"
  10227. "\r\n");
  10228. }
  10229. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10230. const char *rejected[] = {
  10231. // RFC 9112 §3: one SP between the parts, and nothing else
  10232. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10233. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10234. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10235. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10236. // A request-target has no fragment
  10237. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10238. // An HTTP/1.1 request needs a Host
  10239. "GET /hi HTTP/1.1\r\n\r\n",
  10240. };
  10241. for (auto request : rejected) {
  10242. std::string out;
  10243. test_raw_request(request, &out);
  10244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10245. }
  10246. std::string out;
  10247. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10248. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10249. }
  10250. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10251. // RFC 9112 §6.1
  10252. const char *requests[] = {
  10253. "PUT /put_hi HTTP/1.1\r\n"
  10254. "Host: localhost\r\n"
  10255. "Content-Length: 0\r\n"
  10256. "Transfer-Encoding: chunked\r\n"
  10257. "\r\n"
  10258. "0\r\n\r\n",
  10259. "PUT /put_hi HTTP/1.0\r\n"
  10260. "Connection: keep-alive\r\n"
  10261. "Transfer-Encoding: chunked\r\n"
  10262. "\r\n"
  10263. "0\r\n\r\n",
  10264. };
  10265. for (auto request : requests) {
  10266. std::string out;
  10267. test_raw_request(request, &out);
  10268. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10269. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10270. }
  10271. }
  10272. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10273. std::string out;
  10274. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10275. "Content-Type: text/plain\r\n"
  10276. "Transfer-Encoding: chunked\r\n"
  10277. "\r\n"
  10278. "nothex\r\n",
  10279. &out);
  10280. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10281. }
  10282. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10283. std::string out;
  10284. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10285. "Content-Type: text/plain\r\n"
  10286. "Transfer-Encoding: chunked\r\n"
  10287. "\r\n"
  10288. "3\r\n"
  10289. "xyz\r\n"
  10290. "NaN\r\n",
  10291. &out);
  10292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10293. }
  10294. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10295. std::string out;
  10296. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10297. "Content-Type: text/plain\r\n"
  10298. "Transfer-Encoding: chunked\r\n"
  10299. "\r\n"
  10300. // Length is too large for 64 bits.
  10301. "1ffffffffffffffff\r\n"
  10302. "xyz\r\n",
  10303. &out);
  10304. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10305. }
  10306. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10307. test_raw_request("GET /hi HTTP/1.1\r\n"
  10308. "Content-Type: text/plain\r\n\r");
  10309. }
  10310. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10311. std::string out;
  10312. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10313. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10314. }
  10315. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10316. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10317. std::string out;
  10318. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10319. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10320. }
  10321. }
  10322. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10323. std::string out;
  10324. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10325. "Host: localhost\r\n"
  10326. "Connection: close\r\n\r\n",
  10327. &out);
  10328. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10329. }
  10330. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10331. Server svr;
  10332. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10333. EXPECT_TRUE(!req.remote_addr.empty());
  10334. });
  10335. thread t = thread([&] { svr.listen(HOST, PORT); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. t.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. // Send an invalid request line to trigger Bad Request
  10343. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10344. std::string out;
  10345. ASSERT_TRUE(send_request(5, bad_req, &out));
  10346. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10347. }
  10348. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10349. // answered right away rather than blocking on a read that waits for EOF.
  10350. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10351. std::string out;
  10352. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10353. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10354. }
  10355. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10356. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10357. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10358. for (const auto *method : methods) {
  10359. Server svr;
  10360. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10361. EXPECT_FALSE(svr.is_valid()) << method;
  10362. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10363. }
  10364. }
  10365. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10366. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10367. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10368. for (const auto *method : methods) {
  10369. Server svr;
  10370. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10371. EXPECT_FALSE(svr.is_valid()) << method;
  10372. }
  10373. }
  10374. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10375. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10376. "COPY", "MOVE", "LOCK",
  10377. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10378. Server svr;
  10379. for (const auto *method : methods) {
  10380. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10381. }
  10382. EXPECT_TRUE(svr.is_valid());
  10383. }
  10384. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10385. Server svr;
  10386. svr.CustomRoute("POST", "/x",
  10387. [](const Request &, Response &, const ContentReader &) {});
  10388. EXPECT_FALSE(svr.is_valid());
  10389. }
  10390. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10391. Server svr;
  10392. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10393. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10394. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10395. EXPECT_FALSE(svr.is_valid());
  10396. }
  10397. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10398. Server svr;
  10399. auto captured = Error::Success;
  10400. svr.set_error_logger(
  10401. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10402. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10403. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10404. }
  10405. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10406. std::string out;
  10407. std::string request(
  10408. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10409. test_raw_request(request, &out);
  10410. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10411. }
  10412. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10413. std::string out;
  10414. std::string request(
  10415. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10416. test_raw_request(request, &out);
  10417. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10418. }
  10419. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10420. std::string out;
  10421. std::string request(
  10422. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10423. test_raw_request(request, &out);
  10424. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10425. }
  10426. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10427. std::string out;
  10428. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10429. "Host: localhost\r\n"
  10430. "Test: \r\n\r\n",
  10431. &out);
  10432. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10433. }
  10434. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10435. Server svr;
  10436. std::string x_custom;
  10437. std::string cookie;
  10438. std::string xff;
  10439. std::string x_unicode;
  10440. std::string x_iis;
  10441. svr.Get("/check", [&](const Request &req, Response &res) {
  10442. x_custom = req.get_header_value("X-Custom");
  10443. cookie = req.get_header_value("Cookie");
  10444. xff = req.get_header_value("X-Forwarded-For");
  10445. x_unicode = req.get_header_value("X-Unicode");
  10446. x_iis = req.get_header_value("X-IIS");
  10447. res.set_content("ok", "text/plain");
  10448. });
  10449. thread t = thread([&] { svr.listen(HOST, PORT); });
  10450. auto se = detail::scope_exit([&] {
  10451. svr.stop();
  10452. t.join();
  10453. ASSERT_FALSE(svr.is_running());
  10454. });
  10455. svr.wait_until_ready();
  10456. const std::string req = "GET /check HTTP/1.1\r\n"
  10457. "Host: localhost\r\n"
  10458. "X-Custom: a%0D%0AInjected: b\r\n"
  10459. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10460. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10461. "X-Unicode: %E3%81%82\r\n"
  10462. "X-IIS: %u00E9\r\n"
  10463. "Connection: close\r\n"
  10464. "\r\n";
  10465. std::string res;
  10466. ASSERT_TRUE(send_request(5, req, &res));
  10467. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10468. // Every value must be returned verbatim (wire form), with no decoding.
  10469. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10470. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10471. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10472. EXPECT_EQ("%E3%81%82", x_unicode);
  10473. EXPECT_EQ("%u00E9", x_iis);
  10474. }
  10475. // Applications that previously relied on automatic percent-decoding can
  10476. // reproduce the old behavior by explicitly calling decode_path_component()
  10477. // or, for RFC 3986 conformance, decode_uri_component().
  10478. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10479. Server svr;
  10480. std::string decoded;
  10481. svr.Get("/check", [&](const Request &req, Response &res) {
  10482. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10483. res.set_content("ok", "text/plain");
  10484. });
  10485. thread t = thread([&] { svr.listen(HOST, PORT); });
  10486. auto se = detail::scope_exit([&] {
  10487. svr.stop();
  10488. t.join();
  10489. ASSERT_FALSE(svr.is_running());
  10490. });
  10491. svr.wait_until_ready();
  10492. const std::string req = "GET /check HTTP/1.1\r\n"
  10493. "Host: localhost\r\n"
  10494. "X-Custom: hello%20world\r\n"
  10495. "Connection: close\r\n"
  10496. "\r\n";
  10497. std::string res;
  10498. ASSERT_TRUE(send_request(5, req, &res));
  10499. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10500. EXPECT_EQ("hello world", decoded);
  10501. }
  10502. // Regression test for #2033. Browsers send Referer values that include
  10503. // percent-encoded characters such as %0A inside the URL. Decoding the
  10504. // header value would either trip the post-decode CR/LF/NUL guard (the
  10505. // original bug, returning 400) or, after that guard was relaxed, silently
  10506. // store a literal LF — both unacceptable. The wire form must round-trip.
  10507. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10508. Server svr;
  10509. std::string referer;
  10510. svr.Get("/check", [&](const Request &req, Response &res) {
  10511. referer = req.get_header_value("Referer");
  10512. res.set_content("ok", "text/plain");
  10513. });
  10514. thread t = thread([&] { svr.listen(HOST, PORT); });
  10515. auto se = detail::scope_exit([&] {
  10516. svr.stop();
  10517. t.join();
  10518. ASSERT_FALSE(svr.is_running());
  10519. });
  10520. svr.wait_until_ready();
  10521. const std::string req = "GET /check HTTP/1.1\r\n"
  10522. "Host: localhost\r\n"
  10523. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10524. "Connection: close\r\n"
  10525. "\r\n";
  10526. std::string res;
  10527. ASSERT_TRUE(send_request(5, req, &res));
  10528. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10529. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10530. }
  10531. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10532. Server svr;
  10533. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10534. res.set_header("Cache-Control", "no-cache");
  10535. res.set_chunked_content_provider(
  10536. "text/event-stream", [](size_t offset, DataSink &sink) {
  10537. std::string s = "data:";
  10538. s += std::to_string(offset);
  10539. s += "\n\n";
  10540. auto ret = sink.write(s.data(), s.size());
  10541. EXPECT_TRUE(ret);
  10542. std::this_thread::sleep_for(std::chrono::seconds(1));
  10543. return true;
  10544. });
  10545. });
  10546. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10547. svr.wait_until_ready();
  10548. Client client(HOST, PORT);
  10549. const Headers headers = {{"Accept", "text/event-stream"}};
  10550. auto get_thread = std::thread([&client, &headers]() {
  10551. auto res = client.Get(
  10552. "/events", headers,
  10553. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10554. });
  10555. auto se = detail::scope_exit([&] {
  10556. svr.stop();
  10557. get_thread.join();
  10558. listen_thread.join();
  10559. ASSERT_FALSE(svr.is_running());
  10560. });
  10561. // Give GET time to get a few messages.
  10562. std::this_thread::sleep_for(std::chrono::seconds(2));
  10563. }
  10564. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10565. httplib::Server svr;
  10566. svr.Post("/hi",
  10567. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10568. res.status = StatusCode::OK_200;
  10569. });
  10570. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10571. svr.wait_until_ready();
  10572. Client cli(HOST, PORT);
  10573. auto res = cli.Post("/hi", "data", "text/plain");
  10574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10575. EXPECT_EQ(StatusCode::OK_200, res->status);
  10576. svr.stop();
  10577. thread.join();
  10578. ASSERT_FALSE(svr.is_running());
  10579. res = cli.Post("/hi", "data", "text/plain");
  10580. ASSERT_FALSE(res);
  10581. }
  10582. TEST(ServerStopTest, ListenFailure) {
  10583. Server svr;
  10584. auto t = thread([&]() {
  10585. auto ret = svr.listen("????", PORT);
  10586. EXPECT_FALSE(ret);
  10587. });
  10588. svr.wait_until_ready();
  10589. svr.stop();
  10590. t.join();
  10591. }
  10592. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10593. TEST(ServerStopTest, Decommision) {
  10594. Server svr;
  10595. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10596. for (int i = 0; i < 4; i++) {
  10597. auto is_even = !(i % 2);
  10598. std::thread t{[&] {
  10599. try {
  10600. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10601. if (is_even) {
  10602. throw std::runtime_error("Some thing that happens to go wrong.");
  10603. }
  10604. svr.listen(HOST, PORT);
  10605. } catch (...) { svr.decommission(); }
  10606. }};
  10607. svr.wait_until_ready();
  10608. // Server is up
  10609. {
  10610. Client cli(HOST, PORT);
  10611. auto res = cli.Get("/hi");
  10612. if (is_even) {
  10613. EXPECT_FALSE(res);
  10614. } else {
  10615. EXPECT_TRUE(res);
  10616. EXPECT_EQ("hi...", res->body);
  10617. }
  10618. }
  10619. svr.stop();
  10620. t.join();
  10621. // Server is down...
  10622. {
  10623. Client cli(HOST, PORT);
  10624. auto res = cli.Get("/hi");
  10625. EXPECT_FALSE(res);
  10626. }
  10627. }
  10628. }
  10629. #endif
  10630. // Helper function for string body upload progress tests
  10631. template <typename SetupHandler, typename ClientCall>
  10632. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10633. ClientCall &&client_call,
  10634. const string &body) {
  10635. Server svr;
  10636. setup_handler(svr);
  10637. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10638. auto se = detail::scope_exit([&] {
  10639. svr.stop();
  10640. t.join();
  10641. });
  10642. svr.wait_until_ready();
  10643. Client cli(HOST, PORT);
  10644. vector<uint64_t> progress_values;
  10645. bool progress_called = false;
  10646. auto res =
  10647. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10648. progress_values.push_back(current);
  10649. progress_called = true;
  10650. return true;
  10651. });
  10652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10653. EXPECT_EQ(200, res->status);
  10654. EXPECT_TRUE(progress_called);
  10655. }
  10656. TEST(UploadProgressTest, PostStringBodyBasic) {
  10657. TestStringBodyUploadProgress(
  10658. [](Server &svr) {
  10659. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10660. res.set_content("received", "text/plain");
  10661. });
  10662. },
  10663. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10664. return cli.Post("/test", body, "text/plain", progress_callback);
  10665. },
  10666. "test data for upload progress");
  10667. }
  10668. TEST(UploadProgressTest, PutStringBodyBasic) {
  10669. TestStringBodyUploadProgress(
  10670. [](Server &svr) {
  10671. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10672. res.set_content("put received", "text/plain");
  10673. });
  10674. },
  10675. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10676. return cli.Put("/test", body, "text/plain", progress_callback);
  10677. },
  10678. "put test data for upload progress");
  10679. }
  10680. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10681. TestStringBodyUploadProgress(
  10682. [](Server &svr) {
  10683. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10684. res.set_content("patch received", "text/plain");
  10685. });
  10686. },
  10687. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10688. return cli.Patch("/test", body, "text/plain", progress_callback);
  10689. },
  10690. "patch test data for upload progress");
  10691. }
  10692. // Helper function for content provider upload progress tests
  10693. template <typename SetupHandler, typename ClientCall>
  10694. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10695. ClientCall &&client_call) {
  10696. Server svr;
  10697. setup_handler(svr);
  10698. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10699. auto se = detail::scope_exit([&] {
  10700. svr.stop();
  10701. t.join();
  10702. });
  10703. svr.wait_until_ready();
  10704. Client cli(HOST, PORT);
  10705. vector<uint64_t> progress_values;
  10706. auto res =
  10707. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10708. progress_values.push_back(current);
  10709. return true;
  10710. });
  10711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10712. EXPECT_EQ(200, res->status);
  10713. EXPECT_FALSE(progress_values.empty());
  10714. }
  10715. TEST(UploadProgressTest, PostContentProviderProgress) {
  10716. TestContentProviderUploadProgress(
  10717. [](Server &svr) {
  10718. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10719. res.set_content("provider received", "text/plain");
  10720. });
  10721. },
  10722. [](Client &cli, UploadProgress progress_callback) {
  10723. return cli.Post(
  10724. "/test", 9,
  10725. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10726. sink.os << "test data";
  10727. return true;
  10728. },
  10729. "text/plain", progress_callback);
  10730. });
  10731. }
  10732. // Helper function for multipart upload progress tests
  10733. template <typename SetupHandler, typename ClientCall>
  10734. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10735. ClientCall &&client_call,
  10736. const string &endpoint) {
  10737. Server svr;
  10738. setup_handler(svr);
  10739. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10740. auto se = detail::scope_exit([&] {
  10741. svr.stop();
  10742. t.join();
  10743. });
  10744. svr.wait_until_ready();
  10745. Client cli(HOST, PORT);
  10746. vector<uint64_t> progress_values;
  10747. UploadFormDataItems items = {
  10748. {"field1", "value1", "", ""},
  10749. {"field2", "longer value for progress tracking test", "", ""},
  10750. {"file1", "file content data for upload progress", "test.txt",
  10751. "text/plain"}};
  10752. auto res = client_call(cli, endpoint, items,
  10753. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10754. progress_values.push_back(current);
  10755. return true;
  10756. });
  10757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10758. EXPECT_EQ(200, res->status);
  10759. EXPECT_FALSE(progress_values.empty());
  10760. }
  10761. TEST(UploadProgressTest, PostMultipartProgress) {
  10762. TestMultipartUploadProgress(
  10763. [](Server &svr) {
  10764. svr.Post("/multipart", [](const Request &req, Response &res) {
  10765. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10766. res.set_content("multipart received", "text/plain");
  10767. });
  10768. },
  10769. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10770. UploadProgress progress_callback) {
  10771. return cli.Post(endpoint, items, progress_callback);
  10772. },
  10773. "/multipart");
  10774. }
  10775. // Helper function for basic download progress tests
  10776. template <typename SetupHandler, typename ClientCall>
  10777. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10778. ClientCall &&client_call, const string &endpoint,
  10779. size_t expected_content_size) {
  10780. Server svr;
  10781. setup_handler(svr);
  10782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10783. auto se = detail::scope_exit([&] {
  10784. svr.stop();
  10785. t.join();
  10786. });
  10787. svr.wait_until_ready();
  10788. Client cli(HOST, PORT);
  10789. vector<uint64_t> progress_values;
  10790. auto res = client_call(cli, endpoint,
  10791. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10792. progress_values.push_back(current);
  10793. return true;
  10794. });
  10795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10796. EXPECT_EQ(200, res->status);
  10797. EXPECT_FALSE(progress_values.empty());
  10798. EXPECT_EQ(expected_content_size, res->body.size());
  10799. }
  10800. TEST(DownloadProgressTest, GetBasic) {
  10801. TestBasicDownloadProgress(
  10802. [](Server &svr) {
  10803. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10804. string content(1000, 'D');
  10805. res.set_content(content, "text/plain");
  10806. });
  10807. },
  10808. [](Client &cli, const string &endpoint,
  10809. DownloadProgress progress_callback) {
  10810. return cli.Get(endpoint, progress_callback);
  10811. },
  10812. "/download", 1000u);
  10813. }
  10814. // Helper function for content receiver download progress tests
  10815. template <typename SetupHandler, typename ClientCall>
  10816. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10817. ClientCall &&client_call,
  10818. const string &endpoint,
  10819. size_t expected_content_size) {
  10820. Server svr;
  10821. setup_handler(svr);
  10822. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10823. auto se = detail::scope_exit([&] {
  10824. svr.stop();
  10825. t.join();
  10826. });
  10827. svr.wait_until_ready();
  10828. Client cli(HOST, PORT);
  10829. vector<uint64_t> progress_values;
  10830. string received_body;
  10831. auto res = client_call(
  10832. cli, endpoint,
  10833. [&](const char *data, size_t data_length) -> bool {
  10834. received_body.append(data, data_length);
  10835. return true;
  10836. },
  10837. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10838. progress_values.push_back(current);
  10839. return true;
  10840. });
  10841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10842. EXPECT_EQ(200, res->status);
  10843. EXPECT_FALSE(progress_values.empty());
  10844. EXPECT_EQ(expected_content_size, received_body.size());
  10845. EXPECT_TRUE(res->body.empty());
  10846. }
  10847. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10848. TestContentReceiverDownloadProgress(
  10849. [](Server &svr) {
  10850. svr.Get("/download-receiver",
  10851. [](const Request & /*req*/, Response &res) {
  10852. string content(2000, 'R');
  10853. res.set_content(content, "text/plain");
  10854. });
  10855. },
  10856. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10857. DownloadProgress progress_callback) {
  10858. return cli.Get(endpoint, content_receiver, progress_callback);
  10859. },
  10860. "/download-receiver", 2000u);
  10861. }
  10862. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10863. // A provider reaching a pass with nothing to hand over - an empty buffer
  10864. // popped off a queue, say - must not be taken to mean the body is finished.
  10865. // It used to end the loop with the terminating chunk unwritten while the
  10866. // server still considered the response complete, so the peer waited for an
  10867. // end that never arrived.
  10868. Server svr;
  10869. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10870. auto step = std::make_shared<int>(0);
  10871. res.set_chunked_content_provider("text/plain",
  10872. [step](size_t /*offset*/, DataSink &sink) {
  10873. switch ((*step)++) {
  10874. case 0: sink.write("", 0); break;
  10875. case 1: sink.write("hello", 5); break;
  10876. default: sink.done(); break;
  10877. }
  10878. return true;
  10879. });
  10880. });
  10881. auto port = svr.bind_to_any_port(HOST);
  10882. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10883. auto listen_se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. listen_thread.join();
  10886. ASSERT_FALSE(svr.is_running());
  10887. });
  10888. svr.wait_until_ready();
  10889. Client cli(HOST, port);
  10890. // Without the fix the body is never terminated, so bound the wait rather
  10891. // than letting the test hang on the default read timeout.
  10892. cli.set_read_timeout(5, 0);
  10893. auto res = cli.Get("/stream");
  10894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10895. EXPECT_EQ(StatusCode::OK_200, res->status);
  10896. EXPECT_EQ("hello", res->body);
  10897. }
  10898. TEST(StreamingTest, NoContentLengthStreaming) {
  10899. Server svr;
  10900. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10901. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10902. if (offset < 6) {
  10903. sink.os << (offset < 3 ? "a" : "b");
  10904. } else {
  10905. sink.done();
  10906. }
  10907. return true;
  10908. });
  10909. });
  10910. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10911. auto listen_se = detail::scope_exit([&] {
  10912. svr.stop();
  10913. listen_thread.join();
  10914. ASSERT_FALSE(svr.is_running());
  10915. });
  10916. svr.wait_until_ready();
  10917. Client client(HOST, PORT);
  10918. auto get_thread = std::thread([&client]() {
  10919. std::string s;
  10920. auto res =
  10921. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10922. s += std::string(data, len);
  10923. return true;
  10924. });
  10925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10926. EXPECT_EQ(StatusCode::OK_200, res->status);
  10927. EXPECT_EQ("aaabbb", s);
  10928. });
  10929. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10930. // Give GET time to get a few messages.
  10931. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10932. }
  10933. TEST(MountTest, Unmount) {
  10934. Server svr;
  10935. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10936. auto se = detail::scope_exit([&] {
  10937. svr.stop();
  10938. listen_thread.join();
  10939. ASSERT_FALSE(svr.is_running());
  10940. });
  10941. svr.wait_until_ready();
  10942. Client cli("localhost", PORT);
  10943. svr.set_mount_point("/mount2", "./www2");
  10944. auto res = cli.Get("/");
  10945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10946. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10947. res = cli.Get("/mount2/dir/test.html");
  10948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10949. EXPECT_EQ(StatusCode::OK_200, res->status);
  10950. svr.set_mount_point("/", "./www");
  10951. res = cli.Get("/dir/");
  10952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10953. EXPECT_EQ(StatusCode::OK_200, res->status);
  10954. svr.remove_mount_point("/");
  10955. res = cli.Get("/dir/");
  10956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10958. svr.remove_mount_point("/mount2");
  10959. res = cli.Get("/mount2/dir/test.html");
  10960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10961. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10962. }
  10963. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10964. Server svr;
  10965. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10966. svr.Get("/api/hello", [](const Request &, Response &res) {
  10967. res.set_content("api", "text/plain");
  10968. });
  10969. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10970. auto se = detail::scope_exit([&] {
  10971. svr.stop();
  10972. listen_thread.join();
  10973. ASSERT_FALSE(svr.is_running());
  10974. });
  10975. svr.wait_until_ready();
  10976. Client cli(HOST, PORT);
  10977. auto res = cli.Get("/dir/test.html");
  10978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10979. EXPECT_EQ(StatusCode::OK_200, res->status);
  10980. res = cli.Get("/api/hello");
  10981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10982. EXPECT_EQ(StatusCode::OK_200, res->status);
  10983. EXPECT_EQ("api", res->body);
  10984. }
  10985. TEST(MountTest, PathSegmentBoundary) {
  10986. Server svr;
  10987. svr.set_mount_point("/mount2", "./www2");
  10988. svr.set_mount_point("/", "./www");
  10989. auto port = svr.bind_to_any_port(HOST);
  10990. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10991. auto se = detail::scope_exit([&] {
  10992. svr.stop();
  10993. listen_thread.join();
  10994. ASSERT_FALSE(svr.is_running());
  10995. });
  10996. svr.wait_until_ready();
  10997. Client cli(HOST, port);
  10998. auto res = cli.Get("/mount2/dir/test.html");
  10999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11000. EXPECT_EQ(StatusCode::OK_200, res->status);
  11001. // "/mount2" must not match part-way through a path segment.
  11002. res = cli.Get("/mount2dir/test.html");
  11003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11004. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11005. // A mount point ending in '/' keeps matching every path below it.
  11006. res = cli.Get("/dir/test.html");
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. EXPECT_EQ(StatusCode::OK_200, res->status);
  11009. }
  11010. TEST(MountTest, Redicect) {
  11011. Server svr;
  11012. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11013. auto se = detail::scope_exit([&] {
  11014. svr.stop();
  11015. listen_thread.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. });
  11018. svr.set_mount_point("/", "./www");
  11019. svr.wait_until_ready();
  11020. Client cli("localhost", PORT);
  11021. auto res = cli.Get("/dir/");
  11022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11023. EXPECT_EQ(StatusCode::OK_200, res->status);
  11024. res = cli.Get("/dir");
  11025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11026. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11027. res = cli.Get("/file");
  11028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11029. EXPECT_EQ(StatusCode::OK_200, res->status);
  11030. res = cli.Get("/file/");
  11031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11033. cli.set_follow_location(true);
  11034. res = cli.Get("/dir");
  11035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11036. EXPECT_EQ(StatusCode::OK_200, res->status);
  11037. }
  11038. TEST(MountTest, MultibytesPathName) {
  11039. Server svr;
  11040. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11041. auto se = detail::scope_exit([&] {
  11042. svr.stop();
  11043. listen_thread.join();
  11044. ASSERT_FALSE(svr.is_running());
  11045. });
  11046. svr.set_mount_point("/", "./www");
  11047. svr.wait_until_ready();
  11048. Client cli("localhost", PORT);
  11049. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11051. EXPECT_EQ(StatusCode::OK_200, res->status);
  11052. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11053. }
  11054. // A mount point serves no path with an empty segment or one ending in '.' or
  11055. // a space, so a guard in the pre-routing handler sees the path of every file
  11056. // that is served
  11057. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11058. Server svr;
  11059. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11060. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11061. if (req.path == "/dir/test.html") {
  11062. res.status = StatusCode::Unauthorized_401;
  11063. return Server::HandlerResponse::Handled;
  11064. }
  11065. return Server::HandlerResponse::Unhandled;
  11066. });
  11067. auto port = svr.bind_to_any_port(HOST);
  11068. ASSERT_LT(0, port);
  11069. thread t = thread([&] { svr.listen_after_bind(); });
  11070. auto se = detail::scope_exit([&] {
  11071. svr.stop();
  11072. t.join();
  11073. ASSERT_FALSE(svr.is_running());
  11074. });
  11075. svr.wait_until_ready();
  11076. Client cli(HOST, port);
  11077. for (auto path :
  11078. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11079. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11080. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11081. "/dir/test.html%3A%3A$DATA"}) {
  11082. SCOPED_TRACE(path);
  11083. auto res = cli.Get(path);
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11086. }
  11087. }
  11088. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11089. Server svr;
  11090. svr.set_mount_point("/", "./www");
  11091. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11092. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11093. auto port = svr.bind_to_any_port(HOST);
  11094. ASSERT_GT(port, 0);
  11095. thread t = thread([&] { svr.listen_after_bind(); });
  11096. auto se = detail::scope_exit([&] {
  11097. svr.stop();
  11098. t.join();
  11099. ASSERT_FALSE(svr.is_running());
  11100. });
  11101. svr.wait_until_ready();
  11102. Client cli(HOST, port);
  11103. auto res = cli.Get("/dir/test.abcde");
  11104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11105. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11106. res = cli.Get("/dir/test.html");
  11107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11108. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11109. }
  11110. #ifdef _WIN32
  11111. // Issue #2435: mmap::open() must succeed even when another handle holds
  11112. // the file open for writing (e.g. an active log file).
  11113. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11114. const char *path = "mmap_concurrent_writer_test.txt";
  11115. const char *content = "hello";
  11116. {
  11117. std::ofstream f(path, std::ios::binary);
  11118. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11119. }
  11120. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11121. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11122. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11123. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11124. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11125. detail::mmap m(path);
  11126. ASSERT_TRUE(m.is_open());
  11127. EXPECT_EQ(strlen(content), m.size());
  11128. char buf[8];
  11129. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11130. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11131. }
  11132. #endif
  11133. #ifndef _WIN32
  11134. // A directory or a device has no size to serve.
  11135. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11136. const char *path = "./mmap_not_regular_test_dir";
  11137. ASSERT_EQ(0, ::mkdir(path, 0755));
  11138. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11139. for (auto p : {path, "/dev/null"}) {
  11140. detail::mmap m(p);
  11141. EXPECT_FALSE(m.is_open()) << p;
  11142. EXPECT_EQ(0U, m.size()) << p;
  11143. }
  11144. Server svr;
  11145. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11146. res.set_file_content("/dev/null");
  11147. });
  11148. auto port = svr.bind_to_any_port(HOST);
  11149. thread t = thread([&] { svr.listen_after_bind(); });
  11150. auto se = detail::scope_exit([&] {
  11151. svr.stop();
  11152. t.join();
  11153. });
  11154. svr.wait_until_ready();
  11155. auto res = Client(HOST, port).Get("/null");
  11156. ASSERT_TRUE(res);
  11157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11158. }
  11159. #endif
  11160. #ifdef __linux__
  11161. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11162. TEST(MmapTest, FileIsNotMapped) {
  11163. const char *path = "mmap_not_mapped_test.txt";
  11164. {
  11165. std::ofstream f(path, std::ios::binary);
  11166. f << "hello";
  11167. }
  11168. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11169. detail::mmap m(path);
  11170. ASSERT_TRUE(m.is_open());
  11171. std::ifstream maps("/proc/self/maps");
  11172. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11173. std::istreambuf_iterator<char>());
  11174. EXPECT_EQ(std::string::npos, mappings.find(path));
  11175. }
  11176. #endif
  11177. TEST(KeepAliveTest, ReadTimeout) {
  11178. Server svr;
  11179. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11180. std::this_thread::sleep_for(std::chrono::seconds(2));
  11181. res.set_content("a", "text/plain");
  11182. });
  11183. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11184. res.set_content("b", "text/plain");
  11185. });
  11186. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11187. auto se = detail::scope_exit([&] {
  11188. svr.stop();
  11189. listen_thread.join();
  11190. ASSERT_FALSE(svr.is_running());
  11191. });
  11192. svr.wait_until_ready();
  11193. Client cli("localhost", PORT);
  11194. cli.set_keep_alive(true);
  11195. cli.set_read_timeout(std::chrono::seconds(1));
  11196. auto resa = cli.Get("/a");
  11197. ASSERT_FALSE(resa);
  11198. EXPECT_EQ(Error::Read, resa.error());
  11199. auto resb = cli.Get("/b");
  11200. ASSERT_TRUE(resb);
  11201. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11202. EXPECT_EQ("b", resb->body);
  11203. }
  11204. TEST(KeepAliveTest, MaxCount) {
  11205. size_t keep_alive_max_count = 3;
  11206. Server svr;
  11207. svr.set_keep_alive_max_count(keep_alive_max_count);
  11208. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11209. res.set_content("Hello World!", "text/plain");
  11210. });
  11211. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11212. auto se = detail::scope_exit([&] {
  11213. svr.stop();
  11214. listen_thread.join();
  11215. ASSERT_FALSE(svr.is_running());
  11216. });
  11217. svr.wait_until_ready();
  11218. Client cli(HOST, PORT);
  11219. cli.set_keep_alive(true);
  11220. for (size_t i = 0; i < 5; i++) {
  11221. auto result = cli.Get("/hi");
  11222. ASSERT_TRUE(result);
  11223. EXPECT_EQ(StatusCode::OK_200, result->status);
  11224. if (i == keep_alive_max_count - 1) {
  11225. EXPECT_EQ("close", result->get_header_value("Connection"));
  11226. } else {
  11227. EXPECT_FALSE(result->has_header("Connection"));
  11228. }
  11229. }
  11230. }
  11231. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11232. // can pull the next one into the server's buffer. The server must serve it
  11233. // without waiting for the socket to become readable again. The keep-alive
  11234. // timeout outlasts the client's read timeout, so a request left waiting for it
  11235. // shows up as a missing response.
  11236. static void serve_pipelining_routes(Server &svr,
  11237. const std::function<void(int)> &client) {
  11238. svr.set_keep_alive_timeout(5);
  11239. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11240. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11241. });
  11242. svr.Post("/echo", [](const Request &req, Response &res) {
  11243. res.set_content("echo " + req.body, "text/plain");
  11244. });
  11245. auto port = svr.bind_to_any_port(HOST);
  11246. thread t = thread([&] { svr.listen_after_bind(); });
  11247. auto se = detail::scope_exit([&] {
  11248. svr.stop();
  11249. t.join();
  11250. });
  11251. svr.wait_until_ready();
  11252. client(port);
  11253. }
  11254. static std::string
  11255. send_pipelined_requests(const std::vector<std::string> &parts) {
  11256. Server svr;
  11257. std::string res;
  11258. serve_pipelining_routes(svr, [&](int port) {
  11259. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11260. });
  11261. return res;
  11262. }
  11263. static void expect_in_order(const std::string &res,
  11264. const std::vector<std::string> &bodies) {
  11265. size_t pos = 0;
  11266. for (const auto &body : bodies) {
  11267. pos = res.find(body, pos);
  11268. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11269. pos += body.size();
  11270. }
  11271. }
  11272. TEST(KeepAliveTest, PipelinedRequests) {
  11273. auto res = send_pipelined_requests(
  11274. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11275. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11276. "Content-Length: 4\r\n\r\nbody"
  11277. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11278. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11279. }
  11280. // The second request starts in the server's buffer and ends on the socket.
  11281. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11282. auto res =
  11283. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11284. "GET /hi/2 HTTP/1.1\r\nHo",
  11285. "st: localhost\r\nConnection: close\r\n\r\n"});
  11286. expect_in_order(res, {"hi 1", "hi 2"});
  11287. }
  11288. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11289. // CRLF after a body does not turn into a 400 for the next request.
  11290. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11291. auto res = send_pipelined_requests(
  11292. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11293. "Content-Length: 4\r\n\r\nbody\r\n"
  11294. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11295. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11296. expect_in_order(res, {"echo body", "hi 2"});
  11297. }
  11298. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11299. // must not be served as the next request.
  11300. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11301. auto res = send_pipelined_requests(
  11302. {"INVALID REQUEST LINE\r\n\r\n"
  11303. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11304. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11305. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11306. }
  11307. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11308. // Over TLS, the next request is held by the TLS library as already decrypted
  11309. // data rather than on the socket.
  11310. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11312. std::string res;
  11313. serve_pipelining_routes(svr, [&](int port) {
  11314. // One part, so all three requests arrive in one TLS record
  11315. EXPECT_TRUE(send_ssl_request_in_parts(
  11316. 2,
  11317. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11318. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11319. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11320. &res, port));
  11321. });
  11322. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11323. }
  11324. #endif
  11325. TEST(KeepAliveTest, Issue1041) {
  11326. Server svr;
  11327. svr.set_keep_alive_timeout(3);
  11328. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11329. res.set_content("Hello World!", "text/plain");
  11330. });
  11331. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11332. auto se = detail::scope_exit([&] {
  11333. svr.stop();
  11334. listen_thread.join();
  11335. ASSERT_FALSE(svr.is_running());
  11336. });
  11337. svr.wait_until_ready();
  11338. Client cli(HOST, PORT);
  11339. cli.set_keep_alive(true);
  11340. auto result = cli.Get("/hi");
  11341. ASSERT_TRUE(result);
  11342. EXPECT_EQ(StatusCode::OK_200, result->status);
  11343. std::this_thread::sleep_for(std::chrono::seconds(5));
  11344. result = cli.Get("/hi");
  11345. ASSERT_TRUE(result);
  11346. EXPECT_EQ(StatusCode::OK_200, result->status);
  11347. }
  11348. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11349. Server svr;
  11350. svr.set_keep_alive_max_count(0);
  11351. std::set<int> remote_ports;
  11352. svr.Get("/hi", [&](const Request &req, Response &res) {
  11353. remote_ports.insert(req.remote_port);
  11354. res.set_content("hi", "text/plain");
  11355. });
  11356. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11357. auto se = detail::scope_exit([&] {
  11358. svr.stop();
  11359. listen_thread.join();
  11360. ASSERT_FALSE(svr.is_running());
  11361. });
  11362. svr.wait_until_ready();
  11363. Client cli(HOST, PORT);
  11364. cli.set_keep_alive(true);
  11365. for (int i = 0; i < 3; i++) {
  11366. auto res = cli.Get("/hi");
  11367. ASSERT_TRUE(res);
  11368. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11369. }
  11370. // All three over one connection
  11371. EXPECT_EQ(1u, remote_ports.size());
  11372. }
  11373. // Forward declaration (see the base64_encode note).
  11374. namespace httplib {
  11375. namespace detail {
  11376. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11377. } // namespace detail
  11378. } // namespace httplib
  11379. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11380. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11381. #ifndef _WIN32
  11382. signal(SIGPIPE, SIG_IGN);
  11383. #endif
  11384. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11385. ASSERT_NE(INVALID_SOCKET, srv);
  11386. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11387. default_socket_options(srv);
  11388. sockaddr_in addr{};
  11389. addr.sin_family = AF_INET;
  11390. addr.sin_port = 0;
  11391. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11392. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11393. ASSERT_EQ(0, ::listen(srv, 2));
  11394. socklen_t addr_len = sizeof(addr);
  11395. ASSERT_EQ(0,
  11396. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11397. auto port = ntohs(addr.sin_port);
  11398. struct Peer {
  11399. socket_t sock = INVALID_SOCKET;
  11400. #ifdef CPPHTTPLIB_SSL_ENABLED
  11401. tls::session_t session = nullptr;
  11402. #endif
  11403. };
  11404. #ifdef CPPHTTPLIB_SSL_ENABLED
  11405. tls::ctx_t ctx = nullptr;
  11406. if (use_tls) {
  11407. ctx = tls::create_server_context();
  11408. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11409. nullptr);
  11410. }
  11411. auto ctx_se = detail::scope_exit([&] {
  11412. if (ctx) { tls::free_context(ctx); }
  11413. });
  11414. #endif
  11415. auto close_peer = [](Peer &peer) {
  11416. #ifdef CPPHTTPLIB_SSL_ENABLED
  11417. if (peer.session) { tls::free_session(peer.session); }
  11418. #endif
  11419. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11420. };
  11421. auto accept_peer = [&]() {
  11422. Peer peer;
  11423. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11424. peer.sock = ::accept(srv, nullptr, nullptr);
  11425. if (peer.sock == INVALID_SOCKET) { return peer; }
  11426. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11427. #ifdef CPPHTTPLIB_SSL_ENABLED
  11428. if (use_tls) {
  11429. peer.session = tls::create_session(ctx, peer.sock);
  11430. tls::TlsError err;
  11431. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11432. close_peer(peer);
  11433. return Peer();
  11434. }
  11435. }
  11436. #endif
  11437. return peer;
  11438. };
  11439. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11440. #ifdef CPPHTTPLIB_SSL_ENABLED
  11441. tls::TlsError err;
  11442. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11443. #endif
  11444. return detail::read_socket(peer.sock, buf, len, 0);
  11445. };
  11446. auto read_head = [&](const Peer &peer) {
  11447. std::string head;
  11448. char buf[1024];
  11449. while (head.find("\r\n\r\n") == std::string::npos) {
  11450. auto n = read_some(peer, buf, sizeof(buf));
  11451. if (n <= 0) { break; }
  11452. head.append(buf, static_cast<size_t>(n));
  11453. }
  11454. };
  11455. auto send_text = [](const Peer &peer, const std::string &text) {
  11456. #ifdef CPPHTTPLIB_SSL_ENABLED
  11457. tls::TlsError err;
  11458. if (peer.session) {
  11459. tls::write(peer.session, text.data(), text.size(), err);
  11460. return;
  11461. }
  11462. #endif
  11463. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11464. };
  11465. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11466. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11467. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11468. // Sent once the first response is read, so that it lands on an idle socket
  11469. std::promise<void> first_response_read;
  11470. auto first_response_read_future = first_response_read.get_future();
  11471. auto server_thread = std::thread([&] {
  11472. auto peer1 = accept_peer();
  11473. if (peer1.sock == INVALID_SOCKET) { return; }
  11474. read_head(peer1);
  11475. if (same_write) {
  11476. send_text(peer1, first + stray);
  11477. } else {
  11478. send_text(peer1, first);
  11479. first_response_read_future.wait_for(std::chrono::seconds(5));
  11480. send_text(peer1, stray);
  11481. }
  11482. // peer1 stays open, so only the unread data can tell the client
  11483. auto peer2 = accept_peer();
  11484. if (peer2.sock != INVALID_SOCKET) {
  11485. read_head(peer2);
  11486. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11487. "Connection: close\r\n\r\nsecond");
  11488. close_peer(peer2);
  11489. }
  11490. close_peer(peer1);
  11491. });
  11492. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11493. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11494. std::to_string(port));
  11495. #ifdef CPPHTTPLIB_SSL_ENABLED
  11496. cli.enable_server_certificate_verification(false);
  11497. #endif
  11498. cli.set_keep_alive(true);
  11499. cli.set_read_timeout(5, 0);
  11500. auto res = cli.Get("/1");
  11501. first_response_read.set_value();
  11502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11503. EXPECT_EQ("first", res->body);
  11504. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11505. res = cli.Get("/2");
  11506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11507. EXPECT_EQ(StatusCode::OK_200, res->status);
  11508. EXPECT_EQ("second", res->body);
  11509. }
  11510. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11511. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11512. }
  11513. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11514. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11515. }
  11516. #ifdef CPPHTTPLIB_SSL_ENABLED
  11517. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11518. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11519. }
  11520. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11521. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11522. }
  11523. #endif
  11524. TEST(KeepAliveTest, Issue1959) {
  11525. Server svr;
  11526. svr.set_keep_alive_timeout(5);
  11527. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11528. res.set_content("a", "text/plain");
  11529. });
  11530. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11531. auto se = detail::scope_exit([&] {
  11532. if (!svr.is_running()) return;
  11533. svr.stop();
  11534. listen_thread.join();
  11535. ASSERT_FALSE(svr.is_running());
  11536. });
  11537. svr.wait_until_ready();
  11538. Client cli("localhost", PORT);
  11539. cli.set_keep_alive(true);
  11540. using namespace std::chrono;
  11541. auto start = steady_clock::now();
  11542. cli.Get("/a");
  11543. svr.stop();
  11544. listen_thread.join();
  11545. auto end = steady_clock::now();
  11546. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11547. EXPECT_LT(elapsed, 5000);
  11548. }
  11549. #ifdef CPPHTTPLIB_SSL_ENABLED
  11550. TEST(KeepAliveTest, SSLClientReconnection) {
  11551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11552. ASSERT_TRUE(svr.is_valid());
  11553. svr.set_keep_alive_timeout(1);
  11554. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11555. res.set_content("Hello World!", "text/plain");
  11556. });
  11557. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11558. auto se = detail::scope_exit([&] {
  11559. svr.stop();
  11560. listen_thread.join();
  11561. ASSERT_FALSE(svr.is_running());
  11562. });
  11563. svr.wait_until_ready();
  11564. SSLClient cli(HOST, PORT);
  11565. cli.enable_server_certificate_verification(false);
  11566. cli.set_keep_alive(true);
  11567. auto result = cli.Get("/hi");
  11568. ASSERT_TRUE(result);
  11569. EXPECT_EQ(StatusCode::OK_200, result->status);
  11570. result = cli.Get("/hi");
  11571. ASSERT_TRUE(result);
  11572. EXPECT_EQ(StatusCode::OK_200, result->status);
  11573. std::this_thread::sleep_for(std::chrono::seconds(2));
  11574. // Recoonect
  11575. result = cli.Get("/hi");
  11576. ASSERT_TRUE(result);
  11577. EXPECT_EQ(StatusCode::OK_200, result->status);
  11578. result = cli.Get("/hi");
  11579. ASSERT_TRUE(result);
  11580. EXPECT_EQ(StatusCode::OK_200, result->status);
  11581. }
  11582. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11584. ASSERT_TRUE(svr.is_valid());
  11585. svr.set_keep_alive_timeout(1);
  11586. std::string content = "reconnect";
  11587. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11588. res.set_content("Hello World!", "text/plain");
  11589. });
  11590. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11591. auto se = detail::scope_exit([&] {
  11592. svr.stop();
  11593. listen_thread.join();
  11594. ASSERT_FALSE(svr.is_running());
  11595. });
  11596. svr.wait_until_ready();
  11597. SSLClient cli(HOST, PORT);
  11598. cli.enable_server_certificate_verification(false);
  11599. cli.set_keep_alive(true);
  11600. auto result = cli.Post(
  11601. "/hi", content.size(),
  11602. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11603. sink.write(content.c_str(), content.size());
  11604. return true;
  11605. },
  11606. "text/plain");
  11607. ASSERT_TRUE(result);
  11608. EXPECT_EQ(200, result->status);
  11609. std::this_thread::sleep_for(std::chrono::seconds(2));
  11610. // Recoonect
  11611. result = cli.Post(
  11612. "/hi", content.size(),
  11613. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11614. sink.write(content.c_str(), content.size());
  11615. return true;
  11616. },
  11617. "text/plain");
  11618. ASSERT_TRUE(result);
  11619. EXPECT_EQ(200, result->status);
  11620. result = cli.Post(
  11621. "/hi", content.size(),
  11622. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11623. sink.write(content.c_str(), content.size());
  11624. return true;
  11625. },
  11626. "text/plain");
  11627. ASSERT_TRUE(result);
  11628. EXPECT_EQ(200, result->status);
  11629. }
  11630. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11631. using namespace httplib::tls;
  11632. {
  11633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11634. ASSERT_TRUE(svr.is_valid());
  11635. svr.Get("/sni", [&](const Request &req, Response &res) {
  11636. std::string expected = req.sni();
  11637. EXPECT_EQ(expected, req.get_param_value("expected"));
  11638. res.set_content("ok", "text/plain");
  11639. });
  11640. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11641. auto se = detail::scope_exit([&] {
  11642. svr.stop();
  11643. listen_thread.join();
  11644. ASSERT_FALSE(svr.is_running());
  11645. });
  11646. svr.wait_until_ready();
  11647. {
  11648. SSLClient cli("localhost", PORT);
  11649. cli.enable_server_certificate_verification(false);
  11650. auto res = cli.Get("/sni?expected=localhost");
  11651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11652. }
  11653. {
  11654. SSLClient cli("::1", PORT);
  11655. cli.enable_server_certificate_verification(false);
  11656. auto res = cli.Get("/sni?expected=");
  11657. // NOTE: This may fail if the server is listening on IPv4 only
  11658. // (e.g., when localhost resolves to 127.0.0.1 only)
  11659. if (res) {
  11660. EXPECT_EQ(StatusCode::OK_200, res->status);
  11661. } else {
  11662. EXPECT_EQ(Error::Connection, res.error());
  11663. }
  11664. }
  11665. }
  11666. }
  11667. // The SNI of a failed handshake does not reach the next connection that the
  11668. // same worker thread serves
  11669. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11671. ASSERT_TRUE(svr.is_valid());
  11672. svr.new_task_queue = [] { return new ThreadPool(1); };
  11673. svr.Get("/sni", [](const Request &req, Response &res) {
  11674. res.set_content(req.sni(), "text/plain");
  11675. });
  11676. auto port = svr.bind_to_any_port("127.0.0.1");
  11677. ASSERT_LT(0, port);
  11678. thread t = thread([&] { svr.listen_after_bind(); });
  11679. auto se = detail::scope_exit([&] {
  11680. svr.stop();
  11681. t.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. svr.wait_until_ready();
  11685. {
  11686. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11687. SSLClient cli("localhost", port);
  11688. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11689. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11690. auto res = cli.Get("/sni");
  11691. ASSERT_FALSE(res);
  11692. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11693. }
  11694. // An IP host sends no SNI (RFC 6066)
  11695. SSLClient cli("127.0.0.1", port);
  11696. cli.enable_server_certificate_verification(false);
  11697. auto res = cli.Get("/sni");
  11698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11699. EXPECT_EQ("", res->body);
  11700. }
  11701. #endif
  11702. TEST(ClientProblemDetectionTest, ContentProvider) {
  11703. Server svr;
  11704. size_t content_length = 1024 * 1024;
  11705. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11706. res.set_content_provider(
  11707. content_length, "text/plain",
  11708. [&](size_t offset, size_t length, DataSink &sink) {
  11709. auto out_len = std::min(length, static_cast<size_t>(1024));
  11710. std::string out(out_len, '@');
  11711. sink.write(out.data(), out_len);
  11712. return offset < 4096;
  11713. },
  11714. [](bool success) { ASSERT_FALSE(success); });
  11715. });
  11716. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11717. res.set_content_provider(
  11718. 0, "text/plain",
  11719. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11720. EXPECT_TRUE(false);
  11721. return true;
  11722. },
  11723. [](bool success) { ASSERT_FALSE(success); });
  11724. });
  11725. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11726. auto se = detail::scope_exit([&] {
  11727. svr.stop();
  11728. listen_thread.join();
  11729. ASSERT_FALSE(svr.is_running());
  11730. });
  11731. svr.wait_until_ready();
  11732. Client cli("localhost", PORT);
  11733. {
  11734. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11735. size_t /*data_length*/) { return false; });
  11736. ASSERT_FALSE(res);
  11737. }
  11738. {
  11739. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11740. size_t /*data_length*/) { return false; });
  11741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11742. }
  11743. }
  11744. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11745. // A provider that reports success without writing anything and without
  11746. // calling done() used to be handed the same offset and length again on every
  11747. // pass, so it spun for as long as the peer stayed connected.
  11748. Server svr;
  11749. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11750. res.set_content("ok", "text/plain");
  11751. });
  11752. auto port = svr.bind_to_any_port(HOST);
  11753. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11754. auto se = detail::scope_exit([&] {
  11755. svr.stop();
  11756. listen_thread.join();
  11757. ASSERT_FALSE(svr.is_running());
  11758. });
  11759. svr.wait_until_ready();
  11760. std::atomic<int> call_count{0};
  11761. Client cli(HOST, port);
  11762. auto res = cli.Post(
  11763. "/", 1024,
  11764. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11765. // Give up after enough passes to show the spin, so that losing the
  11766. // check below fails this test instead of hanging it.
  11767. return ++call_count < 100;
  11768. },
  11769. "text/plain");
  11770. ASSERT_FALSE(res);
  11771. EXPECT_EQ(Error::Write, res.error());
  11772. EXPECT_EQ(1, call_count.load());
  11773. }
  11774. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11775. // A writer only has to assign `write`. The other three used to be left as
  11776. // empty std::functions, so a provider calling one threw
  11777. // std::bad_function_call out of the thread running it and took the whole
  11778. // process down.
  11779. DataSink sink;
  11780. std::string written;
  11781. sink.write = [&](const char *data, size_t data_len) {
  11782. written.append(data, data_len);
  11783. return true;
  11784. };
  11785. EXPECT_TRUE(sink.is_writable());
  11786. sink.done();
  11787. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11788. EXPECT_TRUE(written.empty());
  11789. }
  11790. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11791. // A sink that cannot carry trailers still has to finish.
  11792. DataSink sink;
  11793. auto done_count = 0;
  11794. sink.done = [&]() { done_count++; };
  11795. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11796. EXPECT_EQ(1, done_count);
  11797. }
  11798. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11799. Server svr;
  11800. const std::string body(4096, 'x');
  11801. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11802. res.set_content_provider(body.size(), "text/plain",
  11803. [&](size_t offset, size_t length, DataSink &sink) {
  11804. sink.write(body.data() + offset, length);
  11805. sink.done();
  11806. return true;
  11807. });
  11808. });
  11809. auto port = svr.bind_to_any_port(HOST);
  11810. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11811. auto se = detail::scope_exit([&] {
  11812. svr.stop();
  11813. listen_thread.join();
  11814. ASSERT_FALSE(svr.is_running());
  11815. });
  11816. svr.wait_until_ready();
  11817. Client cli(HOST, port);
  11818. auto res = cli.Get("/");
  11819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11820. EXPECT_EQ(StatusCode::OK_200, res->status);
  11821. EXPECT_EQ(body, res->body);
  11822. }
  11823. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11824. Server svr;
  11825. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11826. res.set_content_provider(
  11827. 1024, "text/plain",
  11828. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11829. sink.write("hello", 5);
  11830. sink.done(); // short of the 1024 bytes the response promised
  11831. return true;
  11832. });
  11833. });
  11834. auto port = svr.bind_to_any_port(HOST);
  11835. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11836. auto se = detail::scope_exit([&] {
  11837. svr.stop();
  11838. listen_thread.join();
  11839. ASSERT_FALSE(svr.is_running());
  11840. });
  11841. svr.wait_until_ready();
  11842. Client cli(HOST, port);
  11843. cli.set_read_timeout(5, 0);
  11844. // The response is short of its Content-Length, so the client cannot read a
  11845. // complete body. What matters is that this returns at all: a no-op done()
  11846. // would leave the writer looping over a provider that never makes progress.
  11847. auto res = cli.Get("/");
  11848. EXPECT_FALSE(res);
  11849. }
  11850. // Read as the next response by a peer that sees it after a framed body.
  11851. static const std::string smuggled_response =
  11852. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11853. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11854. Server svr;
  11855. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11856. res.set_content_provider(
  11857. 5, "text/plain",
  11858. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11859. auto data = "AAAAA" + smuggled_response;
  11860. sink.write(data.data(), data.size());
  11861. return true;
  11862. });
  11863. });
  11864. thread t = thread([&] { svr.listen(HOST, PORT); });
  11865. auto se = detail::scope_exit([&] {
  11866. svr.stop();
  11867. t.join();
  11868. ASSERT_FALSE(svr.is_running());
  11869. });
  11870. svr.wait_until_ready();
  11871. std::string resp;
  11872. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11873. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11874. resp.clear();
  11875. ASSERT_TRUE(send_request(
  11876. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11877. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11878. }
  11879. TEST(NoContentTest, BodyIsNotSent) {
  11880. Server svr;
  11881. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11882. res.status = StatusCode::NoContent_204;
  11883. res.set_content(smuggled_response, "text/plain");
  11884. });
  11885. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11886. res.status = StatusCode::NotModified_304;
  11887. res.set_chunked_content_provider(
  11888. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11889. sink.write(smuggled_response.data(), smuggled_response.size());
  11890. sink.done();
  11891. return true;
  11892. });
  11893. });
  11894. thread t = thread([&] { svr.listen(HOST, PORT); });
  11895. auto se = detail::scope_exit([&] {
  11896. svr.stop();
  11897. t.join();
  11898. ASSERT_FALSE(svr.is_running());
  11899. });
  11900. svr.wait_until_ready();
  11901. for (auto path : {"/204", "/304"}) {
  11902. std::string resp;
  11903. ASSERT_TRUE(send_request(
  11904. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11905. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11906. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11907. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11908. }
  11909. }
  11910. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11911. Server svr;
  11912. std::atomic<bool> smuggled(false);
  11913. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11914. res.set_content("ok", "text/plain");
  11915. });
  11916. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11917. smuggled = true;
  11918. });
  11919. auto port = svr.bind_to_any_port(HOST);
  11920. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11921. auto se = detail::scope_exit([&] {
  11922. svr.stop();
  11923. listen_thread.join();
  11924. ASSERT_FALSE(svr.is_running());
  11925. });
  11926. svr.wait_until_ready();
  11927. // What follows the body would be read as the next request.
  11928. Client cli(HOST, port);
  11929. auto res = cli.Post(
  11930. "/", 5,
  11931. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11932. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11933. sink.write(data.data(), data.size());
  11934. return true;
  11935. },
  11936. "text/plain");
  11937. ASSERT_FALSE(res);
  11938. EXPECT_EQ(Error::Write, res.error());
  11939. EXPECT_FALSE(smuggled);
  11940. }
  11941. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11942. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11943. // The compressed path builds the whole body before connecting, so this
  11944. // fails client-side and never reaches a server.
  11945. Client cli(HOST, PORT);
  11946. cli.set_compress(true);
  11947. auto res = cli.Post(
  11948. "/", 1024,
  11949. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11950. sink.write("hello", 5);
  11951. sink.done(); // short of the 1024 bytes the request announced
  11952. return true;
  11953. },
  11954. "text/plain");
  11955. ASSERT_FALSE(res);
  11956. EXPECT_EQ(Error::Write, res.error());
  11957. }
  11958. #endif
  11959. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11960. Server svr;
  11961. svr.set_error_handler([](Request const &, Response &res) -> void {
  11962. res.set_chunked_content_provider(
  11963. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11964. sink.os << "hello";
  11965. sink.os << "world";
  11966. sink.done();
  11967. return true;
  11968. });
  11969. });
  11970. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  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("/");
  11979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11980. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11981. EXPECT_EQ("helloworld", res->body);
  11982. }
  11983. // A body set after a content provider must replace it, not be sent through it.
  11984. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11985. Server svr;
  11986. svr.set_mount_point("/", "./www");
  11987. svr.set_file_request_handler([](const Request &req, Response &res) {
  11988. if (req.path == "/dir/test.html") {
  11989. res.status = StatusCode::Forbidden_403;
  11990. res.set_content(std::string(5000, 'D'), "text/plain");
  11991. } else if (req.path == "/file") {
  11992. res.status = StatusCode::Forbidden_403;
  11993. res.body = "Denied";
  11994. }
  11995. });
  11996. auto port = svr.bind_to_any_port(HOST);
  11997. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11998. auto se = detail::scope_exit([&] {
  11999. svr.stop();
  12000. t.join();
  12001. ASSERT_FALSE(svr.is_running());
  12002. });
  12003. svr.wait_until_ready();
  12004. Client cli(HOST, port);
  12005. {
  12006. auto res = cli.Get("/dir/test.html");
  12007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12008. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12009. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12010. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12011. }
  12012. {
  12013. auto res = cli.Get("/file");
  12014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12015. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12016. EXPECT_EQ("Denied", res->body);
  12017. }
  12018. {
  12019. auto res = cli.Get("/dir/index.html");
  12020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12021. EXPECT_EQ(StatusCode::OK_200, res->status);
  12022. EXPECT_EQ(0U, res->body.find("<html>"));
  12023. }
  12024. }
  12025. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12026. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12027. Server svr;
  12028. std::vector<bool> released;
  12029. std::mutex released_mutex;
  12030. auto releaser = [&](bool success) {
  12031. std::lock_guard<std::mutex> guard(released_mutex);
  12032. released.push_back(success);
  12033. };
  12034. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12035. return sink.write(&"hello"[offset], length);
  12036. };
  12037. svr.Get("/sized", [&](const Request &, Response &res) {
  12038. res.status = StatusCode::NotFound_404;
  12039. res.set_content_provider(5, "text/plain", provider, releaser);
  12040. });
  12041. svr.Get("/chunked", [&](const Request &, Response &res) {
  12042. res.status = StatusCode::ServiceUnavailable_503;
  12043. res.set_chunked_content_provider(
  12044. "text/plain",
  12045. [](size_t, DataSink &sink) {
  12046. sink.os << "chunk";
  12047. sink.done();
  12048. return true;
  12049. },
  12050. releaser);
  12051. });
  12052. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12053. res.set_content_provider(5, "text/plain", provider, releaser);
  12054. throw std::runtime_error("after the provider");
  12055. });
  12056. svr.set_error_handler([](const Request &req, Response &res) {
  12057. // Leave the exception handler's content to it.
  12058. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12059. res.set_content(std::string(1000, 'E'), "text/html");
  12060. return Server::HandlerResponse::Handled;
  12061. });
  12062. svr.set_exception_handler(
  12063. [](const Request &, Response &res, std::exception_ptr) {
  12064. res.status = StatusCode::InternalServerError_500;
  12065. res.set_content(std::string(1000, 'X'), "text/html");
  12066. });
  12067. auto port = svr.bind_to_any_port(HOST);
  12068. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12069. auto se = detail::scope_exit([&] {
  12070. svr.stop();
  12071. t.join();
  12072. ASSERT_FALSE(svr.is_running());
  12073. });
  12074. svr.wait_until_ready();
  12075. Client cli(HOST, port);
  12076. {
  12077. auto res = cli.Get("/sized");
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12080. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12081. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12082. }
  12083. {
  12084. auto res = cli.Get("/chunked");
  12085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12086. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12087. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12088. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12089. }
  12090. {
  12091. auto res = cli.Get("/throw");
  12092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12093. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12094. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12095. }
  12096. std::lock_guard<std::mutex> guard(released_mutex);
  12097. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12098. }
  12099. #endif
  12100. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12101. Server svr;
  12102. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12103. return sink.write(&"abc"[offset], length);
  12104. };
  12105. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12106. res.set_file_content("./www/dir/test.html");
  12107. res.set_content("body", "text/plain");
  12108. });
  12109. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12110. res.set_content(std::string(100, 'B'), "text/plain");
  12111. res.set_file_content("./www/dir/test.html");
  12112. });
  12113. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12114. res.set_content(std::string(100, 'B'), "text/plain");
  12115. res.set_content_provider(3, "text/x-provider", abc);
  12116. });
  12117. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12118. res.set_content_provider(3, "text/x-provider", abc);
  12119. res.set_content(std::string(100, 'B'), "text/plain");
  12120. });
  12121. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12122. res.set_content_provider(3, "text/x-provider", abc);
  12123. res.set_file_content("./www/dir/test.html", "text/x-file");
  12124. });
  12125. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12126. res.set_file_content("./www/dir/test.html");
  12127. res.set_header("Content-Type", "text/x-handler");
  12128. });
  12129. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12130. res.set_content_provider(3, "text/plain", abc);
  12131. res.body = "direct";
  12132. });
  12133. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12134. res.set_file_content("./www/dir/test.html");
  12135. res.body = "direct";
  12136. });
  12137. auto port = svr.bind_to_any_port(HOST);
  12138. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12139. auto se = detail::scope_exit([&] {
  12140. svr.stop();
  12141. t.join();
  12142. ASSERT_FALSE(svr.is_running());
  12143. });
  12144. svr.wait_until_ready();
  12145. Client cli(HOST, port);
  12146. auto expect_body = [&](const char *path, const std::string &body,
  12147. const std::string &type) {
  12148. // Uncompressed, so Content-Length can be compared with the body.
  12149. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12150. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12151. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12152. EXPECT_EQ(body, res->body) << path;
  12153. EXPECT_EQ(std::to_string(body.size()),
  12154. res->get_header_value("Content-Length"))
  12155. << path;
  12156. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12157. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12158. };
  12159. expect_body("/file-then-body", "body", "text/plain");
  12160. expect_body("/body-then-file", "test.html", "text/html");
  12161. expect_body("/body-then-provider", "abc", "text/x-provider");
  12162. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12163. expect_body("/provider-then-file", "test.html", "text/x-file");
  12164. expect_body("/file-then-header", "test.html", "text/x-handler");
  12165. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12166. expect_body("/file-then-direct-body", "direct", "text/plain");
  12167. // Ranges are checked against the body, not the dropped provider.
  12168. {
  12169. auto res = cli.Get("/provider-then-direct-body",
  12170. Headers{{make_range_header({{1, 2}})}});
  12171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12172. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12173. EXPECT_EQ("ir", res->body);
  12174. }
  12175. {
  12176. auto res = cli.Get("/file-then-direct-body",
  12177. Headers{{make_range_header({{7, 8}})}});
  12178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12179. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12180. }
  12181. }
  12182. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12183. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12184. const char *path = "./truncated_while_served.txt";
  12185. const size_t size = 32 * 1024 * 1024;
  12186. {
  12187. std::ofstream f(path, std::ios::binary);
  12188. f << std::string(size, 'x');
  12189. }
  12190. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12191. // Over TLS, where the bytes are encrypted in this process rather than
  12192. // copied by send().
  12193. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12194. svr.Get("/file", [&](const Request &, Response &res) {
  12195. res.set_file_content(path, "text/plain");
  12196. });
  12197. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12198. auto se = detail::scope_exit([&] {
  12199. svr.stop();
  12200. thread.join();
  12201. ASSERT_FALSE(svr.is_running());
  12202. });
  12203. svr.wait_until_ready();
  12204. // The file shrinks once the first bytes are in, as a rewrite in place
  12205. // would, and reading the mapping past its new end used to raise SIGBUS.
  12206. SSLClient cli(HOST, PORT);
  12207. cli.enable_server_certificate_verification(false);
  12208. size_t received = 0;
  12209. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12210. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12211. received += len;
  12212. return true;
  12213. });
  12214. EXPECT_FALSE(res);
  12215. EXPECT_LT(received, size);
  12216. }
  12217. #endif
  12218. // Forward declaration (see the base64_encode note).
  12219. namespace httplib {
  12220. namespace detail {
  12221. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12222. const std::string &content_type,
  12223. EncodingType encoding);
  12224. } // namespace detail
  12225. } // namespace httplib
  12226. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12227. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12228. ASSERT_TRUE(mm->is_open());
  12229. Response res;
  12230. detail::set_file_content_provider(res, mm, "text/html",
  12231. detail::EncodingType::None);
  12232. std::string out;
  12233. DataSink sink;
  12234. sink.write = [&](const char *d, size_t l) {
  12235. out.append(d, l);
  12236. return true;
  12237. };
  12238. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12239. EXPECT_EQ("test.html", out);
  12240. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12241. EXPECT_EQ("test.html", out);
  12242. }
  12243. TEST(LongPollingTest, ClientCloseDetection) {
  12244. Server svr;
  12245. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12246. res.set_chunked_content_provider(
  12247. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12248. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12249. sink.os << "hello";
  12250. auto count = 10;
  12251. while (count > 0 && sink.is_writable()) {
  12252. this_thread::sleep_for(chrono::milliseconds(10));
  12253. count--;
  12254. }
  12255. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12256. return true;
  12257. });
  12258. });
  12259. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12260. auto se = detail::scope_exit([&] {
  12261. svr.stop();
  12262. listen_thread.join();
  12263. ASSERT_FALSE(svr.is_running());
  12264. });
  12265. svr.wait_until_ready();
  12266. Client cli("localhost", PORT);
  12267. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12268. EXPECT_EQ("hello", string(data, data_length));
  12269. return false; // close the socket immediately.
  12270. });
  12271. ASSERT_FALSE(res);
  12272. }
  12273. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12274. Server svr;
  12275. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12276. res.set_chunked_content_provider(
  12277. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12278. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12279. sink.os << "hello";
  12280. EXPECT_TRUE(sink.os.good());
  12281. // Wait for the client to close the connection
  12282. auto count = 10;
  12283. while (count > 0 && sink.is_writable()) {
  12284. this_thread::sleep_for(chrono::milliseconds(10));
  12285. count--;
  12286. }
  12287. // After client disconnect, write repeatedly until the socket
  12288. // write actually fails (small writes may be absorbed by the
  12289. // kernel buffer)
  12290. std::string chunk(1024, 'x');
  12291. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12292. sink.os << chunk;
  12293. }
  12294. EXPECT_TRUE(sink.os.fail());
  12295. return true;
  12296. });
  12297. });
  12298. auto port = svr.bind_to_any_port("localhost");
  12299. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12300. auto se = detail::scope_exit([&] {
  12301. svr.stop();
  12302. listen_thread.join();
  12303. ASSERT_FALSE(svr.is_running());
  12304. });
  12305. svr.wait_until_ready();
  12306. Client cli("localhost", port);
  12307. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12308. EXPECT_EQ("hello", string(data, data_length));
  12309. return false; // close the socket immediately.
  12310. });
  12311. ASSERT_FALSE(res);
  12312. }
  12313. TEST(GetWithParametersTest, GetWithParameters) {
  12314. Server svr;
  12315. svr.Get("/", [&](const Request &req, Response &) {
  12316. EXPECT_EQ("world", req.get_param_value("hello"));
  12317. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12318. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12319. });
  12320. svr.Get("/params", [&](const Request &req, Response &) {
  12321. EXPECT_EQ("world", req.get_param_value("hello"));
  12322. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12323. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12324. });
  12325. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12326. EXPECT_EQ("resource-id", req.matches[1]);
  12327. EXPECT_EQ("foo", req.get_param_value("param1"));
  12328. EXPECT_EQ("bar", req.get_param_value("param2"));
  12329. });
  12330. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12331. EXPECT_EQ("user-id", req.path_params.at("id"));
  12332. EXPECT_EQ("foo", req.get_param_value("param1"));
  12333. EXPECT_EQ("bar", req.get_param_value("param2"));
  12334. });
  12335. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. listen_thread.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. });
  12341. svr.wait_until_ready();
  12342. {
  12343. Client cli(HOST, PORT);
  12344. Params params;
  12345. params.emplace("hello", "world");
  12346. params.emplace("hello2", "world2");
  12347. params.emplace("hello3", "world3");
  12348. auto res = cli.Get("/", params, Headers{});
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::OK_200, res->status);
  12351. }
  12352. {
  12353. Client cli(HOST, PORT);
  12354. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12356. EXPECT_EQ(StatusCode::OK_200, res->status);
  12357. }
  12358. {
  12359. Client cli(HOST, PORT);
  12360. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12362. EXPECT_EQ(StatusCode::OK_200, res->status);
  12363. }
  12364. {
  12365. Client cli(HOST, PORT);
  12366. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12368. EXPECT_EQ(StatusCode::OK_200, res->status);
  12369. }
  12370. }
  12371. TEST(GetWithParametersTest, GetWithParameters2) {
  12372. Server svr;
  12373. svr.Get("/", [&](const Request &req, Response &res) {
  12374. auto text = req.get_param_value("hello");
  12375. res.set_content(text, "text/plain");
  12376. });
  12377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12378. auto se = detail::scope_exit([&] {
  12379. svr.stop();
  12380. listen_thread.join();
  12381. ASSERT_FALSE(svr.is_running());
  12382. });
  12383. svr.wait_until_ready();
  12384. Client cli("localhost", PORT);
  12385. Params params;
  12386. params.emplace("hello", "world");
  12387. std::string body;
  12388. auto res = cli.Get("/", params, Headers{},
  12389. [&](const char *data, size_t data_length) {
  12390. body.append(data, data_length);
  12391. return true;
  12392. });
  12393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12394. EXPECT_EQ(StatusCode::OK_200, res->status);
  12395. EXPECT_EQ("world", body);
  12396. }
  12397. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12398. Server svr;
  12399. svr.Get("/search", [&](const Request &req, Response &res) {
  12400. auto q = req.get_param_value("q");
  12401. res.set_content(q, "text/plain");
  12402. });
  12403. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12404. auto se = detail::scope_exit([&] {
  12405. svr.stop();
  12406. listen_thread.join();
  12407. ASSERT_FALSE(svr.is_running());
  12408. });
  12409. svr.wait_until_ready();
  12410. Client cli("localhost", PORT);
  12411. // Verify that Get(path, params) works without requiring Headers argument
  12412. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12414. EXPECT_EQ(StatusCode::OK_200, res->status);
  12415. EXPECT_EQ("cpp-httplib", res->body);
  12416. }
  12417. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12418. auto host = "httpbingo.org";
  12419. auto path = std::string{"/range/32"};
  12420. #ifdef CPPHTTPLIB_SSL_ENABLED
  12421. SSLClient cli(host);
  12422. #else
  12423. Client cli(host);
  12424. #endif
  12425. cli.set_default_headers({make_range_header({{1, 10}})});
  12426. cli.set_connection_timeout(5);
  12427. {
  12428. auto res = cli.Get(path);
  12429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12430. EXPECT_EQ("bcdefghijk", res->body);
  12431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12432. }
  12433. {
  12434. auto res = cli.Get(path);
  12435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12436. EXPECT_EQ("bcdefghijk", res->body);
  12437. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12438. }
  12439. }
  12440. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12441. Server svr;
  12442. svr.set_default_headers({{"Hello", "World"}});
  12443. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12444. res.set_content("ok", "text/plain");
  12445. });
  12446. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12447. auto se = detail::scope_exit([&] {
  12448. svr.stop();
  12449. listen_thread.join();
  12450. ASSERT_FALSE(svr.is_running());
  12451. });
  12452. svr.wait_until_ready();
  12453. Client cli("localhost", PORT);
  12454. auto res = cli.Get("/");
  12455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12456. EXPECT_EQ(StatusCode::OK_200, res->status);
  12457. EXPECT_EQ("ok", res->body);
  12458. EXPECT_EQ("World", res->get_header_value("Hello"));
  12459. }
  12460. #ifdef CPPHTTPLIB_SSL_ENABLED
  12461. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12463. ASSERT_TRUE(svr.is_valid());
  12464. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12465. std::this_thread::sleep_for(std::chrono::seconds(2));
  12466. res.set_content("a", "text/plain");
  12467. });
  12468. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12469. res.set_content("b", "text/plain");
  12470. });
  12471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12472. auto se = detail::scope_exit([&] {
  12473. svr.stop();
  12474. listen_thread.join();
  12475. ASSERT_FALSE(svr.is_running());
  12476. });
  12477. svr.wait_until_ready();
  12478. SSLClient cli("localhost", PORT);
  12479. cli.enable_server_certificate_verification(false);
  12480. cli.set_keep_alive(true);
  12481. cli.set_read_timeout(std::chrono::seconds(1));
  12482. auto resa = cli.Get("/a");
  12483. ASSERT_TRUE(!resa);
  12484. EXPECT_EQ(Error::Read, resa.error());
  12485. auto resb = cli.Get("/b");
  12486. ASSERT_TRUE(resb);
  12487. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12488. EXPECT_EQ("b", resb->body);
  12489. }
  12490. // Closing an idle keep-alive connection sends close_notify and returns. The
  12491. // server must not wait for the client's close_notify: an idle client never
  12492. // sends one, so the worker would be held until the read timeout expires, and
  12493. // stop() would wait for it.
  12494. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12496. ASSERT_TRUE(svr.is_valid());
  12497. svr.set_keep_alive_timeout(1);
  12498. svr.set_read_timeout(10, 0);
  12499. svr.Get("/", [](const Request &, Response &res) {
  12500. res.set_content("ok", "text/plain");
  12501. });
  12502. auto port = svr.bind_to_any_port(HOST);
  12503. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12504. auto se = detail::scope_exit([&] {
  12505. if (listen_thread.joinable()) {
  12506. svr.stop();
  12507. listen_thread.join();
  12508. }
  12509. });
  12510. svr.wait_until_ready();
  12511. SSLClient cli(HOST, port);
  12512. cli.enable_server_certificate_verification(false);
  12513. cli.set_keep_alive(true);
  12514. auto res = cli.Get("/");
  12515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12516. EXPECT_EQ(StatusCode::OK_200, res->status);
  12517. // Stay idle past the keep-alive timeout so the server closes the connection.
  12518. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12519. auto start = std::chrono::steady_clock::now();
  12520. svr.stop();
  12521. listen_thread.join();
  12522. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12523. std::chrono::steady_clock::now() - start)
  12524. .count();
  12525. EXPECT_LT(elapsed, 3000);
  12526. }
  12527. #endif
  12528. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12529. protected:
  12530. ServerTestWithAI_PASSIVE()
  12531. : cli_(HOST, PORT)
  12532. #ifdef CPPHTTPLIB_SSL_ENABLED
  12533. ,
  12534. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12535. #endif
  12536. {
  12537. #ifdef CPPHTTPLIB_SSL_ENABLED
  12538. cli_.enable_server_certificate_verification(false);
  12539. #endif
  12540. }
  12541. virtual void SetUp() {
  12542. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12543. res.set_content("Hello World!", "text/plain");
  12544. });
  12545. t_ = thread(
  12546. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12547. svr_.wait_until_ready();
  12548. }
  12549. virtual void TearDown() {
  12550. svr_.stop();
  12551. t_.join();
  12552. }
  12553. #ifdef CPPHTTPLIB_SSL_ENABLED
  12554. SSLClient cli_;
  12555. SSLServer svr_;
  12556. #else
  12557. Client cli_;
  12558. Server svr_;
  12559. #endif
  12560. thread t_;
  12561. };
  12562. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12563. auto res = cli_.Get("/hi");
  12564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12565. EXPECT_EQ(StatusCode::OK_200, res->status);
  12566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12567. EXPECT_EQ("Hello World!", res->body);
  12568. }
  12569. class ServerUpDownTest : public ::testing::Test {
  12570. protected:
  12571. ServerUpDownTest() : cli_(HOST, PORT) {}
  12572. virtual void SetUp() {
  12573. t_ = thread([&]() {
  12574. svr_.bind_to_any_port(HOST);
  12575. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12576. ASSERT_TRUE(svr_.listen_after_bind());
  12577. });
  12578. svr_.wait_until_ready();
  12579. }
  12580. virtual void TearDown() {
  12581. svr_.stop();
  12582. t_.join();
  12583. }
  12584. Client cli_;
  12585. Server svr_;
  12586. thread t_;
  12587. };
  12588. TEST_F(ServerUpDownTest, QuickStartStop) {
  12589. // Should not crash, especially when run with
  12590. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12591. }
  12592. class PayloadMaxLengthTest : public ::testing::Test {
  12593. protected:
  12594. PayloadMaxLengthTest()
  12595. : cli_(HOST, PORT)
  12596. #ifdef CPPHTTPLIB_SSL_ENABLED
  12597. ,
  12598. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12599. #endif
  12600. {
  12601. #ifdef CPPHTTPLIB_SSL_ENABLED
  12602. cli_.enable_server_certificate_verification(false);
  12603. #endif
  12604. }
  12605. virtual void SetUp() {
  12606. svr_.set_payload_max_length(8);
  12607. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12608. res.set_content("test", "text/plain");
  12609. });
  12610. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12611. svr_.wait_until_ready();
  12612. }
  12613. virtual void TearDown() {
  12614. svr_.stop();
  12615. t_.join();
  12616. }
  12617. #ifdef CPPHTTPLIB_SSL_ENABLED
  12618. SSLClient cli_;
  12619. SSLServer svr_;
  12620. #else
  12621. Client cli_;
  12622. Server svr_;
  12623. #endif
  12624. thread t_;
  12625. };
  12626. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12627. auto res = cli_.Post("/test", "123456789", "text/plain");
  12628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12629. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12630. res = cli_.Post("/test", "12345678", "text/plain");
  12631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12632. EXPECT_EQ(StatusCode::OK_200, res->status);
  12633. }
  12634. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12635. // Test chunked encoding with payload exceeding the 8-byte limit
  12636. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12637. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12639. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12640. }
  12641. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12642. // Test chunked encoding with payload within the 8-byte limit
  12643. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12644. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12646. EXPECT_EQ(StatusCode::OK_200, res->status);
  12647. }
  12648. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12649. // Test using send_request to send chunked data exceeding payload limit
  12650. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12651. "Host: " +
  12652. std::string(HOST) + ":" + std::to_string(PORT) +
  12653. "\r\n"
  12654. "Transfer-Encoding: chunked\r\n"
  12655. "Connection: close\r\n"
  12656. "\r\n"
  12657. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12658. "0123456789\r\n"
  12659. "0\r\n" // End chunk
  12660. "\r\n";
  12661. std::string response;
  12662. bool result = send_request(1, chunked_request, &response);
  12663. if (!result) {
  12664. // If send_request fails, it might be because the server closed the
  12665. // connection due to payload limit enforcement, which is acceptable
  12666. SUCCEED()
  12667. << "Server rejected oversized chunked request (connection closed)";
  12668. } else {
  12669. // If we got a response, check if it's an error response or connection was
  12670. // closed early Short response length indicates connection was closed due to
  12671. // payload limit
  12672. if (response.length() <= 10) {
  12673. SUCCEED() << "Server closed connection for oversized chunked request";
  12674. } else {
  12675. // Check for error status codes
  12676. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12677. response.find("Payload Too Large") != std::string::npos ||
  12678. response.find("400") != std::string::npos);
  12679. }
  12680. }
  12681. }
  12682. class LargePayloadMaxLengthTest : public ::testing::Test {
  12683. protected:
  12684. LargePayloadMaxLengthTest()
  12685. : cli_(HOST, PORT)
  12686. #ifdef CPPHTTPLIB_SSL_ENABLED
  12687. ,
  12688. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12689. #endif
  12690. {
  12691. #ifdef CPPHTTPLIB_SSL_ENABLED
  12692. cli_.enable_server_certificate_verification(false);
  12693. #endif
  12694. }
  12695. virtual void SetUp() {
  12696. // Set 10MB payload limit
  12697. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12698. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12699. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12700. res.set_content("Large payload test", "text/plain");
  12701. });
  12702. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12703. svr_.wait_until_ready();
  12704. }
  12705. virtual void TearDown() {
  12706. svr_.stop();
  12707. t_.join();
  12708. }
  12709. #ifdef CPPHTTPLIB_SSL_ENABLED
  12710. SSLClient cli_;
  12711. SSLServer svr_;
  12712. #else
  12713. Client cli_;
  12714. Server svr_;
  12715. #endif
  12716. thread t_;
  12717. };
  12718. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12719. // Test chunked encoding with payload within 10MB limit
  12720. std::string medium_payload(5 * 1024 * 1024,
  12721. 'A'); // 5MB payload, within 10MB limit
  12722. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12724. EXPECT_EQ(StatusCode::OK_200, res->status);
  12725. }
  12726. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12727. // Test chunked encoding with payload exceeding 10MB limit
  12728. std::string large_payload(12 * 1024 * 1024,
  12729. 'B'); // 12MB payload, exceeds 10MB limit
  12730. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12731. // Server may either return 413 or close the connection
  12732. if (res) {
  12733. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12734. } else {
  12735. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12736. }
  12737. }
  12738. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12739. Server svr;
  12740. svr.Get("/", [](const Request &, Response &res) {
  12741. // Claims the most the client accepts, far more than it sends, then drops
  12742. // the connection.
  12743. res.set_content_provider(std::string().max_size(), "text/plain",
  12744. [](size_t, size_t, DataSink &sink) {
  12745. sink.write("abc", 3);
  12746. return false;
  12747. });
  12748. });
  12749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12750. auto se = detail::scope_exit([&] {
  12751. svr.stop();
  12752. thread.join();
  12753. ASSERT_FALSE(svr.is_running());
  12754. });
  12755. svr.wait_until_ready();
  12756. Client cli(HOST, PORT);
  12757. cli.set_payload_max_length(0);
  12758. EXPECT_FALSE(cli.Get("/"));
  12759. }
  12760. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12761. // Stream API does, not as a plain read failure
  12762. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12763. Server svr;
  12764. svr.Get("/big", [](const Request &, Response &res) {
  12765. res.set_content(std::string(100000, 'b'), "text/plain");
  12766. });
  12767. auto port = svr.bind_to_any_port(HOST);
  12768. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12769. auto se = detail::scope_exit([&] {
  12770. svr.stop();
  12771. thread.join();
  12772. });
  12773. svr.wait_until_ready();
  12774. Client cli(HOST, port);
  12775. cli.set_payload_max_length(1000);
  12776. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12777. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12778. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12779. [](const char *, size_t) { return true; });
  12780. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12781. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12782. // Small on the wire, over the limit once decompressed
  12783. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12784. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12785. #endif
  12786. }
  12787. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12788. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12789. // path.
  12790. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12791. Server svr;
  12792. const size_t LIMIT = 64 * 1024; // 64KB
  12793. svr.set_payload_max_length(LIMIT);
  12794. size_t total = 0;
  12795. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12796. const ContentReader &content_reader) {
  12797. content_reader([&](const char * /*data*/, size_t len) {
  12798. total += len;
  12799. return true;
  12800. });
  12801. res.status = 200;
  12802. res.set_content("stream_ok", "text/plain");
  12803. });
  12804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12805. auto se = detail::scope_exit([&] {
  12806. svr.stop();
  12807. thread.join();
  12808. ASSERT_FALSE(svr.is_running());
  12809. });
  12810. svr.wait_until_ready();
  12811. // Prepare 256KB raw data and gzip-compress it
  12812. std::string raw(256 * 1024, 'A');
  12813. std::string gz;
  12814. {
  12815. z_stream zs{};
  12816. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12817. Z_DEFAULT_STRATEGY);
  12818. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12819. zs.avail_in = static_cast<uInt>(raw.size());
  12820. char outbuf[4096];
  12821. int ret;
  12822. do {
  12823. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12824. zs.avail_out = sizeof(outbuf);
  12825. ret = deflate(&zs, Z_FINISH);
  12826. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12827. } while (ret != Z_STREAM_END);
  12828. deflateEnd(&zs);
  12829. }
  12830. Client cli(HOST, PORT);
  12831. cli.set_connection_timeout(std::chrono::seconds(5));
  12832. Headers headers = {{"Content-Encoding", "gzip"}};
  12833. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12834. "application/octet-stream");
  12835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12836. // Server must reject oversized decompressed payloads with 413.
  12837. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12838. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12839. EXPECT_LE(total, LIMIT);
  12840. }
  12841. #endif
  12842. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12843. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12844. // the payload must be passed through untouched instead of being rejected.
  12845. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12846. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12847. Server svr;
  12848. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12849. res.set_content(body, "image/jpeg");
  12850. res.set_header("Content-Encoding", "UTF-8");
  12851. });
  12852. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12853. res.set_content(body, "image/jpeg");
  12854. res.set_header("Content-Encoding", "identity");
  12855. });
  12856. svr.Post("/echo", [](const Request &req, Response &res) {
  12857. res.set_content(req.body, "image/jpeg");
  12858. });
  12859. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12860. auto se = detail::scope_exit([&] {
  12861. svr.stop();
  12862. t.join();
  12863. ASSERT_FALSE(svr.is_running());
  12864. });
  12865. svr.wait_until_ready();
  12866. Client cli(HOST, PORT);
  12867. {
  12868. auto res = cli.Get("/image");
  12869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12870. EXPECT_EQ(StatusCode::OK_200, res->status);
  12871. EXPECT_EQ(body, res->body);
  12872. }
  12873. {
  12874. auto res = cli.Get("/identity");
  12875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12876. EXPECT_EQ(StatusCode::OK_200, res->status);
  12877. EXPECT_EQ(body, res->body);
  12878. }
  12879. {
  12880. // The same applies to a request body reaching the server.
  12881. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12882. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12884. EXPECT_EQ(StatusCode::OK_200, res->status);
  12885. EXPECT_EQ(body, res->body);
  12886. }
  12887. }
  12888. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12889. // gzip-encoded response even when the build has no zlib support.
  12890. static const char GZIPPED_HELLO_WORLD[] = {
  12891. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12892. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12893. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12894. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12895. // A content coding is a whole token, not something the field value merely
  12896. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12897. // as "fibre" look like Brotli, and turned a multi-coding value like
  12898. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12899. // it was never meant to see.
  12900. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12901. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12902. Server svr;
  12903. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12904. res.set_content(body, "image/jpeg");
  12905. res.set_header("Content-Encoding", "fibre");
  12906. });
  12907. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12908. res.set_content(body, "image/jpeg");
  12909. res.set_header("Content-Encoding", "gzip, br");
  12910. });
  12911. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12912. res.set_content(body, "image/jpeg");
  12913. res.set_header("Content-Encoding", "x-zstd-ish");
  12914. });
  12915. auto port = svr.bind_to_any_port(HOST);
  12916. thread t = thread([&]() { svr.listen_after_bind(); });
  12917. auto se = detail::scope_exit([&] {
  12918. svr.stop();
  12919. t.join();
  12920. ASSERT_FALSE(svr.is_running());
  12921. });
  12922. svr.wait_until_ready();
  12923. Client cli(HOST, port);
  12924. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12925. auto res = cli.Get(path);
  12926. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12927. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12928. // Not a coding we recognize, so the payload comes back untouched
  12929. EXPECT_EQ(body, res->body) << path;
  12930. }
  12931. }
  12932. // A content coding cpp-httplib recognizes but was not built with must be
  12933. // reported as such. Handing the still-compressed payload back to the caller
  12934. // would silently corrupt it.
  12935. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12936. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12937. Server svr;
  12938. // "image/jpeg" keeps the server from applying a content coding of its own,
  12939. // so the hand-crafted Content-Encoding below survives.
  12940. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12941. res.set_content(gzipped, "image/jpeg");
  12942. res.set_header("Content-Encoding", "gzip");
  12943. });
  12944. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12945. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12946. res.set_content(gzipped, "image/jpeg");
  12947. res.set_header("Content-Encoding", "GZIP");
  12948. });
  12949. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12950. auto se = detail::scope_exit([&] {
  12951. svr.stop();
  12952. t.join();
  12953. ASSERT_FALSE(svr.is_running());
  12954. });
  12955. svr.wait_until_ready();
  12956. Client cli(HOST, PORT);
  12957. {
  12958. auto res = cli.Get("/gzipped");
  12959. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12961. EXPECT_EQ("Hello World!", res->body);
  12962. #else
  12963. ASSERT_FALSE(res);
  12964. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12965. #endif
  12966. }
  12967. {
  12968. // open_stream() must behave the same way.
  12969. auto handle = cli.open_stream("GET", "/gzipped");
  12970. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12971. ASSERT_TRUE(handle.is_valid());
  12972. std::string received;
  12973. char buf[256];
  12974. ssize_t n;
  12975. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12976. received.append(buf, static_cast<size_t>(n));
  12977. }
  12978. EXPECT_EQ("Hello World!", received);
  12979. #else
  12980. EXPECT_FALSE(handle.is_valid());
  12981. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12982. #endif
  12983. }
  12984. {
  12985. // A differently-cased coding must not be mistaken for an unknown one, or
  12986. // the body would be handed back still compressed.
  12987. auto res = cli.Get("/gzipped-uppercase");
  12988. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12990. EXPECT_EQ("Hello World!", res->body);
  12991. #else
  12992. ASSERT_FALSE(res);
  12993. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12994. #endif
  12995. }
  12996. }
  12997. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12998. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12999. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13000. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13001. // body a second time and appending a second Content-Encoding field line, so
  13002. // clients that decode one coding per listed value handed back raw gzip bytes.
  13003. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13004. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13005. Server svr;
  13006. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13007. // keeps the server from applying a coding of its own.
  13008. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13009. res.set_content(gzipped, "text/plain");
  13010. res.set_header("Content-Encoding", "gzip");
  13011. });
  13012. auto port = svr.bind_to_any_port(HOST);
  13013. thread t = thread([&]() { svr.listen_after_bind(); });
  13014. auto se = detail::scope_exit([&] {
  13015. svr.stop();
  13016. t.join();
  13017. ASSERT_FALSE(svr.is_running());
  13018. });
  13019. svr.wait_until_ready();
  13020. Client cli(HOST, port);
  13021. Headers headers = {{"Accept-Encoding", "gzip"}};
  13022. auto res = cli.Get("/pre-gzipped", headers);
  13023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13024. EXPECT_EQ(StatusCode::OK_200, res->status);
  13025. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13026. EXPECT_EQ("Hello World!", res->body);
  13027. }
  13028. // set_compress(false) sends every handler response as it is, buffered or
  13029. // streamed
  13030. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13031. const std::string text(1000, 'a');
  13032. Server svr;
  13033. svr.set_compress(false);
  13034. svr.Get("/buffered", [&](const Request &, Response &res) {
  13035. res.set_content(text, "text/plain");
  13036. });
  13037. svr.Get("/streamed", [&](const Request &, Response &res) {
  13038. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13039. sink.write(text.data(), text.size());
  13040. sink.done();
  13041. return true;
  13042. });
  13043. });
  13044. auto port = svr.bind_to_any_port(HOST);
  13045. ASSERT_LT(0, port);
  13046. thread t = thread([&] { svr.listen_after_bind(); });
  13047. auto se = detail::scope_exit([&] {
  13048. svr.stop();
  13049. t.join();
  13050. ASSERT_FALSE(svr.is_running());
  13051. });
  13052. svr.wait_until_ready();
  13053. Client cli(HOST, port);
  13054. cli.set_decompress(false);
  13055. for (auto path : {"/buffered", "/streamed"}) {
  13056. SCOPED_TRACE(path);
  13057. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13059. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13060. EXPECT_EQ(text, res->body);
  13061. }
  13062. }
  13063. // A chunked provider settles its coding where the headers are written and
  13064. // reuses it at write time. Both ends of that have to hold: a handler's own
  13065. // Content-Encoding suppresses the coding, and a response without one is still
  13066. // compressed as it always was.
  13067. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13068. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13069. const std::string plain = "Hello World! Hello World! Hello World!";
  13070. Server svr;
  13071. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13072. res.set_header("Content-Encoding", "gzip");
  13073. res.set_chunked_content_provider(
  13074. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13075. sink.write(gzipped.data(), gzipped.size());
  13076. sink.done();
  13077. return true;
  13078. });
  13079. });
  13080. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13081. res.set_chunked_content_provider(
  13082. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13083. sink.write(plain.data(), plain.size());
  13084. sink.done();
  13085. return true;
  13086. });
  13087. });
  13088. auto port = svr.bind_to_any_port(HOST);
  13089. thread t = thread([&]() { svr.listen_after_bind(); });
  13090. auto se = detail::scope_exit([&] {
  13091. svr.stop();
  13092. t.join();
  13093. ASSERT_FALSE(svr.is_running());
  13094. });
  13095. svr.wait_until_ready();
  13096. Client cli(HOST, port);
  13097. Headers headers = {{"Accept-Encoding", "gzip"}};
  13098. {
  13099. auto res = cli.Get("/pre-gzipped", headers);
  13100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13101. EXPECT_EQ(StatusCode::OK_200, res->status);
  13102. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13103. EXPECT_EQ("Hello World!", res->body);
  13104. }
  13105. {
  13106. auto res = cli.Get("/negotiated", headers);
  13107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13108. EXPECT_EQ(StatusCode::OK_200, res->status);
  13109. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13110. EXPECT_EQ(plain, res->body);
  13111. }
  13112. }
  13113. #endif
  13114. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13115. // the same message as the comma-joined one, so both have to be read the same
  13116. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13117. // single gzip coding, and a body the sender says was encoded twice was handed
  13118. // back after one pass, still compressed but presented as decoded.
  13119. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13120. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13121. Server svr;
  13122. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13123. res.set_content(body, "image/jpeg");
  13124. res.headers.emplace("Content-Encoding", "gzip");
  13125. res.headers.emplace("Content-Encoding", "gzip");
  13126. });
  13127. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13128. res.set_content(body, "image/jpeg");
  13129. res.set_header("Content-Encoding", "gzip, gzip");
  13130. });
  13131. auto port = svr.bind_to_any_port(HOST);
  13132. thread t = thread([&]() { svr.listen_after_bind(); });
  13133. auto se = detail::scope_exit([&] {
  13134. svr.stop();
  13135. t.join();
  13136. ASSERT_FALSE(svr.is_running());
  13137. });
  13138. svr.wait_until_ready();
  13139. Client cli(HOST, port);
  13140. // Two codings is not something cpp-httplib decodes, so both representations
  13141. // take the pass-through path rather than one of them being gunzipped once.
  13142. for (const char *path : {"/split", "/joined"}) {
  13143. auto res = cli.Get(path);
  13144. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13145. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13146. EXPECT_EQ(body, res->body) << path;
  13147. }
  13148. }
  13149. // Regression test for DoS vulnerability: a malicious server sending a response
  13150. // without Content-Length header must not cause unbounded memory consumption on
  13151. // the client side. The client should stop reading after a reasonable limit,
  13152. // similar to the server-side set_payload_max_length protection.
  13153. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13154. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13155. #ifndef _WIN32
  13156. signal(SIGPIPE, SIG_IGN);
  13157. #endif
  13158. auto server_thread = std::thread([] {
  13159. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13160. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13161. default_socket_options(srv);
  13162. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13163. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13164. sockaddr_in addr{};
  13165. addr.sin_family = AF_INET;
  13166. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13167. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13168. int opt = 1;
  13169. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13170. #ifdef _WIN32
  13171. reinterpret_cast<const char *>(&opt),
  13172. #else
  13173. &opt,
  13174. #endif
  13175. sizeof(opt));
  13176. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13177. ::listen(srv, 1);
  13178. sockaddr_in cli_addr{};
  13179. socklen_t cli_len = sizeof(cli_addr);
  13180. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13181. if (cli != INVALID_SOCKET) {
  13182. char buf[4096];
  13183. ::recv(cli, buf, sizeof(buf), 0);
  13184. // Malicious response: no Content-Length, no chunked encoding
  13185. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13186. "Connection: close\r\n"
  13187. "\r\n";
  13188. ::send(cli,
  13189. #ifdef _WIN32
  13190. static_cast<const char *>(response_header.c_str()),
  13191. static_cast<int>(response_header.size()),
  13192. #else
  13193. response_header.c_str(), response_header.size(),
  13194. #endif
  13195. 0);
  13196. // Send 10MB of data
  13197. std::string chunk(64 * 1024, 'A');
  13198. size_t total_sent = 0;
  13199. while (total_sent < MALICIOUS_DATA_SIZE) {
  13200. auto to_send = std::min(chunk.size(), MALICIOUS_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_read = 0;
  13218. {
  13219. Client cli("127.0.0.1", PORT + 2);
  13220. cli.set_read_timeout(5, 0);
  13221. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13222. auto stream = cli.open_stream("GET", "/malicious");
  13223. ASSERT_TRUE(stream.is_valid());
  13224. char buffer[64 * 1024];
  13225. ssize_t n;
  13226. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13227. total_read += static_cast<size_t>(n);
  13228. }
  13229. } // StreamHandle and Client destroyed here, closing the socket
  13230. server_thread.join();
  13231. // With set_payload_max_length, the client must stop reading before consuming
  13232. // all 10MB. The read loop should be cut off at or near the configured limit.
  13233. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13234. << "Client read " << total_read << " bytes, exceeding the configured "
  13235. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13236. }
  13237. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13238. // the entire response body without truncation.
  13239. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13240. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13241. #ifndef _WIN32
  13242. signal(SIGPIPE, SIG_IGN);
  13243. #endif
  13244. auto server_thread = std::thread([] {
  13245. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13246. default_socket_options(srv);
  13247. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13248. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13249. sockaddr_in addr{};
  13250. addr.sin_family = AF_INET;
  13251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13252. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13253. int opt = 1;
  13254. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13255. #ifdef _WIN32
  13256. reinterpret_cast<const char *>(&opt),
  13257. #else
  13258. &opt,
  13259. #endif
  13260. sizeof(opt));
  13261. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13262. ::listen(srv, 1);
  13263. sockaddr_in cli_addr{};
  13264. socklen_t cli_len = sizeof(cli_addr);
  13265. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13266. if (cli != INVALID_SOCKET) {
  13267. char buf[4096];
  13268. ::recv(cli, buf, sizeof(buf), 0);
  13269. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13270. "Connection: close\r\n"
  13271. "\r\n";
  13272. ::send(cli,
  13273. #ifdef _WIN32
  13274. static_cast<const char *>(response_header.c_str()),
  13275. static_cast<int>(response_header.size()),
  13276. #else
  13277. response_header.c_str(), response_header.size(),
  13278. #endif
  13279. 0);
  13280. std::string chunk(64 * 1024, 'A');
  13281. size_t total_sent = 0;
  13282. while (total_sent < DATA_SIZE) {
  13283. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13284. auto sent = ::send(cli,
  13285. #ifdef _WIN32
  13286. static_cast<const char *>(chunk.c_str()),
  13287. static_cast<int>(to_send),
  13288. #else
  13289. chunk.c_str(), to_send,
  13290. #endif
  13291. 0);
  13292. if (sent <= 0) break;
  13293. total_sent += static_cast<size_t>(sent);
  13294. }
  13295. #ifdef _WIN32
  13296. ::shutdown(cli, SD_SEND);
  13297. #else
  13298. ::shutdown(cli, SHUT_WR);
  13299. #endif
  13300. // Drain until the client closes its end, ensuring all data is delivered
  13301. char drain[1024];
  13302. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13303. detail::close_socket(cli);
  13304. }
  13305. detail::close_socket(srv);
  13306. });
  13307. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13308. size_t total_read = 0;
  13309. {
  13310. Client cli("127.0.0.1", PORT + 2);
  13311. cli.set_read_timeout(5, 0);
  13312. cli.set_payload_max_length(0); // 0 means no limit
  13313. auto stream = cli.open_stream("GET", "/data");
  13314. ASSERT_TRUE(stream.is_valid());
  13315. char buffer[64 * 1024];
  13316. ssize_t n;
  13317. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13318. total_read += static_cast<size_t>(n);
  13319. }
  13320. }
  13321. server_thread.join();
  13322. EXPECT_EQ(total_read, DATA_SIZE)
  13323. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13324. << " bytes without truncation, but only read " << total_read << " bytes.";
  13325. }
  13326. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13327. // enormous Content-Length must not cause the client to pre-allocate a huge
  13328. // response body buffer. The reservation is capped at payload_max_length_, and
  13329. // the read itself fails when the body exceeds the limit.
  13330. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13331. #ifndef _WIN32
  13332. signal(SIGPIPE, SIG_IGN);
  13333. #endif
  13334. auto server_thread = std::thread([] {
  13335. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13336. default_socket_options(srv);
  13337. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13338. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13339. sockaddr_in addr{};
  13340. addr.sin_family = AF_INET;
  13341. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13342. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13343. int opt = 1;
  13344. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13345. #ifdef _WIN32
  13346. reinterpret_cast<const char *>(&opt),
  13347. #else
  13348. &opt,
  13349. #endif
  13350. sizeof(opt));
  13351. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13352. ::listen(srv, 1);
  13353. sockaddr_in cli_addr{};
  13354. socklen_t cli_len = sizeof(cli_addr);
  13355. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13356. if (cli != INVALID_SOCKET) {
  13357. char buf[4096];
  13358. ::recv(cli, buf, sizeof(buf), 0);
  13359. // Malicious response: claim a 20GB body but send only a tiny payload.
  13360. std::string response = "HTTP/1.1 200 OK\r\n"
  13361. "Content-Length: 20000000000\r\n"
  13362. "\r\n"
  13363. "abc";
  13364. ::send(cli,
  13365. #ifdef _WIN32
  13366. static_cast<const char *>(response.c_str()),
  13367. static_cast<int>(response.size()),
  13368. #else
  13369. response.c_str(), response.size(),
  13370. #endif
  13371. 0);
  13372. detail::close_socket(cli);
  13373. }
  13374. detail::close_socket(srv);
  13375. });
  13376. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13377. {
  13378. Client cli("127.0.0.1", PORT + 2);
  13379. cli.set_read_timeout(5, 0);
  13380. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13381. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13382. // (server claims more bytes than payload_max_length permits), but it must
  13383. // not exhaust memory before getting there.
  13384. auto res = cli.Get("/malicious");
  13385. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13386. }
  13387. server_thread.join();
  13388. }
  13389. // Verify that content_receiver bypasses the default payload_max_length,
  13390. // allowing streaming downloads larger than 100MB without requiring an explicit
  13391. // set_payload_max_length call.
  13392. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13393. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13394. #ifndef _WIN32
  13395. signal(SIGPIPE, SIG_IGN);
  13396. #endif
  13397. auto server_thread = std::thread([] {
  13398. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13399. default_socket_options(srv);
  13400. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13401. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13402. sockaddr_in addr{};
  13403. addr.sin_family = AF_INET;
  13404. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13405. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13406. int opt = 1;
  13407. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13408. #ifdef _WIN32
  13409. reinterpret_cast<const char *>(&opt),
  13410. #else
  13411. &opt,
  13412. #endif
  13413. sizeof(opt));
  13414. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13415. ::listen(srv, 1);
  13416. sockaddr_in cli_addr{};
  13417. socklen_t cli_len = sizeof(cli_addr);
  13418. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13419. if (cli != INVALID_SOCKET) {
  13420. char buf[4096];
  13421. ::recv(cli, buf, sizeof(buf), 0);
  13422. // Response with Content-Length larger than default 100MB limit
  13423. auto content_length = std::to_string(DATA_SIZE);
  13424. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13425. "Content-Length: " +
  13426. content_length +
  13427. "\r\n"
  13428. "Connection: close\r\n"
  13429. "\r\n";
  13430. ::send(cli,
  13431. #ifdef _WIN32
  13432. static_cast<const char *>(response_header.c_str()),
  13433. static_cast<int>(response_header.size()),
  13434. #else
  13435. response_header.c_str(), response_header.size(),
  13436. #endif
  13437. 0);
  13438. std::string chunk(64 * 1024, 'A');
  13439. size_t total_sent = 0;
  13440. while (total_sent < DATA_SIZE) {
  13441. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13442. auto sent = ::send(cli,
  13443. #ifdef _WIN32
  13444. static_cast<const char *>(chunk.c_str()),
  13445. static_cast<int>(to_send),
  13446. #else
  13447. chunk.c_str(), to_send,
  13448. #endif
  13449. 0);
  13450. if (sent <= 0) break;
  13451. total_sent += static_cast<size_t>(sent);
  13452. }
  13453. detail::close_socket(cli);
  13454. }
  13455. detail::close_socket(srv);
  13456. });
  13457. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13458. size_t total_received = 0;
  13459. {
  13460. Client cli("127.0.0.1", PORT + 2);
  13461. cli.set_read_timeout(10, 0);
  13462. // Do NOT call set_payload_max_length — use the default 100MB limit
  13463. auto res =
  13464. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13465. total_received += data_length;
  13466. return true;
  13467. });
  13468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13469. EXPECT_EQ(StatusCode::OK_200, res->status);
  13470. }
  13471. server_thread.join();
  13472. EXPECT_EQ(total_received, DATA_SIZE)
  13473. << "With content_receiver, the client should read all " << DATA_SIZE
  13474. << " bytes despite the default 100MB payload_max_length, but only read "
  13475. << total_received << " bytes.";
  13476. }
  13477. // Verify that an explicit set_payload_max_length smaller than the response is
  13478. // enforced even when a content_receiver is used.
  13479. TEST(ClientVulnerabilityTest,
  13480. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13481. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13482. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13483. #ifndef _WIN32
  13484. signal(SIGPIPE, SIG_IGN);
  13485. #endif
  13486. auto server_thread = std::thread([] {
  13487. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13488. default_socket_options(srv);
  13489. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13490. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13491. sockaddr_in addr{};
  13492. addr.sin_family = AF_INET;
  13493. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13494. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13495. int opt = 1;
  13496. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13497. #ifdef _WIN32
  13498. reinterpret_cast<const char *>(&opt),
  13499. #else
  13500. &opt,
  13501. #endif
  13502. sizeof(opt));
  13503. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13504. ::listen(srv, 1);
  13505. sockaddr_in cli_addr{};
  13506. socklen_t cli_len = sizeof(cli_addr);
  13507. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13508. if (cli != INVALID_SOCKET) {
  13509. char buf[4096];
  13510. ::recv(cli, buf, sizeof(buf), 0);
  13511. auto content_length = std::to_string(DATA_SIZE);
  13512. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13513. "Content-Length: " +
  13514. content_length +
  13515. "\r\n"
  13516. "Connection: close\r\n"
  13517. "\r\n";
  13518. ::send(cli,
  13519. #ifdef _WIN32
  13520. static_cast<const char *>(response_header.c_str()),
  13521. static_cast<int>(response_header.size()),
  13522. #else
  13523. response_header.c_str(), response_header.size(),
  13524. #endif
  13525. 0);
  13526. std::string chunk(64 * 1024, 'A');
  13527. size_t total_sent = 0;
  13528. while (total_sent < DATA_SIZE) {
  13529. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13530. auto sent = ::send(cli,
  13531. #ifdef _WIN32
  13532. static_cast<const char *>(chunk.c_str()),
  13533. static_cast<int>(to_send),
  13534. #else
  13535. chunk.c_str(), to_send,
  13536. #endif
  13537. 0);
  13538. if (sent <= 0) break;
  13539. total_sent += static_cast<size_t>(sent);
  13540. }
  13541. detail::close_socket(cli);
  13542. }
  13543. detail::close_socket(srv);
  13544. });
  13545. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13546. size_t total_received = 0;
  13547. {
  13548. Client cli("127.0.0.1", PORT + 2);
  13549. cli.set_read_timeout(10, 0);
  13550. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13551. auto res =
  13552. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13553. total_received += data_length;
  13554. return true;
  13555. });
  13556. // Should fail because 200MB exceeds the explicit 150MB limit
  13557. EXPECT_FALSE(res);
  13558. }
  13559. server_thread.join();
  13560. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13561. << "Client with content_receiver should respect the explicit "
  13562. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13563. << total_received << " bytes.";
  13564. }
  13565. // Verify that an explicit set_payload_max_length larger than the response
  13566. // allows the content_receiver to read all data successfully.
  13567. TEST(ClientVulnerabilityTest,
  13568. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13569. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13570. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13571. #ifndef _WIN32
  13572. signal(SIGPIPE, SIG_IGN);
  13573. #endif
  13574. auto server_thread = std::thread([] {
  13575. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13576. default_socket_options(srv);
  13577. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13578. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13579. sockaddr_in addr{};
  13580. addr.sin_family = AF_INET;
  13581. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13582. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13583. int opt = 1;
  13584. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13585. #ifdef _WIN32
  13586. reinterpret_cast<const char *>(&opt),
  13587. #else
  13588. &opt,
  13589. #endif
  13590. sizeof(opt));
  13591. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13592. ::listen(srv, 1);
  13593. sockaddr_in cli_addr{};
  13594. socklen_t cli_len = sizeof(cli_addr);
  13595. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13596. if (cli != INVALID_SOCKET) {
  13597. char buf[4096];
  13598. ::recv(cli, buf, sizeof(buf), 0);
  13599. auto content_length = std::to_string(DATA_SIZE);
  13600. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13601. "Content-Length: " +
  13602. content_length +
  13603. "\r\n"
  13604. "Connection: close\r\n"
  13605. "\r\n";
  13606. ::send(cli,
  13607. #ifdef _WIN32
  13608. static_cast<const char *>(response_header.c_str()),
  13609. static_cast<int>(response_header.size()),
  13610. #else
  13611. response_header.c_str(), response_header.size(),
  13612. #endif
  13613. 0);
  13614. std::string chunk(64 * 1024, 'A');
  13615. size_t total_sent = 0;
  13616. while (total_sent < DATA_SIZE) {
  13617. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13618. auto sent = ::send(cli,
  13619. #ifdef _WIN32
  13620. static_cast<const char *>(chunk.c_str()),
  13621. static_cast<int>(to_send),
  13622. #else
  13623. chunk.c_str(), to_send,
  13624. #endif
  13625. 0);
  13626. if (sent <= 0) break;
  13627. total_sent += static_cast<size_t>(sent);
  13628. }
  13629. #ifdef _WIN32
  13630. ::shutdown(cli, SD_SEND);
  13631. #else
  13632. ::shutdown(cli, SHUT_WR);
  13633. #endif
  13634. char drain[1024];
  13635. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13636. detail::close_socket(cli);
  13637. }
  13638. detail::close_socket(srv);
  13639. });
  13640. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13641. size_t total_received = 0;
  13642. {
  13643. Client cli("127.0.0.1", PORT + 2);
  13644. cli.set_read_timeout(10, 0);
  13645. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13646. auto res =
  13647. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13648. total_received += data_length;
  13649. return true;
  13650. });
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. EXPECT_EQ(StatusCode::OK_200, res->status);
  13653. }
  13654. server_thread.join();
  13655. EXPECT_EQ(total_received, DATA_SIZE)
  13656. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13657. << " bytes (larger than " << DATA_SIZE
  13658. << " bytes response), content_receiver should read all data, but only "
  13659. "read "
  13660. << total_received << " bytes.";
  13661. }
  13662. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13663. // Regression test for "zip bomb" attack on the client side: a malicious server
  13664. // sends a small gzip-compressed response that decompresses to a huge payload.
  13665. // The client must enforce payload_max_length on the decompressed size.
  13666. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13667. constexpr size_t DECOMPRESSED_SIZE =
  13668. 10 * 1024 * 1024; // 10MB after decompression
  13669. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13670. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13671. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13672. std::string compressed;
  13673. {
  13674. httplib::detail::gzip_compressor compressor;
  13675. bool ok =
  13676. compressor.compress(uncompressed.data(), uncompressed.size(),
  13677. /*last=*/true, [&](const char *buf, size_t len) {
  13678. compressed.append(buf, len);
  13679. return true;
  13680. });
  13681. ASSERT_TRUE(ok);
  13682. }
  13683. // Sanity: compressed data should be much smaller than the decompressed size
  13684. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13685. #ifndef _WIN32
  13686. signal(SIGPIPE, SIG_IGN);
  13687. #endif
  13688. // Set up the listening socket in the main thread so the server is guaranteed
  13689. // to be ready before the client connects (eliminates race condition).
  13690. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13691. default_socket_options(srv);
  13692. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13693. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13694. sockaddr_in addr{};
  13695. addr.sin_family = AF_INET;
  13696. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13697. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13698. int opt = 1;
  13699. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13700. #ifdef _WIN32
  13701. reinterpret_cast<const char *>(&opt),
  13702. #else
  13703. &opt,
  13704. #endif
  13705. sizeof(opt));
  13706. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13707. ASSERT_EQ(0, ::listen(srv, 1));
  13708. auto server_thread = std::thread([&compressed, srv] {
  13709. sockaddr_in cli_addr{};
  13710. socklen_t cli_len = sizeof(cli_addr);
  13711. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13712. if (cli != INVALID_SOCKET) {
  13713. // Read the full HTTP request (until \r\n\r\n)
  13714. char buf[4096];
  13715. size_t total = 0;
  13716. while (total < sizeof(buf)) {
  13717. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13718. if (n <= 0) break;
  13719. total += static_cast<size_t>(n);
  13720. // Check for end of headers
  13721. if (total >= 4) {
  13722. std::string req(buf, total);
  13723. if (req.find("\r\n\r\n") != std::string::npos) break;
  13724. }
  13725. }
  13726. // Malicious response: gzip-compressed body, no Content-Length
  13727. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13728. "Content-Encoding: gzip\r\n"
  13729. "Connection: close\r\n"
  13730. "\r\n";
  13731. ::send(cli,
  13732. #ifdef _WIN32
  13733. static_cast<const char *>(response_header.c_str()),
  13734. static_cast<int>(response_header.size()),
  13735. #else
  13736. response_header.c_str(), response_header.size(),
  13737. #endif
  13738. 0);
  13739. // Send the compressed payload (small on the wire, huge when decompressed)
  13740. size_t total_sent = 0;
  13741. while (total_sent < compressed.size()) {
  13742. auto to_send = std::min(compressed.size() - total_sent,
  13743. static_cast<size_t>(64 * 1024));
  13744. auto sent =
  13745. ::send(cli,
  13746. #ifdef _WIN32
  13747. static_cast<const char *>(compressed.c_str() + total_sent),
  13748. static_cast<int>(to_send),
  13749. #else
  13750. compressed.c_str() + total_sent, to_send,
  13751. #endif
  13752. 0);
  13753. if (sent <= 0) break;
  13754. total_sent += static_cast<size_t>(sent);
  13755. }
  13756. detail::close_socket(cli);
  13757. }
  13758. });
  13759. auto se = detail::scope_exit([&] {
  13760. detail::close_socket(srv);
  13761. server_thread.join();
  13762. });
  13763. size_t total_decompressed = 0;
  13764. {
  13765. Client cli("127.0.0.1", PORT + 3);
  13766. cli.set_read_timeout(5, 0);
  13767. cli.set_decompress(true);
  13768. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13769. auto stream = cli.open_stream("GET", "/zipbomb");
  13770. ASSERT_TRUE(stream.is_valid());
  13771. char buffer[64 * 1024];
  13772. ssize_t n;
  13773. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13774. total_decompressed += static_cast<size_t>(n);
  13775. }
  13776. }
  13777. // The decompressed size must be capped by payload_max_length. Without
  13778. // protection, the client would decompress the full 10MB from a tiny
  13779. // compressed payload, enabling a zip bomb DoS attack.
  13780. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13781. << "Client decompressed " << total_decompressed
  13782. << " bytes from a gzip response. The decompressed size should be "
  13783. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13784. }
  13785. #endif
  13786. TEST(HostAndPortPropertiesTest, NoSSL) {
  13787. httplib::Client cli("www.google.com", 1234);
  13788. ASSERT_EQ("www.google.com", cli.host());
  13789. ASSERT_EQ(1234, cli.port());
  13790. }
  13791. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13792. httplib::Client cli("www.google.com:1234");
  13793. ASSERT_EQ("www.google.com", cli.host());
  13794. ASSERT_EQ(1234, cli.port());
  13795. }
  13796. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13797. // Port number that overflows int — should not crash, client becomes invalid
  13798. httplib::Client cli("http://www.google.com:99999999999999999999");
  13799. ASSERT_FALSE(cli.is_valid());
  13800. }
  13801. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13802. // Port 99999 exceeds valid range (1-65535) — should not crash
  13803. httplib::Client cli("http://www.google.com:99999");
  13804. ASSERT_FALSE(cli.is_valid());
  13805. auto res = cli.Get("/");
  13806. EXPECT_FALSE(res);
  13807. EXPECT_EQ(Error::Connection, res.error());
  13808. }
  13809. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13810. httplib::Client cli("http://user:pass@localhost:1234");
  13811. ASSERT_FALSE(cli.is_valid());
  13812. EXPECT_FALSE(cli.Get("/"));
  13813. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13814. }
  13815. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13816. httplib::Client cli("http://www.google.com:80abc");
  13817. ASSERT_FALSE(cli.is_valid());
  13818. }
  13819. #ifdef CPPHTTPLIB_SSL_ENABLED
  13820. TEST(HostAndPortPropertiesTest, SSL) {
  13821. httplib::SSLClient cli("www.google.com");
  13822. ASSERT_EQ("www.google.com", cli.host());
  13823. ASSERT_EQ(443, cli.port());
  13824. }
  13825. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13826. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13827. std::string cert;
  13828. read_file(CA_CERT_FILE, cert);
  13829. httplib::SSLClient httplib_client("www.google.com");
  13830. // Load CA store first time
  13831. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13832. // Load CA store second time (update)
  13833. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13834. // Verify client is still valid and can make connections
  13835. httplib_client.enable_server_certificate_verification(true);
  13836. auto res = httplib_client.Get("/");
  13837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13838. // Google may return 200 or 301 depending on various factors
  13839. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13840. res->status == StatusCode::MovedPermanently_301);
  13841. }
  13842. TEST(SSLClientTest, ServerNameIndication_Online) {
  13843. auto host = "httpbingo.org";
  13844. auto path = std::string{"/get"};
  13845. SSLClient cli(host, 443);
  13846. auto res = cli.Get(path);
  13847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13848. ASSERT_EQ(StatusCode::OK_200, res->status);
  13849. }
  13850. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13851. // Use a site that will cause SSL verification failure due to self-signed cert
  13852. SSLClient cli("self-signed.badssl.com", 443);
  13853. cli.enable_server_certificate_verification(true);
  13854. auto res = cli.Get("/");
  13855. ASSERT_TRUE(!res);
  13856. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13857. // Verify backend error is captured for SSLServerVerification
  13858. // This occurs when certificate verification fails
  13859. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13860. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13861. EXPECT_NE(0UL, res.ssl_backend_error());
  13862. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13863. res.ssl_error());
  13864. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13865. #if !defined(_WIN32) || \
  13866. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13867. // On non-Windows or when Windows Schannel is disabled, the error comes
  13868. // from OpenSSL's verification
  13869. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13870. res.ssl_backend_error());
  13871. #endif
  13872. #endif
  13873. }
  13874. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13875. // Use a site where hostname doesn't match the certificate
  13876. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13877. SSLClient cli("wrong.host.badssl.com", 443);
  13878. cli.enable_server_certificate_verification(true);
  13879. cli.enable_server_hostname_verification(true);
  13880. auto res = cli.Get("/");
  13881. ASSERT_TRUE(!res);
  13882. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13883. // Verify backend error is captured for hostname verification failure
  13884. EXPECT_NE(0UL, res.ssl_backend_error());
  13885. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13886. res.ssl_error());
  13887. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13888. #if !defined(_WIN32) || \
  13889. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13890. // On non-Windows or when Windows Schannel is disabled, the error comes
  13891. // from OpenSSL's hostname verification
  13892. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13893. res.ssl_backend_error());
  13894. #endif
  13895. #endif
  13896. }
  13897. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13898. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13899. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13900. SSLClient cli("www.google.com", 443);
  13901. cli.enable_server_certificate_verification(true);
  13902. auto res = cli.Get("/");
  13903. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13904. }
  13905. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13906. SSLClient cli("www.google.com", 443);
  13907. cli.enable_server_certificate_verification(true);
  13908. cli.enable_windows_certificate_verification(false);
  13909. auto res = cli.Get("/");
  13910. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13911. }
  13912. // The server sends an intermediate cross-signed by a root Windows trusts,
  13913. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13914. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13915. SSLClient cli("accounts.spotify.com", 443);
  13916. auto res = cli.Get("/");
  13917. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13918. << " ssl_backend_error=" << res.ssl_backend_error();
  13919. }
  13920. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13921. // policy status, which no backend reports for a self-signed certificate.
  13922. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13923. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13924. ASSERT_TRUE(svr.is_valid());
  13925. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13926. auto se = detail::scope_exit([&] {
  13927. svr.stop();
  13928. t.join();
  13929. ASSERT_FALSE(svr.is_running());
  13930. });
  13931. svr.wait_until_ready();
  13932. SSLClient cli("127.0.0.1", PORT);
  13933. cli.set_connection_timeout(30);
  13934. auto res = cli.Get("/");
  13935. ASSERT_FALSE(res);
  13936. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13937. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13938. }
  13939. #endif
  13940. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13941. Client cli("https://google.com");
  13942. auto res = cli.Get("/");
  13943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13944. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13945. }
  13946. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13947. SSLClient cli("google.com");
  13948. cli.set_ca_cert_path(CA_CERT_FILE);
  13949. auto res = cli.Get("/");
  13950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13951. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13952. }
  13953. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13954. SSLClient cli("google.com");
  13955. cli.enable_server_certificate_verification(true);
  13956. cli.set_ca_cert_path("hello");
  13957. auto res = cli.Get("/");
  13958. ASSERT_TRUE(!res);
  13959. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13960. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13961. // should be set
  13962. EXPECT_EQ(0, res.ssl_error());
  13963. // Verify backend error is captured for SSLLoadingCerts
  13964. // This error occurs when loading CA certificates fails
  13965. EXPECT_NE(0UL, res.ssl_backend_error());
  13966. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13967. // OpenSSL specific error codes:
  13968. // > openssl errstr 0x80000002
  13969. // error:80000002:system library::No such file or directory
  13970. // > openssl errstr 0xA000126
  13971. // error:0A000126:SSL routines::unexpected eof while reading
  13972. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13973. res.ssl_backend_error() == 0xA000126);
  13974. #endif
  13975. }
  13976. TEST(SSLClientTest, ServerCertificateVerification4) {
  13977. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13978. ASSERT_TRUE(svr.is_valid());
  13979. svr.Get("/test", [&](const Request &, Response &res) {
  13980. res.set_content("test", "text/plain");
  13981. svr.stop();
  13982. ASSERT_TRUE(true);
  13983. });
  13984. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13985. auto se = detail::scope_exit([&] {
  13986. t.join();
  13987. ASSERT_FALSE(svr.is_running());
  13988. });
  13989. svr.wait_until_ready();
  13990. SSLClient cli("127.0.0.1", PORT);
  13991. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13992. cli.enable_server_certificate_verification(true);
  13993. cli.set_connection_timeout(30);
  13994. auto res = cli.Get("/test");
  13995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13996. ASSERT_EQ(StatusCode::OK_200, res->status);
  13997. }
  13998. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13999. std::string cert;
  14000. read_file(CA_CERT_FILE, cert);
  14001. SSLClient cli("google.com");
  14002. cli.load_ca_cert_store(cert.data(), cert.size());
  14003. const auto res = cli.Get("/");
  14004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14005. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14006. }
  14007. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14008. // clang-format off
  14009. static constexpr char cert[] =
  14010. "GlobalSign Root CA\n"
  14011. "==================\n"
  14012. "-----BEGIN CERTIFICATE-----\n"
  14013. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14014. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14015. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14016. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14017. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14018. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14019. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14020. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14021. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14022. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14023. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14024. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14025. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14026. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14027. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14028. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14029. "-----END CERTIFICATE-----\n";
  14030. // clang-format on
  14031. SSLClient cli("google.com");
  14032. cli.load_ca_cert_store(cert, sizeof(cert));
  14033. const auto res = cli.Get("/");
  14034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14035. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14036. }
  14037. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14038. SSLClient cli("www.youtube.com");
  14039. cli.set_ca_cert_path(CA_CERT_FILE);
  14040. cli.enable_server_certificate_verification(true);
  14041. cli.set_follow_location(true);
  14042. auto res = cli.Get("/");
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. ASSERT_EQ(StatusCode::OK_200, res->status);
  14045. }
  14046. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14047. SSLClient cli("wWw.YouTube.Com");
  14048. cli.set_ca_cert_path(CA_CERT_FILE);
  14049. cli.enable_server_certificate_verification(true);
  14050. cli.enable_server_hostname_verification(true);
  14051. cli.set_follow_location(true);
  14052. auto res = cli.Get("/");
  14053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14054. ASSERT_EQ(StatusCode::OK_200, res->status);
  14055. }
  14056. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14057. SSLClient cli("gOoGlE.COm");
  14058. cli.enable_server_certificate_verification(true);
  14059. cli.enable_server_hostname_verification(true);
  14060. cli.set_follow_location(true);
  14061. auto res = cli.Get("/");
  14062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14063. ASSERT_EQ(StatusCode::OK_200, res->status);
  14064. }
  14065. TEST(SSLClientTest, Issue2004_Online) {
  14066. Client client("https://google.com");
  14067. client.set_follow_location(true);
  14068. auto res = client.Get("/");
  14069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14070. ASSERT_EQ(StatusCode::OK_200, res->status);
  14071. auto body = res->body;
  14072. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14073. }
  14074. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14075. // Create SSLClient with invalid cert/key to make is_valid() return false
  14076. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14077. "nonexistent_key.pem");
  14078. // is_valid() should be false due to cert loading failure
  14079. ASSERT_FALSE(cli.is_valid());
  14080. auto res = cli.Get("/");
  14081. ASSERT_FALSE(res);
  14082. EXPECT_EQ(Error::SSLConnection, res.error());
  14083. }
  14084. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14085. // Test for Issue #2251: SSL error not properly reported when client cert
  14086. // and key paths are swapped or mismatched
  14087. // This simulates the scenario where user accidentally swaps the cert and key
  14088. // files
  14089. // Using client cert file as private key and vice versa (completely wrong)
  14090. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14091. // Should fail validation due to cert/key mismatch
  14092. ASSERT_FALSE(cli.is_valid());
  14093. // Attempt to make a request should fail with proper error
  14094. auto res = cli.Get("/");
  14095. ASSERT_FALSE(res);
  14096. EXPECT_EQ(Error::SSLConnection, res.error());
  14097. // SSL error should be recorded in the Result object (this is the key fix for
  14098. // Issue #2251)
  14099. auto backend_error = res.ssl_backend_error();
  14100. EXPECT_NE(0u, backend_error);
  14101. }
  14102. // Tests cert/key mismatch detection at the TLS context level
  14103. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14104. // Test that using mismatched cert/key causes connection failure.
  14105. // We verify this at the SSLClient level rather than through internal
  14106. // TLS API functions.
  14107. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14108. cli.enable_server_certificate_verification(false);
  14109. cli.set_connection_timeout(2);
  14110. // The mismatch should cause a connection or handshake error
  14111. auto res = cli.Get("/test");
  14112. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14113. // Either way, the request should fail
  14114. EXPECT_FALSE(res);
  14115. }
  14116. #endif
  14117. #if 0
  14118. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14119. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14120. ASSERT_TRUE(cli != nullptr);
  14121. cli->set_address_family(AF_INET6);
  14122. cli->set_interface("en0");
  14123. auto res = cli->Get("/get");
  14124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14125. ASSERT_EQ(StatusCode::OK_200, res->status);
  14126. }
  14127. #endif
  14128. // Client certificate tests - work with all TLS backends
  14129. #ifdef CPPHTTPLIB_SSL_ENABLED
  14130. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14131. void ClientCertPresent(
  14132. const std::string &client_cert_file,
  14133. const std::string &client_private_key_file,
  14134. const std::string &client_encrypted_private_key_pass = std::string(),
  14135. const ClientCertServerSetup &setup = nullptr) {
  14136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14137. ASSERT_TRUE(svr.is_valid());
  14138. if (setup) { setup(svr); }
  14139. svr.Get("/test", [&](const Request &req, Response &res) {
  14140. res.set_content("test", "text/plain");
  14141. auto cert = req.peer_cert();
  14142. ASSERT_TRUE(static_cast<bool>(cert));
  14143. std::string common_name = cert.subject_cn();
  14144. EXPECT_EQ("Common Name", common_name);
  14145. });
  14146. auto port = svr.bind_to_any_port(HOST);
  14147. ASSERT_LT(0, port);
  14148. thread t = thread([&]() { svr.listen_after_bind(); });
  14149. auto se = detail::scope_exit([&] {
  14150. svr.stop();
  14151. t.join();
  14152. ASSERT_FALSE(svr.is_running());
  14153. });
  14154. svr.wait_until_ready();
  14155. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14156. client_encrypted_private_key_pass);
  14157. cli.enable_server_certificate_verification(false);
  14158. cli.set_connection_timeout(30);
  14159. auto res = cli.Get("/test");
  14160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14161. ASSERT_EQ(StatusCode::OK_200, res->status);
  14162. }
  14163. TEST(SSLClientServerTest, ClientCertPresent) {
  14164. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14165. }
  14166. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14167. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14168. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14169. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14170. }
  14171. // Expects svr, which must require client certificates, to reject a client
  14172. // that has none
  14173. void RejectsClientWithoutCert(SSLServer &svr) {
  14174. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14175. auto port = svr.bind_to_any_port(HOST);
  14176. ASSERT_LT(0, port);
  14177. thread t = thread([&]() { svr.listen_after_bind(); });
  14178. auto se = detail::scope_exit([&] {
  14179. svr.stop();
  14180. t.join();
  14181. ASSERT_FALSE(svr.is_running());
  14182. });
  14183. svr.wait_until_ready();
  14184. SSLClient cli(HOST, port);
  14185. cli.set_connection_timeout(30);
  14186. // Skip the server certificate check, so that the request fails because the
  14187. // client certificate is missing rather than because cert.pem is not trusted
  14188. cli.enable_server_certificate_verification(false);
  14189. auto res = cli.Get("/test");
  14190. ASSERT_FALSE(res);
  14191. // The server rejects the client during the handshake, or on TLS 1.3 right
  14192. // after it, which the client notices on its first write or read
  14193. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14194. res.error() == Error::Write || res.error() == Error::Read)
  14195. << to_string(res.error());
  14196. if (res.error() == Error::SSLConnection) {
  14197. EXPECT_NE(0UL, res.ssl_backend_error());
  14198. }
  14199. // A rejection noticed on the write keeps the TLS error the write hit
  14200. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14201. }
  14202. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14204. ASSERT_TRUE(svr.is_valid());
  14205. if (setup) { setup(svr); }
  14206. RejectsClientWithoutCert(svr);
  14207. }
  14208. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14209. // A server that requires client certificates must keep requiring them after
  14210. // setup changes it, and keep accepting a client that has one
  14211. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14212. ClientCertMissing(setup);
  14213. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14214. setup);
  14215. }
  14216. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14217. ClientCertStillRequired([](SSLServer &svr) {
  14218. ASSERT_TRUE(tls::set_verify_callback(
  14219. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14220. });
  14221. }
  14222. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14223. ClientCertStillRequired([](SSLServer &svr) {
  14224. ASSERT_TRUE(tls::set_verify_callback(
  14225. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14226. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14227. });
  14228. }
  14229. // The client verifies the server certificate during the handshake, so a
  14230. // server that fails the check never gets the client certificate, even when a
  14231. // verifier of the client's own accepts it
  14232. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14233. struct Case {
  14234. const char *trusted_ca;
  14235. const char *host;
  14236. Error error;
  14237. };
  14238. // cert2.pem names localhost: the first client does not trust it, and the
  14239. // second trusts it but asks for another name
  14240. for (const auto &c :
  14241. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14242. Case{SERVER_CERT2_FILE, "example.com",
  14243. Error::SSLServerHostnameVerification}}) {
  14244. for (auto with_verifier : {false, true}) {
  14245. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14246. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14247. CLIENT_CA_CERT_FILE);
  14248. ASSERT_TRUE(svr.is_valid());
  14249. std::atomic<bool> got_client_cert{false};
  14250. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14251. [&](const tls::VerifyContext &) {
  14252. got_client_cert = true;
  14253. return true;
  14254. }));
  14255. auto port = svr.bind_to_any_port("127.0.0.1");
  14256. ASSERT_LT(0, port);
  14257. thread t = thread([&] { svr.listen_after_bind(); });
  14258. svr.wait_until_ready();
  14259. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14260. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14261. cli.set_ca_cert_path(c.trusted_ca);
  14262. if (with_verifier) {
  14263. cli.set_server_certificate_verifier(
  14264. [](const tls::VerifyContext &) { return true; });
  14265. }
  14266. auto res = cli.Get("/");
  14267. EXPECT_FALSE(res);
  14268. EXPECT_EQ(c.error, res.error());
  14269. svr.stop();
  14270. t.join();
  14271. EXPECT_FALSE(got_client_cert);
  14272. }
  14273. }
  14274. }
  14275. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14276. std::string cert_pem, key_pem, ca_pem;
  14277. read_file(SERVER_CERT_FILE, cert_pem);
  14278. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14279. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14280. ASSERT_TRUE(
  14281. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14282. }
  14283. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14285. ASSERT_TRUE(svr.is_valid());
  14286. UpdateCertsPemWithClientCA(svr);
  14287. RejectsClientWithoutCert(svr);
  14288. }
  14289. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14290. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14291. }
  14292. // A TLS error from one request must not show up in a later request's Result
  14293. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14295. ASSERT_TRUE(svr.is_valid());
  14296. svr.Get("/test", [](const Request &, Response &res) {
  14297. res.set_content("test", "text/plain");
  14298. });
  14299. auto port = svr.bind_to_any_port(HOST);
  14300. ASSERT_LT(0, port);
  14301. thread t = thread([&]() { svr.listen_after_bind(); });
  14302. auto se = detail::scope_exit([&] {
  14303. svr.stop();
  14304. t.join();
  14305. ASSERT_FALSE(svr.is_running());
  14306. });
  14307. svr.wait_until_ready();
  14308. SSLClient cli(HOST, port);
  14309. cli.set_connection_timeout(30);
  14310. cli.enable_server_hostname_verification(false);
  14311. // cert.pem is not trusted, so the handshake fails
  14312. ASSERT_FALSE(cli.Get("/test"));
  14313. cli.enable_server_certificate_verification(false);
  14314. auto res = cli.Get("/test");
  14315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14316. EXPECT_EQ(0, res.ssl_error());
  14317. EXPECT_EQ(0UL, res.ssl_backend_error());
  14318. }
  14319. // PEM memory-based constructor tests (works with all TLS backends).
  14320. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14321. // terminator after it.
  14322. void PemMemoryClientCertPresent(
  14323. const std::string &client_cert_file,
  14324. const std::string &client_private_key_file,
  14325. const std::string &client_encrypted_private_key_pass = std::string(),
  14326. bool exact_size = false) {
  14327. // Read PEM files into memory
  14328. std::string server_cert_pem, server_key_pem;
  14329. std::string client_ca_pem;
  14330. std::string client_cert_pem, client_key_pem;
  14331. read_file(SERVER_CERT_FILE, server_cert_pem);
  14332. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14333. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14334. read_file(client_cert_file, client_cert_pem);
  14335. read_file(client_private_key_file, client_key_pem);
  14336. std::list<std::vector<char>> exact_copies;
  14337. auto data = [&](const std::string &pem) -> const char * {
  14338. if (!exact_size) { return pem.c_str(); }
  14339. exact_copies.emplace_back(pem.begin(), pem.end());
  14340. return exact_copies.back().data();
  14341. };
  14342. // Create server with PEM memory
  14343. SSLServer::PemMemory server_pem = {
  14344. data(server_cert_pem),
  14345. server_cert_pem.size(),
  14346. data(server_key_pem),
  14347. server_key_pem.size(),
  14348. data(client_ca_pem),
  14349. client_ca_pem.size(),
  14350. nullptr // no password for server key
  14351. };
  14352. SSLServer svr(server_pem);
  14353. ASSERT_TRUE(svr.is_valid());
  14354. svr.Get("/test", [&](const Request &req, Response &res) {
  14355. res.set_content("test", "text/plain");
  14356. auto cert = req.peer_cert();
  14357. ASSERT_TRUE(static_cast<bool>(cert));
  14358. EXPECT_EQ("Common Name", cert.subject_cn());
  14359. });
  14360. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14361. auto se = detail::scope_exit([&] {
  14362. svr.stop();
  14363. t.join();
  14364. ASSERT_FALSE(svr.is_running());
  14365. });
  14366. svr.wait_until_ready();
  14367. // Create client with PEM memory
  14368. const char *password = client_encrypted_private_key_pass.empty()
  14369. ? nullptr
  14370. : client_encrypted_private_key_pass.c_str();
  14371. SSLClient::PemMemory client_pem = {
  14372. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14373. client_key_pem.size(), password};
  14374. SSLClient cli(HOST, PORT, client_pem);
  14375. cli.enable_server_certificate_verification(false);
  14376. cli.set_connection_timeout(30);
  14377. auto res = cli.Get("/test");
  14378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14379. ASSERT_EQ(StatusCode::OK_200, res->status);
  14380. }
  14381. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14382. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14383. }
  14384. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14385. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14386. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14387. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14388. }
  14389. // A server built from PEM memory with a client CA requires client certificates,
  14390. // also when the CA is a NUL-terminated string passed with a length of 0
  14391. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14392. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14393. read_file(SERVER_CERT_FILE, server_cert_pem);
  14394. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14395. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14396. SSLServer::PemMemory server_pem = {
  14397. server_cert_pem.c_str(),
  14398. server_cert_pem.size(),
  14399. server_key_pem.c_str(),
  14400. server_key_pem.size(),
  14401. client_ca_pem.c_str(),
  14402. client_ca_pem.size(),
  14403. nullptr // no password for server key
  14404. };
  14405. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14406. SCOPED_TRACE(client_ca_pem_len);
  14407. server_pem.client_ca_pem_len = client_ca_pem_len;
  14408. SSLServer svr(server_pem);
  14409. ASSERT_TRUE(svr.is_valid());
  14410. RejectsClientWithoutCert(svr);
  14411. }
  14412. // An empty CA fails to load instead of turning the check off
  14413. server_pem.client_ca_pem = "";
  14414. server_pem.client_ca_pem_len = 0;
  14415. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14416. }
  14417. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14418. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14419. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14420. true);
  14421. }
  14422. // A length shorter than the PEM cuts it short, so it no longer loads
  14423. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14424. std::string cert, key;
  14425. read_file(SERVER_CERT_FILE, cert);
  14426. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14427. for (auto cut_cert : {true, false}) {
  14428. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14429. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14430. SSLServer::PemMemory server_pem = {
  14431. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14432. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14433. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14434. key_len, nullptr};
  14435. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14436. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14437. key.c_str(), key_len, nullptr};
  14438. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14439. }
  14440. }
  14441. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14442. class NoListenSSLServer : public SSLServer {
  14443. public:
  14444. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14445. const char *client_ca_cert_file_path,
  14446. const char *client_ca_cert_dir_path = nullptr)
  14447. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14448. client_ca_cert_dir_path),
  14449. stop_(false) {}
  14450. std::atomic_bool stop_;
  14451. private:
  14452. bool process_and_close_socket(socket_t /*sock*/) override {
  14453. // Don't create SSL context
  14454. while (!stop_.load()) {
  14455. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14456. }
  14457. return true;
  14458. }
  14459. };
  14460. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14461. CLIENT_CA_CERT_FILE);
  14462. ASSERT_TRUE(svr.is_valid());
  14463. svr.Get("/test", [&](const Request &, Response &res) {
  14464. res.set_content("test", "text/plain");
  14465. });
  14466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14467. auto se = detail::scope_exit([&] {
  14468. svr.stop_ = true;
  14469. svr.stop();
  14470. t.join();
  14471. ASSERT_FALSE(svr.is_running());
  14472. });
  14473. svr.wait_until_ready();
  14474. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14475. cli.enable_server_certificate_verification(false);
  14476. cli.set_connection_timeout(1);
  14477. auto res = cli.Get("/test");
  14478. ASSERT_TRUE(!res);
  14479. EXPECT_EQ(Error::SSLConnection, res.error());
  14480. // Timeout results in WantRead error code (maps to backend-specific value)
  14481. EXPECT_NE(0, res.ssl_error());
  14482. }
  14483. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14484. // Test SSLServer with client certificate verification using the standard
  14485. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14487. CLIENT_CA_CERT_DIR);
  14488. ASSERT_TRUE(svr.is_valid());
  14489. svr.Get("/test", [&](const Request &req, Response &res) {
  14490. res.set_content("test", "text/plain");
  14491. auto cert = req.peer_cert();
  14492. ASSERT_TRUE(static_cast<bool>(cert));
  14493. auto common_name = cert.subject_cn();
  14494. EXPECT_EQ("Common Name", common_name);
  14495. });
  14496. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14497. auto se = detail::scope_exit([&] {
  14498. svr.stop();
  14499. t.join();
  14500. ASSERT_FALSE(svr.is_running());
  14501. });
  14502. svr.wait_until_ready();
  14503. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14504. cli.enable_server_certificate_verification(false);
  14505. cli.set_connection_timeout(30);
  14506. auto res = cli.Get("/test");
  14507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14508. ASSERT_EQ(StatusCode::OK_200, res->status);
  14509. }
  14510. // Test verify_hostname on every backend: a host is named by a SAN only
  14511. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14512. using namespace httplib::tls;
  14513. // We need a running server to test against
  14514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14515. ASSERT_TRUE(svr.is_valid());
  14516. svr.Get("/test", [](const Request &, Response &res) {
  14517. res.set_content("ok", "text/plain");
  14518. });
  14519. thread t([&]() { svr.listen(HOST, PORT); });
  14520. auto se = detail::scope_exit([&] {
  14521. svr.stop();
  14522. t.join();
  14523. });
  14524. svr.wait_until_ready();
  14525. bool verify_callback_called = false;
  14526. bool verify_result_wrong = false;
  14527. SSLClient cli(HOST, PORT);
  14528. cli.enable_server_certificate_verification(true);
  14529. cli.set_ca_cert_path(CA_CERT_FILE);
  14530. cli.set_connection_timeout(5);
  14531. // Note: Test certificate has CN="Common Name", not "localhost"
  14532. bool verify_result_cn = false;
  14533. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14534. verify_callback_called = true;
  14535. if (!ctx.cert) return false;
  14536. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14537. verify_result_cn = ctx.check_hostname("Common Name");
  14538. // Test 2: wrong hostname should not match
  14539. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14540. return true; // Accept for the purpose of this test
  14541. });
  14542. auto res = cli.Get("/test");
  14543. // The request may succeed or fail depending on cert configuration
  14544. // but the callback should have been called
  14545. ASSERT_TRUE(verify_callback_called)
  14546. << "Verify callback should have been called";
  14547. EXPECT_FALSE(verify_result_cn)
  14548. << "verify_hostname must not match the certificate CN (no SAN)";
  14549. // Wrong hostname should not match
  14550. EXPECT_FALSE(verify_result_wrong)
  14551. << "verify_hostname should not match 'wronghost.example.com'";
  14552. }
  14553. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14554. // backend verifies it.
  14555. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14556. // Certificate CN is "localhost" and it carries no SAN.
  14557. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14558. ASSERT_TRUE(svr.is_valid());
  14559. svr.Get("/test", [](const Request &, Response &res) {
  14560. res.set_content("ok", "text/plain");
  14561. });
  14562. auto port = svr.bind_to_any_port(HOST);
  14563. thread t([&]() { svr.listen_after_bind(); });
  14564. auto se = detail::scope_exit([&] {
  14565. svr.stop();
  14566. t.join();
  14567. });
  14568. svr.wait_until_ready();
  14569. SSLClient cli("localhost", port);
  14570. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14571. cli.enable_server_certificate_verification(true);
  14572. cli.set_connection_timeout(5);
  14573. auto res = cli.Get("/test");
  14574. ASSERT_FALSE(res);
  14575. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14576. // The same certificate is accepted once host name verification is off, so the
  14577. // failure above is the host name and not the chain.
  14578. cli.enable_server_hostname_verification(false);
  14579. res = cli.Get("/test");
  14580. ASSERT_TRUE(res) << to_string(res.error());
  14581. EXPECT_EQ(StatusCode::OK_200, res->status);
  14582. }
  14583. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14584. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14585. // X509_check_ip behavior and must hold for every backend.
  14586. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14587. using namespace httplib::tls;
  14588. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14589. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14590. ASSERT_TRUE(svr.is_valid());
  14591. svr.Get("/test", [](const Request &, Response &res) {
  14592. res.set_content("ok", "text/plain");
  14593. });
  14594. thread t([&]() { svr.listen(HOST, PORT); });
  14595. auto se = detail::scope_exit([&] {
  14596. svr.stop();
  14597. t.join();
  14598. });
  14599. svr.wait_until_ready();
  14600. bool verify_callback_called = false;
  14601. bool ip_matched_via_cn = true;
  14602. SSLClient cli(HOST, PORT);
  14603. cli.enable_server_certificate_verification(true);
  14604. cli.set_ca_cert_path(CA_CERT_FILE);
  14605. cli.set_connection_timeout(5);
  14606. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14607. verify_callback_called = true;
  14608. if (!ctx.cert) return false;
  14609. // The IP appears only in the CN, so it must NOT be accepted.
  14610. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14611. return true; // Accept for the purpose of this test
  14612. });
  14613. cli.Get("/test");
  14614. ASSERT_TRUE(verify_callback_called)
  14615. << "Verify callback should have been called";
  14616. EXPECT_FALSE(ip_matched_via_cn)
  14617. << "An IP host must not be authenticated via the certificate CN";
  14618. }
  14619. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14620. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14621. using namespace httplib::tls;
  14622. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14623. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14624. ASSERT_TRUE(svr.is_valid());
  14625. svr.Get("/test", [](const Request &, Response &res) {
  14626. res.set_content("ok", "text/plain");
  14627. });
  14628. thread t([&]() { svr.listen(HOST, PORT); });
  14629. auto se = detail::scope_exit([&] {
  14630. svr.stop();
  14631. t.join();
  14632. });
  14633. svr.wait_until_ready();
  14634. bool verify_callback_called = false;
  14635. bool san_matched = false;
  14636. bool wrong_ipv6_matched = true;
  14637. bool cn_ipv6_matched = true;
  14638. SSLClient cli(HOST, PORT);
  14639. cli.enable_server_certificate_verification(true);
  14640. cli.set_ca_cert_path(CA_CERT_FILE);
  14641. cli.set_connection_timeout(5);
  14642. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14643. verify_callback_called = true;
  14644. if (!ctx.cert) return false;
  14645. // Matches the IPv6 iPAddress SAN.
  14646. san_matched = ctx.check_hostname("2001:db8::1");
  14647. // A different IPv6 address must not match.
  14648. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14649. // "::1" lives only in the CN, so it must not be accepted.
  14650. cn_ipv6_matched = ctx.check_hostname("::1");
  14651. return true; // Accept for the purpose of this test
  14652. });
  14653. cli.Get("/test");
  14654. ASSERT_TRUE(verify_callback_called)
  14655. << "Verify callback should have been called";
  14656. EXPECT_TRUE(san_matched)
  14657. << "verify_hostname should match an IPv6 iPAddress SAN";
  14658. EXPECT_FALSE(wrong_ipv6_matched)
  14659. << "verify_hostname should not match a non-matching IPv6 address";
  14660. EXPECT_FALSE(cn_ipv6_matched)
  14661. << "An IPv6 host must not be authenticated via the certificate CN";
  14662. }
  14663. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14664. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14665. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14666. using namespace httplib::tls;
  14667. // SANs: DNS:a.zz, IP:42.46.122.122
  14668. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14669. ASSERT_TRUE(svr.is_valid());
  14670. svr.Get("/test", [](const Request &, Response &res) {
  14671. res.set_content("ok", "text/plain");
  14672. });
  14673. auto port = svr.bind_to_any_port(HOST);
  14674. thread t([&]() { svr.listen_after_bind(); });
  14675. auto se = detail::scope_exit([&] {
  14676. svr.stop();
  14677. t.join();
  14678. });
  14679. svr.wait_until_ready();
  14680. bool verify_callback_called = false;
  14681. bool dns_san_matched = false;
  14682. bool ip_san_matched = false;
  14683. bool ip_matched_via_dns_san = true;
  14684. bool dns_matched_via_ip_san = true;
  14685. bool cn_matched_next_to_dns_san = true;
  14686. SSLClient cli(HOST, port);
  14687. cli.enable_server_certificate_verification(true);
  14688. cli.set_ca_cert_path(CA_CERT_FILE);
  14689. cli.set_connection_timeout(5);
  14690. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14691. verify_callback_called = true;
  14692. if (!ctx.cert) return false;
  14693. dns_san_matched = ctx.check_hostname("a.zz");
  14694. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14695. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14696. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14697. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14698. return true; // Accept for the purpose of this test
  14699. });
  14700. cli.Get("/test");
  14701. ASSERT_TRUE(verify_callback_called)
  14702. << "Verify callback should have been called";
  14703. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14704. EXPECT_TRUE(ip_san_matched)
  14705. << "verify_hostname should match an iPAddress SAN";
  14706. EXPECT_FALSE(ip_matched_via_dns_san)
  14707. << "An IP host must not be authenticated via a dNSName SAN";
  14708. EXPECT_FALSE(dns_matched_via_ip_san)
  14709. << "A DNS host must not be authenticated via an iPAddress SAN";
  14710. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14711. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14712. }
  14713. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14714. // "www.*.example.test" names one host and not every host under example.test.
  14715. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14716. using namespace httplib::tls;
  14717. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14718. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14719. ASSERT_TRUE(svr.is_valid());
  14720. svr.Get("/test", [](const Request &, Response &res) {
  14721. res.set_content("ok", "text/plain");
  14722. });
  14723. auto port = svr.bind_to_any_port(HOST);
  14724. thread t([&]() { svr.listen_after_bind(); });
  14725. auto se = detail::scope_exit([&] {
  14726. svr.stop();
  14727. t.join();
  14728. });
  14729. svr.wait_until_ready();
  14730. bool verify_callback_called = false;
  14731. bool leftmost_wildcard_matched = false;
  14732. bool wildcard_spanned_labels = true;
  14733. bool inner_wildcard_matched = true;
  14734. SSLClient cli(HOST, port);
  14735. cli.enable_server_certificate_verification(true);
  14736. cli.set_ca_cert_path(CA_CERT_FILE);
  14737. cli.set_connection_timeout(5);
  14738. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14739. verify_callback_called = true;
  14740. if (!ctx.cert) return false;
  14741. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14742. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14743. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14744. return true; // Accept for the purpose of this test
  14745. });
  14746. cli.Get("/test");
  14747. ASSERT_TRUE(verify_callback_called)
  14748. << "Verify callback should have been called";
  14749. EXPECT_TRUE(leftmost_wildcard_matched)
  14750. << "A leftmost wildcard should match a single label";
  14751. EXPECT_FALSE(wildcard_spanned_labels)
  14752. << "A wildcard label must not match more than one label";
  14753. EXPECT_FALSE(inner_wildcard_matched)
  14754. << "A wildcard outside the leftmost label must not be honoured";
  14755. }
  14756. // sans() must report each SAN entry under its own type.
  14757. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14758. using namespace httplib::tls;
  14759. // SANs: DNS:a.zz, IP:42.46.122.122
  14760. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14761. ASSERT_TRUE(svr.is_valid());
  14762. svr.Get("/test", [](const Request &, Response &res) {
  14763. res.set_content("ok", "text/plain");
  14764. });
  14765. auto port = svr.bind_to_any_port(HOST);
  14766. thread t([&]() { svr.listen_after_bind(); });
  14767. auto se = detail::scope_exit([&] {
  14768. svr.stop();
  14769. t.join();
  14770. });
  14771. svr.wait_until_ready();
  14772. bool verify_callback_called = false;
  14773. std::vector<SanEntry> sans;
  14774. SSLClient cli(HOST, port);
  14775. cli.enable_server_certificate_verification(true);
  14776. cli.set_ca_cert_path(CA_CERT_FILE);
  14777. cli.set_connection_timeout(5);
  14778. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14779. verify_callback_called = true;
  14780. if (!ctx.cert) return false;
  14781. sans = ctx.sans();
  14782. return true; // Accept for the purpose of this test
  14783. });
  14784. cli.Get("/test");
  14785. ASSERT_TRUE(verify_callback_called)
  14786. << "Verify callback should have been called";
  14787. auto has_san = [&](SanType type, const std::string &value) {
  14788. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14789. return san.type == type && san.value == value;
  14790. });
  14791. };
  14792. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14793. << "sans() should report the dNSName SAN";
  14794. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14795. << "sans() should report the iPAddress SAN";
  14796. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14797. << "sans() must not report the dNSName SAN as an address";
  14798. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14799. << "sans() must not report the iPAddress SAN as a DNS name";
  14800. }
  14801. #endif
  14802. // mbedTLS-specific callback constructor test
  14803. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14804. #ifdef CPPHTTPLIB_SSL_ENABLED
  14805. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14807. ASSERT_TRUE(svr.is_valid());
  14808. // Set up a handler to verify client certificate is present
  14809. bool client_cert_verified = false;
  14810. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14811. // Verify that client certificate was provided
  14812. client_cert_verified = true;
  14813. res.set_content("success", "text/plain");
  14814. });
  14815. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14816. auto se = detail::scope_exit([&] {
  14817. svr.stop();
  14818. t.join();
  14819. ASSERT_FALSE(svr.is_running());
  14820. });
  14821. svr.wait_until_ready();
  14822. // Client with certificate
  14823. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14824. cli.enable_server_certificate_verification(false);
  14825. cli.set_connection_timeout(30);
  14826. auto res = cli.Get("/test");
  14827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14828. ASSERT_EQ(StatusCode::OK_200, res->status);
  14829. ASSERT_TRUE(client_cert_verified);
  14830. EXPECT_EQ("success", res->body);
  14831. }
  14832. #endif
  14833. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14834. // backends
  14835. #ifdef CPPHTTPLIB_SSL_ENABLED
  14836. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14837. using namespace httplib::tls;
  14838. // Test that when client CA cert file is provided,
  14839. // the server properly requests and validates client certificates
  14840. // Create a server with client authentication
  14841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14842. ASSERT_TRUE(svr.is_valid());
  14843. bool handler_called = false;
  14844. svr.Get("/test", [&](const Request &req, Response &res) {
  14845. handler_called = true;
  14846. // Verify that a client certificate was provided
  14847. auto cert = req.peer_cert();
  14848. ASSERT_TRUE(static_cast<bool>(cert));
  14849. // Get the issuer name
  14850. std::string issuer_str = cert.issuer_name();
  14851. ASSERT_FALSE(issuer_str.empty());
  14852. // The client certificate should be issued by our test CA
  14853. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14854. res.set_content("authenticated", "text/plain");
  14855. });
  14856. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14857. auto se = detail::scope_exit([&] {
  14858. svr.stop();
  14859. t.join();
  14860. ASSERT_FALSE(svr.is_running());
  14861. });
  14862. svr.wait_until_ready();
  14863. // Connect with a client certificate issued by the CA
  14864. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14865. cli.enable_server_certificate_verification(false);
  14866. cli.set_connection_timeout(30);
  14867. auto res = cli.Get("/test");
  14868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14869. ASSERT_EQ(StatusCode::OK_200, res->status);
  14870. ASSERT_TRUE(handler_called);
  14871. EXPECT_EQ("authenticated", res->body);
  14872. }
  14873. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14874. using namespace httplib::tls;
  14875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14876. ASSERT_TRUE(svr.is_valid());
  14877. svr.Get("/test", [](const Request &, Response &res) {
  14878. res.set_content("ok", "text/plain");
  14879. });
  14880. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14881. auto se = detail::scope_exit([&] {
  14882. svr.stop();
  14883. t.join();
  14884. });
  14885. svr.wait_until_ready();
  14886. SSLClient cli(HOST, PORT);
  14887. cli.enable_server_certificate_verification(false);
  14888. cli.set_connection_timeout(30);
  14889. bool cert_checked = false;
  14890. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14891. if (ctx.cert) {
  14892. auto sans = ctx.sans();
  14893. // Test certificate may or may not have SANs - just verify the API
  14894. // works If SANs exist, verify the types are valid
  14895. for (const auto &san : sans) {
  14896. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14897. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14898. san.type == SanType::OTHER);
  14899. EXPECT_FALSE(san.value.empty());
  14900. }
  14901. cert_checked = true;
  14902. }
  14903. return true;
  14904. });
  14905. auto res = cli.Get("/test");
  14906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14907. EXPECT_TRUE(cert_checked);
  14908. }
  14909. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14910. using namespace httplib::tls;
  14911. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14912. ASSERT_TRUE(svr.is_valid());
  14913. svr.Get("/test", [](const Request &, Response &res) {
  14914. res.set_content("ok", "text/plain");
  14915. });
  14916. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14917. auto se = detail::scope_exit([&] {
  14918. svr.stop();
  14919. t.join();
  14920. });
  14921. svr.wait_until_ready();
  14922. SSLClient cli(HOST, PORT);
  14923. cli.enable_server_certificate_verification(false);
  14924. cli.set_connection_timeout(30);
  14925. bool validity_checked = false;
  14926. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14927. if (ctx.cert) {
  14928. time_t not_before = 0, not_after = 0;
  14929. bool result = ctx.validity(not_before, not_after);
  14930. EXPECT_TRUE(result);
  14931. // Verify that not_before < now < not_after for a valid cert
  14932. time_t now = time(nullptr);
  14933. EXPECT_LT(not_before, now);
  14934. EXPECT_GT(not_after, now);
  14935. validity_checked = true;
  14936. }
  14937. return true;
  14938. });
  14939. auto res = cli.Get("/test");
  14940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14941. EXPECT_TRUE(validity_checked);
  14942. }
  14943. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14944. using namespace httplib::tls;
  14945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14946. ASSERT_TRUE(svr.is_valid());
  14947. svr.Get("/test", [](const Request &, Response &res) {
  14948. res.set_content("ok", "text/plain");
  14949. });
  14950. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14951. auto se = detail::scope_exit([&] {
  14952. svr.stop();
  14953. t.join();
  14954. });
  14955. svr.wait_until_ready();
  14956. SSLClient cli(HOST, PORT);
  14957. cli.enable_server_certificate_verification(false);
  14958. cli.set_connection_timeout(30);
  14959. bool serial_checked = false;
  14960. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14961. if (ctx.cert) {
  14962. std::string serial = ctx.serial();
  14963. EXPECT_FALSE(serial.empty());
  14964. // Serial should be a hex string
  14965. for (char c : serial) {
  14966. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14967. (c >= 'a' && c <= 'f'));
  14968. }
  14969. serial_checked = true;
  14970. }
  14971. return true;
  14972. });
  14973. auto res = cli.Get("/test");
  14974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14975. EXPECT_TRUE(serial_checked);
  14976. }
  14977. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14978. // Test 1: Valid CA file - no error should be recorded
  14979. {
  14980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14981. CLIENT_CA_CERT_FILE);
  14982. ASSERT_TRUE(svr.is_valid());
  14983. // With valid setup, last_ssl_error should be 0
  14984. EXPECT_EQ(0, svr.ssl_last_error());
  14985. }
  14986. // Test 2: Invalid CA file content
  14987. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14988. {
  14989. // Create a temporary file with completely invalid content
  14990. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14991. {
  14992. std::ofstream ofs(temp_invalid_ca);
  14993. ofs << "This is not a certificate file at all\n";
  14994. ofs << "Just plain text content\n";
  14995. }
  14996. // Create server with invalid CA file
  14997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14998. // Clean up temporary file
  14999. std::remove(temp_invalid_ca);
  15000. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15001. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15002. // Note: SSL_CTX_load_verify_locations typically fails first,
  15003. // but our error handling code path is still exercised
  15004. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15005. }
  15006. }
  15007. TEST(VerifyCallbackTest, VerifyContextFields) {
  15008. using namespace httplib::tls;
  15009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15010. ASSERT_TRUE(svr.is_valid());
  15011. svr.Get("/test", [](const Request &, Response &res) {
  15012. res.set_content("ok", "text/plain");
  15013. });
  15014. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15015. auto se = detail::scope_exit([&] {
  15016. svr.stop();
  15017. t.join();
  15018. });
  15019. svr.wait_until_ready();
  15020. SSLClient cli(HOST, PORT);
  15021. cli.enable_server_certificate_verification(false);
  15022. cli.set_connection_timeout(30);
  15023. int callback_count = 0;
  15024. bool saw_leaf_cert = false;
  15025. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15026. if (ctx.cert) {
  15027. callback_count++;
  15028. // We should see at least one certificate (the leaf)
  15029. std::string cn = ctx.subject_cn();
  15030. if (!cn.empty()) { saw_leaf_cert = true; }
  15031. // Verify context fields are populated
  15032. EXPECT_NE(ctx.session, nullptr);
  15033. EXPECT_GE(ctx.depth, 0);
  15034. }
  15035. return true;
  15036. });
  15037. auto res = cli.Get("/test");
  15038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15039. EXPECT_GT(callback_count, 0);
  15040. EXPECT_TRUE(saw_leaf_cert);
  15041. }
  15042. // A verifier that accepts runs alongside the built-in verification, and is the
  15043. // only check once that is turned off.
  15044. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15045. using namespace httplib::tls;
  15046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15047. ASSERT_TRUE(svr.is_valid());
  15048. svr.Get("/test", [](const Request &, Response &res) {
  15049. res.set_content("ok", "text/plain");
  15050. });
  15051. auto port = svr.bind_to_any_port(HOST);
  15052. thread t([&]() { svr.listen_after_bind(); });
  15053. auto se = detail::scope_exit([&] {
  15054. svr.stop();
  15055. t.join();
  15056. });
  15057. svr.wait_until_ready();
  15058. SSLClient cli(HOST, port);
  15059. cli.enable_server_hostname_verification(false);
  15060. auto calls = 0;
  15061. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15062. calls++;
  15063. return true;
  15064. });
  15065. // cert.pem is not trusted
  15066. auto res = cli.Get("/test");
  15067. ASSERT_FALSE(res);
  15068. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15069. EXPECT_GT(calls, 0);
  15070. cli.enable_server_certificate_verification(false);
  15071. res = cli.Get("/test");
  15072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15073. EXPECT_EQ("ok", res->body);
  15074. }
  15075. // A verifier belongs to the client that set it, not to the thread that set it.
  15076. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15077. using namespace httplib::tls;
  15078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15079. ASSERT_TRUE(svr.is_valid());
  15080. svr.Get("/test", [](const Request &, Response &res) {
  15081. res.set_content("ok", "text/plain");
  15082. });
  15083. auto port = svr.bind_to_any_port(HOST);
  15084. thread t([&]() { svr.listen_after_bind(); });
  15085. auto se = detail::scope_exit([&] {
  15086. svr.stop();
  15087. t.join();
  15088. });
  15089. svr.wait_until_ready();
  15090. auto rejecting_calls = 0;
  15091. SSLClient rejecting(HOST, port);
  15092. rejecting.enable_server_certificate_verification(false);
  15093. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15094. rejecting_calls++;
  15095. return false;
  15096. });
  15097. auto accepting_calls = 0;
  15098. SSLClient accepting(HOST, port);
  15099. accepting.enable_server_certificate_verification(false);
  15100. // Set on another thread than the requests below.
  15101. thread([&]() {
  15102. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15103. accepting_calls++;
  15104. return true;
  15105. });
  15106. }).join();
  15107. // Requested on another thread than the verifier was set on.
  15108. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15109. EXPECT_GT(rejecting_calls, 0);
  15110. auto res = accepting.Get("/test");
  15111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15112. EXPECT_GT(accepting_calls, 0);
  15113. }
  15114. // A verifier replaced while a handshake runs it lives until it returns.
  15115. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15116. using namespace httplib::tls;
  15117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15118. ASSERT_TRUE(svr.is_valid());
  15119. svr.Get("/test", [](const Request &, Response &res) {
  15120. res.set_content("ok", "text/plain");
  15121. });
  15122. auto port = svr.bind_to_any_port(HOST);
  15123. thread t([&]() { svr.listen_after_bind(); });
  15124. auto se = detail::scope_exit([&] {
  15125. svr.stop();
  15126. t.join();
  15127. });
  15128. svr.wait_until_ready();
  15129. SSLClient cli(HOST, port);
  15130. cli.enable_server_certificate_verification(false);
  15131. std::promise<void> entered;
  15132. std::promise<void> replaced;
  15133. auto replaced_future = replaced.get_future();
  15134. auto first_call = true;
  15135. // Long enough to live on the heap
  15136. std::string expected(64, 'v');
  15137. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15138. if (first_call) {
  15139. first_call = false;
  15140. entered.set_value();
  15141. replaced_future.wait();
  15142. }
  15143. return expected == std::string(64, 'v');
  15144. });
  15145. thread request([&]() {
  15146. auto res = cli.Get("/test");
  15147. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15148. });
  15149. entered.get_future().wait();
  15150. cli.set_server_certificate_verifier(
  15151. [](const VerifyContext &) { return true; });
  15152. replaced.set_value();
  15153. request.join();
  15154. }
  15155. // VerifyContext::session is the same handle the other tls:: functions take.
  15156. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15157. using namespace httplib::tls;
  15158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15159. ASSERT_TRUE(svr.is_valid());
  15160. svr.Get("/test", [](const Request &, Response &res) {
  15161. res.set_content("ok", "text/plain");
  15162. });
  15163. auto port = svr.bind_to_any_port(HOST);
  15164. thread t([&]() { svr.listen_after_bind(); });
  15165. auto se = detail::scope_exit([&] {
  15166. svr.stop();
  15167. t.join();
  15168. });
  15169. svr.wait_until_ready();
  15170. SSLClient cli(HOST, port);
  15171. cli.enable_server_certificate_verification(false);
  15172. session_t verifier_session = nullptr;
  15173. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15174. verifier_session = ctx.session;
  15175. return true;
  15176. });
  15177. session_t session_verifier_session = nullptr;
  15178. cli.set_session_verifier([&](session_t session) {
  15179. session_verifier_session = session;
  15180. return SSLVerifierResponse::NoDecisionMade;
  15181. });
  15182. auto res = cli.Get("/test");
  15183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15184. EXPECT_NE(nullptr, verifier_session);
  15185. EXPECT_EQ(session_verifier_session, verifier_session);
  15186. }
  15187. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15188. using httplib::tls::TlsError;
  15189. // Test that verify_error_to_string returns empty for success
  15190. std::string success_str = TlsError::verify_error_to_string(0);
  15191. EXPECT_TRUE(success_str.empty());
  15192. // Test that verify_error_to_string returns non-empty for error codes
  15193. // Using a common error code (certificate expired)
  15194. std::string error_str =
  15195. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15196. EXPECT_FALSE(error_str.empty());
  15197. }
  15198. TEST(SessionVerifierTest, CertificateAccepted) {
  15199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15200. ASSERT_TRUE(svr.is_valid());
  15201. svr.Get("/test", [](const Request &, Response &res) {
  15202. res.set_content("ok", "text/plain");
  15203. });
  15204. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15205. auto se = detail::scope_exit([&] {
  15206. svr.stop();
  15207. t.join();
  15208. });
  15209. svr.wait_until_ready();
  15210. SSLClient cli(HOST, PORT);
  15211. cli.enable_server_certificate_verification(false);
  15212. cli.set_connection_timeout(30);
  15213. bool callback_called = false;
  15214. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15215. EXPECT_NE(session, nullptr);
  15216. callback_called = true;
  15217. return SSLVerifierResponse::CertificateAccepted;
  15218. });
  15219. auto res = cli.Get("/test");
  15220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15221. EXPECT_EQ(200, res->status);
  15222. EXPECT_TRUE(callback_called);
  15223. }
  15224. TEST(SessionVerifierTest, CertificateRejected) {
  15225. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15226. ASSERT_TRUE(svr.is_valid());
  15227. svr.Get("/test", [](const Request &, Response &res) {
  15228. res.set_content("ok", "text/plain");
  15229. });
  15230. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15231. auto se = detail::scope_exit([&] {
  15232. svr.stop();
  15233. t.join();
  15234. });
  15235. svr.wait_until_ready();
  15236. SSLClient cli(HOST, PORT);
  15237. cli.enable_server_certificate_verification(false);
  15238. cli.set_connection_timeout(30);
  15239. bool callback_called = false;
  15240. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15241. EXPECT_NE(session, nullptr);
  15242. callback_called = true;
  15243. return SSLVerifierResponse::CertificateRejected;
  15244. });
  15245. auto res = cli.Get("/test");
  15246. EXPECT_FALSE(res);
  15247. EXPECT_TRUE(callback_called);
  15248. }
  15249. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15251. ASSERT_TRUE(svr.is_valid());
  15252. svr.Get("/test", [](const Request &, Response &res) {
  15253. res.set_content("ok", "text/plain");
  15254. });
  15255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15256. auto se = detail::scope_exit([&] {
  15257. svr.stop();
  15258. t.join();
  15259. });
  15260. svr.wait_until_ready();
  15261. // NoDecisionMade with verification disabled should succeed (no default check)
  15262. SSLClient cli(HOST, PORT);
  15263. cli.enable_server_certificate_verification(false);
  15264. cli.set_connection_timeout(30);
  15265. bool callback_called = false;
  15266. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15267. EXPECT_NE(session, nullptr);
  15268. callback_called = true;
  15269. return SSLVerifierResponse::NoDecisionMade;
  15270. });
  15271. auto res = cli.Get("/test");
  15272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15273. EXPECT_EQ(200, res->status);
  15274. EXPECT_TRUE(callback_called);
  15275. }
  15276. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15278. ASSERT_TRUE(svr.is_valid());
  15279. svr.Get("/test", [](const Request &, Response &res) {
  15280. res.set_content("ok", "text/plain");
  15281. });
  15282. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15283. auto se = detail::scope_exit([&] {
  15284. svr.stop();
  15285. t.join();
  15286. });
  15287. svr.wait_until_ready();
  15288. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15289. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15290. // so we only check that the request fails, not whether the callback was
  15291. // called.
  15292. SSLClient cli(HOST, PORT);
  15293. cli.enable_server_certificate_verification(true);
  15294. cli.set_connection_timeout(30);
  15295. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15296. EXPECT_NE(session, nullptr);
  15297. return SSLVerifierResponse::NoDecisionMade;
  15298. });
  15299. auto res = cli.Get("/test");
  15300. EXPECT_FALSE(res);
  15301. }
  15302. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15303. // Test SSL server using PemMemory constructor with client CA certificates
  15304. // Read PEM files
  15305. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15306. read_file(SERVER_CERT_FILE, server_cert_pem);
  15307. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15308. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15309. // Create SSLServer with PemMemory constructor including client CA
  15310. SSLServer::PemMemory server_pem = {
  15311. server_cert_pem.c_str(),
  15312. server_cert_pem.size(),
  15313. server_key_pem.c_str(),
  15314. server_key_pem.size(),
  15315. client_ca_pem.c_str(),
  15316. client_ca_pem.size(),
  15317. nullptr // no password for server key
  15318. };
  15319. SSLServer svr(server_pem);
  15320. ASSERT_TRUE(svr.is_valid());
  15321. // No SSL error should be recorded for valid setup
  15322. EXPECT_EQ(0, svr.ssl_last_error());
  15323. // Set up server endpoints
  15324. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15325. res.set_content("ok", "text/plain");
  15326. });
  15327. // Start server in a thread
  15328. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15329. svr.wait_until_ready();
  15330. // Connect with client certificate (using constructor with paths)
  15331. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15332. cli.enable_server_certificate_verification(false);
  15333. auto res = cli.Get("/test-pem-ca");
  15334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15335. EXPECT_EQ(200, res->status);
  15336. EXPECT_EQ("ok", res->body);
  15337. svr.stop();
  15338. server_thread.join();
  15339. }
  15340. #endif
  15341. #ifdef _WIN32
  15342. TEST(CleanupTest, WSACleanup) {
  15343. int ret = WSACleanup();
  15344. ASSERT_EQ(0, ret);
  15345. }
  15346. #endif
  15347. #ifndef CPPHTTPLIB_SSL_ENABLED
  15348. TEST(NoSSLSupport, SimpleInterface) {
  15349. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15350. }
  15351. #endif
  15352. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15353. TEST(InvalidScheme, SimpleInterface) {
  15354. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15355. }
  15356. #endif
  15357. TEST(NoScheme, SimpleInterface) {
  15358. Client cli("yahoo.com:80");
  15359. ASSERT_TRUE(cli.is_valid());
  15360. }
  15361. TEST(SendAPI, SimpleInterface_Online) {
  15362. Client cli("http://yahoo.com");
  15363. Request req;
  15364. req.method = "GET";
  15365. req.path = "/";
  15366. auto res = cli.send(req);
  15367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15368. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15369. }
  15370. TEST(SendAPI, WithParamsInRequest) {
  15371. Server svr;
  15372. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15373. EXPECT_TRUE(req.has_param("test"));
  15374. EXPECT_EQ("test_value", req.get_param_value("test"));
  15375. });
  15376. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15377. auto se = detail::scope_exit([&] {
  15378. svr.stop();
  15379. t.join();
  15380. ASSERT_FALSE(svr.is_running());
  15381. });
  15382. svr.wait_until_ready();
  15383. Client cli(HOST, PORT);
  15384. {
  15385. Request req;
  15386. req.method = "GET";
  15387. req.path = "/";
  15388. req.params.emplace("test", "test_value");
  15389. auto res = cli.send(req);
  15390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15391. }
  15392. {
  15393. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15395. }
  15396. }
  15397. TEST(ClientImplMethods, GetSocketTest) {
  15398. httplib::Server svr;
  15399. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15400. res.status = StatusCode::OK_200;
  15401. });
  15402. auto port = svr.bind_to_any_port("127.0.0.1");
  15403. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15404. auto se = detail::scope_exit([&] {
  15405. svr.stop();
  15406. thread.join();
  15407. ASSERT_FALSE(svr.is_running());
  15408. });
  15409. svr.wait_until_ready();
  15410. {
  15411. httplib::Client cli("127.0.0.1", port);
  15412. cli.set_keep_alive(true);
  15413. // Use the behavior of cpp-httplib of opening the connection
  15414. // only when the first request happens. If that changes,
  15415. // this test would be obsolete.
  15416. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15417. // This also implicitly tests the server. But other tests would fail much
  15418. // earlier than this one to be considered.
  15419. auto res = cli.Get("/");
  15420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15421. EXPECT_EQ(StatusCode::OK_200, res->status);
  15422. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15423. }
  15424. }
  15425. #ifdef CPPHTTPLIB_SSL_ENABLED
  15426. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15427. Client cli("http://yahoo.com");
  15428. auto res = cli.Get("/");
  15429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15430. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15431. cli.set_follow_location(true);
  15432. res = cli.Get("/");
  15433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15434. EXPECT_EQ(StatusCode::OK_200, res->status);
  15435. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15436. }
  15437. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15438. Client cli("https://yahoo.com");
  15439. auto res = cli.Get("/");
  15440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15441. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15442. cli.set_follow_location(true);
  15443. res = cli.Get("/");
  15444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15445. EXPECT_EQ(StatusCode::OK_200, res->status);
  15446. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15447. }
  15448. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15449. Client cli("https://yahoo.com");
  15450. auto res = cli.Get("/");
  15451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15452. ASSERT_FALSE(!res);
  15453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15454. ASSERT_FALSE(res == nullptr);
  15455. ASSERT_TRUE(res != nullptr);
  15456. EXPECT_EQ(Error::Success, res.error());
  15457. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15458. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15459. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15460. cli.set_follow_location(true);
  15461. res = cli.Get("/");
  15462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15463. EXPECT_EQ(Error::Success, res.error());
  15464. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15465. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15466. EXPECT_EQ(StatusCode::OK_200, res->status);
  15467. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15468. }
  15469. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15470. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15471. Client cli("https://cdnjs.cloudflare.com");
  15472. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15473. Headers{{"Accept-Encoding", "br"}});
  15474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15475. EXPECT_EQ(StatusCode::OK_200, res->status);
  15476. EXPECT_EQ(287630U, res->body.size());
  15477. EXPECT_EQ("application/javascript; charset=utf-8",
  15478. res->get_header_value("Content-Type"));
  15479. }
  15480. #endif
  15481. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15482. #undef REDIR_HOST // Silence compiler warning
  15483. #define REDIR_HOST "https://httpbingo.org"
  15484. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15485. Client cli(REDIR_HOST);
  15486. cli.set_follow_location(true);
  15487. auto res =
  15488. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15490. EXPECT_EQ(StatusCode::OK_200, res->status);
  15491. }
  15492. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15493. Client cli(REDIR_HOST);
  15494. cli.set_follow_location(true);
  15495. Params params;
  15496. params.emplace("url", "http://example.com");
  15497. params.emplace("status_code", "302");
  15498. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15500. EXPECT_EQ(StatusCode::OK_200, res->status);
  15501. }
  15502. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15503. Client cli(REDIR_HOST);
  15504. cli.set_follow_location(true);
  15505. Params params;
  15506. params.emplace("url", "http://example.com");
  15507. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15509. EXPECT_EQ(StatusCode::OK_200, res->status);
  15510. }
  15511. TEST(HttpToHttpsRedirectTest, CertFile) {
  15512. auto ssl_port = PORT + 1;
  15513. Server svr;
  15514. ASSERT_TRUE(svr.is_valid());
  15515. svr.Get("/index", [&](const Request &, Response &res) {
  15516. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15517. "/index");
  15518. svr.stop();
  15519. });
  15520. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15521. ASSERT_TRUE(ssl_svr.is_valid());
  15522. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15523. res.set_content("test", "text/plain");
  15524. ssl_svr.stop();
  15525. });
  15526. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15527. thread t2 =
  15528. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15529. auto se = detail::scope_exit([&] {
  15530. t2.join();
  15531. t.join();
  15532. ASSERT_FALSE(svr.is_running());
  15533. });
  15534. svr.wait_until_ready();
  15535. ssl_svr.wait_until_ready();
  15536. Client cli("127.0.0.1", PORT);
  15537. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15538. cli.enable_server_certificate_verification(true);
  15539. cli.set_follow_location(true);
  15540. cli.set_connection_timeout(30);
  15541. auto res = cli.Get("/index");
  15542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15543. ASSERT_EQ(StatusCode::OK_200, res->status);
  15544. }
  15545. TEST(SSLClientRedirectTest, CertFile) {
  15546. auto ssl_port = PORT + 1;
  15547. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15548. ASSERT_TRUE(ssl_svr1.is_valid());
  15549. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15550. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15551. "/index");
  15552. ssl_svr1.stop();
  15553. });
  15554. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15555. ASSERT_TRUE(ssl_svr2.is_valid());
  15556. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15557. res.set_content("test", "text/plain");
  15558. ssl_svr2.stop();
  15559. });
  15560. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15561. thread t2 =
  15562. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15563. auto se = detail::scope_exit([&] {
  15564. t2.join();
  15565. t.join();
  15566. ASSERT_FALSE(ssl_svr1.is_running());
  15567. });
  15568. ssl_svr1.wait_until_ready();
  15569. ssl_svr2.wait_until_ready();
  15570. SSLClient cli("127.0.0.1", PORT);
  15571. std::string cert;
  15572. read_file(SERVER_CERT2_FILE, cert);
  15573. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15574. cli.enable_server_certificate_verification(true);
  15575. cli.set_follow_location(true);
  15576. cli.set_connection_timeout(30);
  15577. auto res = cli.Get("/index");
  15578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15579. ASSERT_EQ(StatusCode::OK_200, res->status);
  15580. }
  15581. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15582. // another port, so the client follows it with a new client.
  15583. static Result GetThroughTlsRedirectToDifferentPort(
  15584. const std::function<void(SSLClient &)> &setup,
  15585. const char *target_cert = SERVER_CERT2_FILE,
  15586. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15587. auto ssl_port = PORT + 1;
  15588. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15589. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15590. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15591. "/index");
  15592. });
  15593. SSLServer ssl_svr2(target_cert, target_key);
  15594. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15595. res.set_content("test", "text/plain");
  15596. });
  15597. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15598. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15599. auto se = detail::scope_exit([&] {
  15600. ssl_svr2.stop();
  15601. ssl_svr1.stop();
  15602. t2.join();
  15603. t.join();
  15604. });
  15605. ssl_svr1.wait_until_ready();
  15606. ssl_svr2.wait_until_ready();
  15607. SSLClient cli("127.0.0.1", PORT);
  15608. cli.set_follow_location(true);
  15609. cli.set_connection_timeout(30);
  15610. setup(cli);
  15611. return cli.Get("/index");
  15612. }
  15613. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15614. auto calls = 0;
  15615. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15616. cli.enable_server_certificate_verification(false);
  15617. // Accept the first server only.
  15618. cli.set_session_verifier([&](tls::session_t) {
  15619. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15620. : SSLVerifierResponse::CertificateRejected;
  15621. });
  15622. });
  15623. ASSERT_FALSE(res);
  15624. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15625. EXPECT_EQ(2, calls);
  15626. }
  15627. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15628. std::string pinned;
  15629. auto res = GetThroughTlsRedirectToDifferentPort(
  15630. [&](SSLClient &cli) {
  15631. cli.enable_server_certificate_verification(false);
  15632. // Pin the first certificate seen.
  15633. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15634. if (pinned.empty()) { pinned = ctx.serial(); }
  15635. return ctx.serial() == pinned;
  15636. });
  15637. },
  15638. // A certificate other than the first server's.
  15639. SERVER_CERT_FILE);
  15640. EXPECT_FALSE(res);
  15641. EXPECT_FALSE(pinned.empty());
  15642. }
  15643. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15644. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15645. std::string cert;
  15646. read_file(SERVER_CERT2_FILE, cert);
  15647. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15648. });
  15649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15650. EXPECT_EQ(StatusCode::OK_200, res->status);
  15651. }
  15652. // The target's certificate is signed by the root CA, which the first server's
  15653. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15654. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15655. auto res = GetThroughTlsRedirectToDifferentPort(
  15656. [](SSLClient &cli) {
  15657. std::string root_ca, cert;
  15658. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15659. read_file(SERVER_CERT2_FILE, cert);
  15660. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15661. cli.load_ca_cert_store(cert.data(), cert.size());
  15662. cli.enable_server_hostname_verification(false);
  15663. },
  15664. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15666. EXPECT_EQ(StatusCode::OK_200, res->status);
  15667. }
  15668. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15669. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15670. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15671. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15672. auto res = GetThroughTlsRedirectToDifferentPort(
  15673. [](SSLClient &cli) {
  15674. std::string root_ca, cert;
  15675. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15676. read_file(SERVER_CERT2_FILE, cert);
  15677. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15678. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15679. cli.enable_server_hostname_verification(false);
  15680. },
  15681. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15682. ASSERT_FALSE(res);
  15683. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15684. }
  15685. #endif
  15686. #endif
  15687. #ifdef CPPHTTPLIB_SSL_ENABLED
  15688. // Test that set_ca_cert_store() skips system certs (consistent with
  15689. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15690. // should be trusted - system certs should NOT be loaded.
  15691. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15692. // Load a specific cert that is NOT a system CA cert
  15693. std::string cert;
  15694. read_file(SERVER_CERT2_FILE, cert);
  15695. SSLClient cli("google.com");
  15696. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15697. cli.enable_server_certificate_verification(true);
  15698. // This should FAIL because:
  15699. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15700. // 2. System certs should NOT be loaded when custom store is set
  15701. // If system certs WERE loaded, this would succeed
  15702. auto res = cli.Get("/");
  15703. ASSERT_FALSE(res);
  15704. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15705. }
  15706. // Same as above, but through the native store handle path. Regression test:
  15707. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15708. // merged system certs into the user-provided store.
  15709. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15710. std::string cert;
  15711. read_file(SERVER_CERT2_FILE, cert);
  15712. SSLClient cli("google.com");
  15713. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15714. cli.enable_server_certificate_verification(true);
  15715. auto res = cli.Get("/");
  15716. ASSERT_FALSE(res);
  15717. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15718. }
  15719. // A custom store set via the native handle must still verify a server whose
  15720. // cert it does contain.
  15721. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15722. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15723. ASSERT_TRUE(svr.is_valid());
  15724. svr.Get("/test", [&](const Request &, Response &res) {
  15725. res.set_content("test", "text/plain");
  15726. });
  15727. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15728. auto se = detail::scope_exit([&] {
  15729. svr.stop();
  15730. t.join();
  15731. ASSERT_FALSE(svr.is_running());
  15732. });
  15733. svr.wait_until_ready();
  15734. SSLClient cli("127.0.0.1", PORT);
  15735. std::string cert;
  15736. read_file(SERVER_CERT2_FILE, cert);
  15737. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15738. cli.enable_server_certificate_verification(true);
  15739. cli.set_connection_timeout(30);
  15740. auto res = cli.Get("/test");
  15741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15742. ASSERT_EQ(StatusCode::OK_200, res->status);
  15743. }
  15744. // CA certs loaded through the universal Client must be transferred to the
  15745. // client created internally for following an HTTPS redirect. Regression test:
  15746. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15747. // the CA data for redirect transfer.
  15748. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15749. auto ssl_port = PORT + 1;
  15750. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15751. ASSERT_TRUE(ssl_svr1.is_valid());
  15752. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15753. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15754. "/index");
  15755. });
  15756. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15757. ASSERT_TRUE(ssl_svr2.is_valid());
  15758. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15759. res.set_content("test", "text/plain");
  15760. });
  15761. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15762. thread t2 =
  15763. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15764. auto se = detail::scope_exit([&] {
  15765. ssl_svr2.stop();
  15766. ssl_svr1.stop();
  15767. t2.join();
  15768. t.join();
  15769. ASSERT_FALSE(ssl_svr1.is_running());
  15770. });
  15771. ssl_svr1.wait_until_ready();
  15772. ssl_svr2.wait_until_ready();
  15773. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15774. std::string cert;
  15775. read_file(SERVER_CERT2_FILE, cert);
  15776. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15777. cli.enable_server_certificate_verification(true);
  15778. cli.set_follow_location(true);
  15779. cli.set_connection_timeout(30);
  15780. auto res = cli.Get("/index");
  15781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15782. ASSERT_EQ(StatusCode::OK_200, res->status);
  15783. }
  15784. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15785. // so a host signed by a system CA verifies even though a custom CA is set
  15786. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15787. std::string cert;
  15788. read_file(SERVER_CERT2_FILE, cert);
  15789. SSLClient cli("google.com");
  15790. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15791. cli.enable_system_ca(true);
  15792. cli.enable_server_certificate_verification(true);
  15793. auto res = cli.Get("/");
  15794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15795. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15796. }
  15797. // The custom CA remains effective when combined with the system CA
  15798. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15799. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15800. ASSERT_TRUE(svr.is_valid());
  15801. svr.Get("/test", [&](const Request &, Response &res) {
  15802. res.set_content("test", "text/plain");
  15803. });
  15804. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15805. auto se = detail::scope_exit([&] {
  15806. svr.stop();
  15807. t.join();
  15808. ASSERT_FALSE(svr.is_running());
  15809. });
  15810. svr.wait_until_ready();
  15811. SSLClient cli("127.0.0.1", PORT);
  15812. std::string cert;
  15813. read_file(SERVER_CERT2_FILE, cert);
  15814. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15815. cli.enable_system_ca(true);
  15816. cli.enable_server_certificate_verification(true);
  15817. cli.set_connection_timeout(30);
  15818. auto res = cli.Get("/test");
  15819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15820. ASSERT_EQ(StatusCode::OK_200, res->status);
  15821. }
  15822. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15823. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15824. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15825. static CFDictionaryRef
  15826. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15827. const SecTrustSettingsResult *result) {
  15828. auto constraint =
  15829. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15830. &kCFTypeDictionaryValueCallBacks);
  15831. if (policy) {
  15832. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15833. }
  15834. if (policy_string) {
  15835. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15836. kCFStringEncodingUTF8);
  15837. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15838. CFRelease(str);
  15839. }
  15840. if (result) {
  15841. auto number_value = static_cast<SInt32>(*result);
  15842. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15843. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15844. CFRelease(number);
  15845. }
  15846. return constraint;
  15847. }
  15848. static SecTrustSettingsResult
  15849. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15850. auto trust_settings =
  15851. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15852. for (auto constraint : constraints) {
  15853. CFArrayAppendValue(trust_settings, constraint);
  15854. CFRelease(constraint);
  15855. }
  15856. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15857. CFRelease(trust_settings);
  15858. return result;
  15859. }
  15860. // The system CA loader takes a Keychain certificate as a trusted root only
  15861. // when its Trust Settings say so for SSL, not merely because it has some.
  15862. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15863. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15864. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15865. const auto deny = kSecTrustSettingsResultDeny;
  15866. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15867. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15868. auto x509_policy = SecPolicyCreateBasicX509();
  15869. // "Always Trust", which stores no constraint at all
  15870. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15871. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15872. ssl_trust_settings_result(
  15873. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15874. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15875. ssl_trust_settings_result(
  15876. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15877. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15878. ssl_trust_settings_result(
  15879. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15880. // "Never Trust", for everything or for SSL
  15881. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15882. ssl_trust_settings_result(
  15883. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15884. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15885. ssl_trust_settings_result(
  15886. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15887. // Trusted for another policy, for one host, or not at all
  15888. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15889. ssl_trust_settings_result(
  15890. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15891. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15892. ssl_trust_settings_result({make_usage_constraint(
  15893. ssl_policy, "www.example.com", &trust_root)}));
  15894. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15895. ssl_trust_settings_result(
  15896. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15897. // The first constraint that applies to SSL decides
  15898. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15899. ssl_trust_settings_result(
  15900. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15901. make_usage_constraint(nullptr, nullptr, &deny)}));
  15902. CFRelease(x509_policy);
  15903. CFRelease(ssl_policy);
  15904. }
  15905. #endif
  15906. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15907. // skip chain verification entirely (only the certificate identity was
  15908. // checked), so a server presenting an untrusted certificate with a matching
  15909. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15910. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15911. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15912. ASSERT_TRUE(svr.is_valid());
  15913. svr.Get("/test", [&](const Request &, Response &res) {
  15914. res.set_content("test", "text/plain");
  15915. });
  15916. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15917. auto se = detail::scope_exit([&] {
  15918. svr.stop();
  15919. t.join();
  15920. ASSERT_FALSE(svr.is_running());
  15921. });
  15922. svr.wait_until_ready();
  15923. SSLClient cli("127.0.0.1", PORT);
  15924. std::string cert;
  15925. // A trusted CA that did not sign the server certificate. The server cert
  15926. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15927. // this connection.
  15928. read_file(CLIENT_CA_CERT_FILE, cert);
  15929. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15930. cli.enable_server_certificate_verification(true);
  15931. cli.set_connection_timeout(30);
  15932. auto res = cli.Get("/test");
  15933. ASSERT_FALSE(res);
  15934. }
  15935. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15936. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15937. // CA that failed to come through fails verification instead of trusting them.
  15938. // (wolfSSL does not list the system CAs it loaded.)
  15939. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15940. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15941. ASSERT_TRUE(svr.is_valid());
  15942. auto port = svr.bind_to_any_port("127.0.0.1");
  15943. ASSERT_LT(0, port);
  15944. thread t = thread([&] { svr.listen_after_bind(); });
  15945. auto se = detail::scope_exit([&] {
  15946. svr.stop();
  15947. t.join();
  15948. ASSERT_FALSE(svr.is_running());
  15949. });
  15950. svr.wait_until_ready();
  15951. // The CAs a client trusts once its first request has loaded them
  15952. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15953. Client cli("https://127.0.0.1:" + std::to_string(port));
  15954. setup(cli);
  15955. cli.Get("/");
  15956. return tls::get_ca_names(cli.tls_context()).size();
  15957. };
  15958. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15959. EXPECT_EQ(0u,
  15960. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15961. }
  15962. #endif
  15963. // A TLS setting changed between requests applies to the next one, not just to
  15964. // the next connection
  15965. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15966. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15967. ASSERT_TRUE(svr.is_valid());
  15968. svr.Get("/", [](const Request &req, Response &res) {
  15969. res.set_content(std::to_string(req.remote_port), "text/plain");
  15970. });
  15971. auto port = svr.bind_to_any_port("127.0.0.1");
  15972. ASSERT_LT(0, port);
  15973. thread t = thread([&] { svr.listen_after_bind(); });
  15974. auto se = detail::scope_exit([&] {
  15975. svr.stop();
  15976. t.join();
  15977. ASSERT_FALSE(svr.is_running());
  15978. });
  15979. svr.wait_until_ready();
  15980. SSLClient cli("127.0.0.1", port);
  15981. cli.set_keep_alive(true);
  15982. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15983. cli.enable_server_certificate_verification(false);
  15984. // The port the request went out from, so a new one means a new connection
  15985. auto client_port = [&] {
  15986. auto res = cli.Get("/");
  15987. return res ? res->body : std::string();
  15988. };
  15989. auto last = client_port();
  15990. ASSERT_FALSE(last.empty());
  15991. // Setting a value it already has keeps the connection
  15992. cli.enable_server_certificate_verification(false);
  15993. cli.enable_server_hostname_verification(true);
  15994. EXPECT_EQ(last, client_port());
  15995. cli.enable_server_certificate_verification(true);
  15996. auto res = cli.Get("/");
  15997. EXPECT_FALSE(res);
  15998. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15999. std::string ca;
  16000. read_file(SERVER_CERT2_FILE, ca);
  16001. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16002. last = client_port();
  16003. ASSERT_FALSE(last.empty());
  16004. std::vector<std::function<void()>> setters = {
  16005. [&] { cli.enable_server_hostname_verification(false); },
  16006. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16007. [&] {
  16008. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16009. },
  16010. [&] {
  16011. cli.set_server_certificate_verifier(
  16012. [](const tls::VerifyContext &) { return true; });
  16013. },
  16014. [&] {
  16015. cli.set_session_verifier(
  16016. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16017. },
  16018. };
  16019. for (const auto &setter : setters) {
  16020. setter();
  16021. auto next = client_port();
  16022. ASSERT_FALSE(next.empty());
  16023. EXPECT_NE(last, next);
  16024. last = next;
  16025. }
  16026. cli.set_session_verifier(
  16027. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16028. auto handle = cli.open_stream("GET", "/");
  16029. EXPECT_FALSE(handle.is_valid());
  16030. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16031. }
  16032. // A PEM given to create_ca_store() needs no NUL after it
  16033. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16034. std::string pem;
  16035. read_file(SERVER_CERT2_FILE, pem);
  16036. auto buf = pem + "X";
  16037. auto store = tls::create_ca_store(buf.data(), pem.size());
  16038. EXPECT_TRUE(store != nullptr);
  16039. SSLClient cli("localhost");
  16040. cli.set_ca_cert_store(store);
  16041. }
  16042. // enable_system_ca(false) prevents system CA loading entirely
  16043. TEST(SSLClientTest, DisableSystemCa_Online) {
  16044. SSLClient cli("google.com");
  16045. cli.enable_system_ca(false);
  16046. cli.enable_server_certificate_verification(true);
  16047. auto res = cli.Get("/");
  16048. ASSERT_FALSE(res);
  16049. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16050. // itself when the CA chain is empty
  16051. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16052. res.error() == Error::SSLConnection);
  16053. }
  16054. // The universal Client forwards enable_system_ca()
  16055. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16056. std::string cert;
  16057. read_file(SERVER_CERT2_FILE, cert);
  16058. Client cli("https://google.com");
  16059. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16060. cli.enable_system_ca(true);
  16061. cli.enable_server_certificate_verification(true);
  16062. auto res = cli.Get("/");
  16063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16064. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16065. }
  16066. // The system CA policy must carry over to the client created internally for
  16067. // following a cross-host HTTPS redirect
  16068. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16069. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16070. ASSERT_TRUE(svr.is_valid());
  16071. svr.Get("/index", [&](const Request &, Response &res) {
  16072. res.set_redirect("https://www.google.com/");
  16073. });
  16074. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16075. auto se = detail::scope_exit([&] {
  16076. svr.stop();
  16077. t.join();
  16078. ASSERT_FALSE(svr.is_running());
  16079. });
  16080. svr.wait_until_ready();
  16081. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16082. std::string cert;
  16083. read_file(SERVER_CERT2_FILE, cert);
  16084. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16085. cli.enable_system_ca(true);
  16086. cli.enable_server_certificate_verification(true);
  16087. cli.set_follow_location(true);
  16088. cli.set_connection_timeout(30);
  16089. // Receiving any response proves the redirect client completed the TLS
  16090. // handshake with a system-CA-signed host
  16091. auto res = cli.Get("/index");
  16092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16093. }
  16094. TEST(MultipartFormDataTest, LargeData) {
  16095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16096. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16097. const ContentReader &content_reader) {
  16098. if (req.is_multipart_form_data()) {
  16099. std::vector<FormData> items;
  16100. content_reader(
  16101. [&](const FormData &file) {
  16102. items.push_back(file);
  16103. return true;
  16104. },
  16105. [&](const char *data, size_t data_length) {
  16106. items.back().content.append(data, data_length);
  16107. return true;
  16108. });
  16109. EXPECT_TRUE(std::string(items[0].name) == "document");
  16110. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16111. EXPECT_TRUE(items[0].filename == "2MB_data");
  16112. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16113. EXPECT_TRUE(items[1].name == "hello");
  16114. EXPECT_TRUE(items[1].content == "world");
  16115. EXPECT_TRUE(items[1].filename == "");
  16116. EXPECT_TRUE(items[1].content_type == "");
  16117. } else {
  16118. std::string body;
  16119. content_reader([&](const char *data, size_t data_length) {
  16120. body.append(data, data_length);
  16121. return true;
  16122. });
  16123. }
  16124. });
  16125. auto port = svr.bind_to_any_port(HOST);
  16126. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16127. auto se = detail::scope_exit([&] {
  16128. svr.stop();
  16129. t.join();
  16130. ASSERT_FALSE(svr.is_running());
  16131. });
  16132. svr.wait_until_ready();
  16133. {
  16134. std::string data(1024 * 1024 * 2, '.');
  16135. std::stringstream buffer;
  16136. buffer << data;
  16137. SSLClient cli(HOST, port);
  16138. cli.enable_server_certificate_verification(false);
  16139. UploadFormDataItems items{
  16140. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16141. {"hello", "world", "", ""},
  16142. };
  16143. auto res = cli.Post("/post", items);
  16144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16145. ASSERT_EQ(StatusCode::OK_200, res->status);
  16146. }
  16147. }
  16148. TEST(MultipartFormDataTest, DataProviderItems) {
  16149. std::random_device seed_gen;
  16150. std::mt19937 random(seed_gen());
  16151. std::string rand1;
  16152. rand1.resize(1000);
  16153. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16154. std::string rand2;
  16155. rand2.resize(3000);
  16156. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16158. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16159. const ContentReader &content_reader) {
  16160. ASSERT_FALSE(req.is_multipart_form_data());
  16161. std::string body;
  16162. content_reader([&](const char *data, size_t data_length) {
  16163. body.append(data, data_length);
  16164. return true;
  16165. });
  16166. EXPECT_EQ(body, "");
  16167. });
  16168. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16169. const ContentReader &content_reader) {
  16170. ASSERT_TRUE(req.is_multipart_form_data());
  16171. std::vector<FormData> items;
  16172. content_reader(
  16173. [&](const FormData &file) {
  16174. items.push_back(file);
  16175. return true;
  16176. },
  16177. [&](const char *data, size_t data_length) {
  16178. items.back().content.append(data, data_length);
  16179. return true;
  16180. });
  16181. ASSERT_TRUE(items.size() == 2);
  16182. EXPECT_EQ(std::string(items[0].name), "name1");
  16183. EXPECT_EQ(items[0].content, "Testing123");
  16184. EXPECT_EQ(items[0].filename, "filename1");
  16185. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16186. EXPECT_EQ(items[1].name, "name2");
  16187. EXPECT_EQ(items[1].content, "Testing456");
  16188. EXPECT_EQ(items[1].filename, "");
  16189. EXPECT_EQ(items[1].content_type, "");
  16190. });
  16191. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16192. const ContentReader &content_reader) {
  16193. ASSERT_TRUE(req.is_multipart_form_data());
  16194. std::vector<FormData> items;
  16195. content_reader(
  16196. [&](const FormData &file) {
  16197. items.push_back(file);
  16198. return true;
  16199. },
  16200. [&](const char *data, size_t data_length) {
  16201. items.back().content.append(data, data_length);
  16202. return true;
  16203. });
  16204. ASSERT_TRUE(items.size() == 2);
  16205. EXPECT_EQ(items[0].name, "name3");
  16206. EXPECT_EQ(items[0].content, rand1);
  16207. EXPECT_EQ(items[0].filename, "filename3");
  16208. EXPECT_EQ(items[0].content_type, "");
  16209. EXPECT_EQ(items[1].name, "name4");
  16210. EXPECT_EQ(items[1].content, rand2);
  16211. EXPECT_EQ(items[1].filename, "filename4");
  16212. EXPECT_EQ(items[1].content_type, "");
  16213. });
  16214. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16215. const ContentReader &content_reader) {
  16216. ASSERT_TRUE(req.is_multipart_form_data());
  16217. std::vector<FormData> items;
  16218. content_reader(
  16219. [&](const FormData &file) {
  16220. items.push_back(file);
  16221. return true;
  16222. },
  16223. [&](const char *data, size_t data_length) {
  16224. items.back().content.append(data, data_length);
  16225. return true;
  16226. });
  16227. ASSERT_TRUE(items.size() == 4);
  16228. EXPECT_EQ(std::string(items[0].name), "name1");
  16229. EXPECT_EQ(items[0].content, "Testing123");
  16230. EXPECT_EQ(items[0].filename, "filename1");
  16231. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16232. EXPECT_EQ(items[1].name, "name2");
  16233. EXPECT_EQ(items[1].content, "Testing456");
  16234. EXPECT_EQ(items[1].filename, "");
  16235. EXPECT_EQ(items[1].content_type, "");
  16236. EXPECT_EQ(items[2].name, "name3");
  16237. EXPECT_EQ(items[2].content, rand1);
  16238. EXPECT_EQ(items[2].filename, "filename3");
  16239. EXPECT_EQ(items[2].content_type, "");
  16240. EXPECT_EQ(items[3].name, "name4");
  16241. EXPECT_EQ(items[3].content, rand2);
  16242. EXPECT_EQ(items[3].filename, "filename4");
  16243. EXPECT_EQ(items[3].content_type, "");
  16244. });
  16245. auto port = svr.bind_to_any_port("localhost");
  16246. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16247. auto se = detail::scope_exit([&] {
  16248. svr.stop();
  16249. t.join();
  16250. ASSERT_FALSE(svr.is_running());
  16251. });
  16252. svr.wait_until_ready();
  16253. {
  16254. SSLClient cli("localhost", port);
  16255. cli.enable_server_certificate_verification(false);
  16256. UploadFormDataItems items{
  16257. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16258. {"name2", "Testing456", "", ""}, // not a file
  16259. };
  16260. {
  16261. auto res = cli.Post("/post-none", {}, {}, {});
  16262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16263. ASSERT_EQ(StatusCode::OK_200, res->status);
  16264. }
  16265. FormDataProviderItems providers;
  16266. {
  16267. auto res =
  16268. cli.Post("/post-items", {}, items, providers); // empty providers
  16269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16270. ASSERT_EQ(StatusCode::OK_200, res->status);
  16271. }
  16272. providers.push_back({"name3",
  16273. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16274. // test the offset is given correctly at each step
  16275. if (!offset)
  16276. sink.os.write(rand1.data(), 30);
  16277. else if (offset == 30)
  16278. sink.os.write(rand1.data() + 30, 300);
  16279. else if (offset == 330)
  16280. sink.os.write(rand1.data() + 330, 670);
  16281. else if (offset == rand1.size())
  16282. sink.done();
  16283. return true;
  16284. },
  16285. "filename3",
  16286. {}});
  16287. providers.push_back({"name4",
  16288. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16289. // test the offset is given correctly at each step
  16290. if (!offset)
  16291. sink.os.write(rand2.data(), 2000);
  16292. else if (offset == 2000)
  16293. sink.os.write(rand2.data() + 2000, 1);
  16294. else if (offset == 2001)
  16295. sink.os.write(rand2.data() + 2001, 999);
  16296. else if (offset == rand2.size())
  16297. sink.done();
  16298. return true;
  16299. },
  16300. "filename4",
  16301. {}});
  16302. {
  16303. auto res = cli.Post("/post-providers", {}, {}, providers);
  16304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16305. ASSERT_EQ(StatusCode::OK_200, res->status);
  16306. }
  16307. {
  16308. auto res = cli.Post("/post-both", {}, items, providers);
  16309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16310. ASSERT_EQ(StatusCode::OK_200, res->status);
  16311. }
  16312. }
  16313. }
  16314. TEST(MultipartFormDataTest, BadHeader) {
  16315. Server svr;
  16316. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16317. res.set_content("ok", "text/plain");
  16318. });
  16319. thread t = thread([&] { svr.listen(HOST, PORT); });
  16320. auto se = detail::scope_exit([&] {
  16321. svr.stop();
  16322. t.join();
  16323. ASSERT_FALSE(svr.is_running());
  16324. });
  16325. svr.wait_until_ready();
  16326. const std::string body =
  16327. "This is the preamble. It is to be ignored, though it\r\n"
  16328. "is a handy place for composition agents to include an\r\n"
  16329. "explanatory note to non-MIME conformant readers.\r\n"
  16330. "\r\n"
  16331. "\r\n"
  16332. "--simple boundary\r\n"
  16333. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16334. ": BAD...\r\n"
  16335. "\r\n"
  16336. "value1\r\n"
  16337. "--simple boundary\r\n"
  16338. "Content-Disposition: form-data; name=\"field2\"; "
  16339. "filename=\"example.txt\"\r\n"
  16340. "\r\n"
  16341. "value2\r\n"
  16342. "--simple boundary--\r\n"
  16343. "This is the epilogue. It is also to be ignored.\r\n";
  16344. std::string content_type =
  16345. R"(multipart/form-data; boundary="simple boundary")";
  16346. Client cli(HOST, PORT);
  16347. auto res = cli.Post("/post", body, content_type.c_str());
  16348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16350. }
  16351. TEST(MultipartFormDataTest, WithPreamble) {
  16352. Server svr;
  16353. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16354. res.set_content("ok", "text/plain");
  16355. });
  16356. thread t = thread([&] { svr.listen(HOST, PORT); });
  16357. auto se = detail::scope_exit([&] {
  16358. svr.stop();
  16359. t.join();
  16360. ASSERT_FALSE(svr.is_running());
  16361. });
  16362. svr.wait_until_ready();
  16363. const std::string body =
  16364. "This is the preamble. It is to be ignored, though it\r\n"
  16365. "is a handy place for composition agents to include an\r\n"
  16366. "explanatory note to non-MIME conformant readers.\r\n"
  16367. "\r\n"
  16368. "\r\n"
  16369. "--simple boundary\r\n"
  16370. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16371. "\r\n"
  16372. "value1\r\n"
  16373. "--simple boundary\r\n"
  16374. "Content-Disposition: form-data; name=\"field2\"; "
  16375. "filename=\"example.txt\"\r\n"
  16376. "\r\n"
  16377. "value2\r\n"
  16378. "--simple boundary--\r\n"
  16379. "This is the epilogue. It is also to be ignored.\r\n";
  16380. std::string content_type =
  16381. R"(multipart/form-data; boundary="simple boundary")";
  16382. Client cli(HOST, PORT);
  16383. auto res = cli.Post("/post", body, content_type.c_str());
  16384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16385. EXPECT_EQ(StatusCode::OK_200, res->status);
  16386. }
  16387. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16389. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16390. const ContentReader &content_reader) {
  16391. if (req.is_multipart_form_data()) {
  16392. std::vector<FormData> items;
  16393. content_reader(
  16394. [&](const FormData &file) {
  16395. items.push_back(file);
  16396. return true;
  16397. },
  16398. [&](const char *data, size_t data_length) {
  16399. items.back().content.append(data, data_length);
  16400. return true;
  16401. });
  16402. EXPECT_TRUE(std::string(items[0].name) == "document");
  16403. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16404. EXPECT_TRUE(items[0].filename == "2MB_data");
  16405. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16406. EXPECT_TRUE(items[1].name == "hello");
  16407. EXPECT_TRUE(items[1].content == "world");
  16408. EXPECT_TRUE(items[1].filename == "");
  16409. EXPECT_TRUE(items[1].content_type == "");
  16410. } else {
  16411. std::string body;
  16412. content_reader([&](const char *data, size_t data_length) {
  16413. body.append(data, data_length);
  16414. return true;
  16415. });
  16416. }
  16417. });
  16418. auto port = svr.bind_to_any_port("localhost");
  16419. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16420. auto se = detail::scope_exit([&] {
  16421. svr.stop();
  16422. t.join();
  16423. ASSERT_FALSE(svr.is_running());
  16424. });
  16425. svr.wait_until_ready();
  16426. {
  16427. std::string data(1024 * 1024 * 2, '.');
  16428. std::stringstream buffer;
  16429. buffer << data;
  16430. SSLClient cli("localhost", port);
  16431. cli.enable_server_certificate_verification(false);
  16432. UploadFormDataItems items{
  16433. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16434. {"hello", "world", "", ""},
  16435. };
  16436. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16438. ASSERT_EQ(StatusCode::OK_200, res->status);
  16439. }
  16440. }
  16441. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16442. std::string data(1024 * 1024 * 2, '&');
  16443. std::stringstream buffer;
  16444. buffer << data;
  16445. Client cli("https://localhost:8080");
  16446. UploadFormDataItems items{
  16447. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16448. {"hello", "world", "", ""},
  16449. };
  16450. for (const char &c : " \t\r\n") {
  16451. auto res =
  16452. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16453. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16454. ASSERT_FALSE(res);
  16455. }
  16456. }
  16457. TEST(MultipartFormDataTest, PutFormData) {
  16458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16459. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16460. const ContentReader &content_reader) {
  16461. if (req.is_multipart_form_data()) {
  16462. std::vector<FormData> items;
  16463. content_reader(
  16464. [&](const FormData &file) {
  16465. items.push_back(file);
  16466. return true;
  16467. },
  16468. [&](const char *data, size_t data_length) {
  16469. items.back().content.append(data, data_length);
  16470. return true;
  16471. });
  16472. EXPECT_TRUE(std::string(items[0].name) == "document");
  16473. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16474. EXPECT_TRUE(items[0].filename == "2MB_data");
  16475. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16476. EXPECT_TRUE(items[1].name == "hello");
  16477. EXPECT_TRUE(items[1].content == "world");
  16478. EXPECT_TRUE(items[1].filename == "");
  16479. EXPECT_TRUE(items[1].content_type == "");
  16480. } else {
  16481. std::string body;
  16482. content_reader([&](const char *data, size_t data_length) {
  16483. body.append(data, data_length);
  16484. return true;
  16485. });
  16486. }
  16487. });
  16488. auto port = svr.bind_to_any_port("localhost");
  16489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16490. auto se = detail::scope_exit([&] {
  16491. svr.stop();
  16492. t.join();
  16493. ASSERT_FALSE(svr.is_running());
  16494. });
  16495. svr.wait_until_ready();
  16496. {
  16497. std::string data(1024 * 1024 * 2, '&');
  16498. std::stringstream buffer;
  16499. buffer << data;
  16500. SSLClient cli("localhost", port);
  16501. cli.enable_server_certificate_verification(false);
  16502. UploadFormDataItems items{
  16503. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16504. {"hello", "world", "", ""},
  16505. };
  16506. auto res = cli.Put("/put", items);
  16507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16508. ASSERT_EQ(StatusCode::OK_200, res->status);
  16509. }
  16510. }
  16511. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16513. svr.Put("/put_customboundary",
  16514. [&](const Request &req, const Response & /*res*/,
  16515. const ContentReader &content_reader) {
  16516. if (req.is_multipart_form_data()) {
  16517. std::vector<FormData> items;
  16518. content_reader(
  16519. [&](const FormData &file) {
  16520. items.push_back(file);
  16521. return true;
  16522. },
  16523. [&](const char *data, size_t data_length) {
  16524. items.back().content.append(data, data_length);
  16525. return true;
  16526. });
  16527. EXPECT_TRUE(std::string(items[0].name) == "document");
  16528. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16529. EXPECT_TRUE(items[0].filename == "2MB_data");
  16530. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16531. EXPECT_TRUE(items[1].name == "hello");
  16532. EXPECT_TRUE(items[1].content == "world");
  16533. EXPECT_TRUE(items[1].filename == "");
  16534. EXPECT_TRUE(items[1].content_type == "");
  16535. } else {
  16536. std::string body;
  16537. content_reader([&](const char *data, size_t data_length) {
  16538. body.append(data, data_length);
  16539. return true;
  16540. });
  16541. }
  16542. });
  16543. auto port = svr.bind_to_any_port("localhost");
  16544. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16545. auto se = detail::scope_exit([&] {
  16546. svr.stop();
  16547. t.join();
  16548. ASSERT_FALSE(svr.is_running());
  16549. });
  16550. svr.wait_until_ready();
  16551. {
  16552. std::string data(1024 * 1024 * 2, '&');
  16553. std::stringstream buffer;
  16554. buffer << data;
  16555. SSLClient cli("localhost", port);
  16556. cli.enable_server_certificate_verification(false);
  16557. UploadFormDataItems items{
  16558. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16559. {"hello", "world", "", ""},
  16560. };
  16561. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16563. ASSERT_EQ(StatusCode::OK_200, res->status);
  16564. }
  16565. }
  16566. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16567. std::string data(1024 * 1024 * 2, '&');
  16568. std::stringstream buffer;
  16569. buffer << data;
  16570. Client cli("https://localhost:8080");
  16571. cli.enable_server_certificate_verification(false);
  16572. UploadFormDataItems items{
  16573. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16574. {"hello", "world", "", ""},
  16575. };
  16576. for (const char &c : " \t\r\n") {
  16577. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16578. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16579. ASSERT_FALSE(res);
  16580. }
  16581. }
  16582. TEST(MultipartFormDataTest, AlternateFilename) {
  16583. auto handled = false;
  16584. Server svr;
  16585. svr.Post("/test", [&](const Request &req, Response &res) {
  16586. ASSERT_EQ(2u, req.form.files.size());
  16587. ASSERT_EQ(1u, req.form.fields.size());
  16588. // Test files
  16589. const auto &file1 = req.form.get_file("file1");
  16590. ASSERT_EQ("file1", file1.name);
  16591. ASSERT_EQ("A.txt", file1.filename);
  16592. ASSERT_EQ("text/plain", file1.content_type);
  16593. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16594. const auto &file2 = req.form.get_file("file2");
  16595. ASSERT_EQ("file2", file2.name);
  16596. ASSERT_EQ("a.html", file2.filename);
  16597. ASSERT_EQ("text/html", file2.content_type);
  16598. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16599. file2.content);
  16600. // Test text field
  16601. const auto &text = req.form.get_field("text");
  16602. ASSERT_EQ("text default", text);
  16603. res.set_content("ok", "text/plain");
  16604. handled = true;
  16605. });
  16606. thread t = thread([&] { svr.listen(HOST, PORT); });
  16607. auto se = detail::scope_exit([&] {
  16608. svr.stop();
  16609. t.join();
  16610. ASSERT_FALSE(svr.is_running());
  16611. ASSERT_TRUE(handled);
  16612. });
  16613. svr.wait_until_ready();
  16614. auto req = "POST /test HTTP/1.1\r\n"
  16615. "Host: localhost\r\n"
  16616. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16617. "Content-Length: 399\r\n"
  16618. "\r\n"
  16619. "----------\r\n"
  16620. "Content-Disposition: form-data; name=\"text\"\r\n"
  16621. "\r\n"
  16622. "text default\r\n"
  16623. "----------\r\n"
  16624. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16625. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16626. "Content-Type: text/plain\r\n"
  16627. "\r\n"
  16628. "Content of a.txt.\r\n"
  16629. "\r\n"
  16630. "----------\r\n"
  16631. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16632. "\"a.html\"\r\n"
  16633. "Content-Type: text/html\r\n"
  16634. "\r\n"
  16635. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16636. "\r\n"
  16637. "------------\r\n";
  16638. ASSERT_TRUE(send_request(1, req));
  16639. }
  16640. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16641. auto handled = false;
  16642. Server svr;
  16643. svr.Post("/test", [&](const Request &req, Response &res) {
  16644. // Case-insensitive "utf-8''" prefix with a long value
  16645. const auto &file = req.form.get_file("file1");
  16646. ASSERT_EQ("file1", file.name);
  16647. // 8000 chars exercises both the Content-Disposition parser and the
  16648. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16649. // Prior to the fix, std::regex_match on this header would cause O(N)
  16650. // stack recursion in libstdc++, leading to SIGSEGV.
  16651. std::string expected_filename(8000, 'A');
  16652. ASSERT_EQ(expected_filename, file.filename);
  16653. res.set_content("ok", "text/plain");
  16654. handled = true;
  16655. });
  16656. thread t = thread([&] { svr.listen(HOST, PORT); });
  16657. auto se = detail::scope_exit([&] {
  16658. svr.stop();
  16659. t.join();
  16660. ASSERT_FALSE(svr.is_running());
  16661. ASSERT_TRUE(handled);
  16662. });
  16663. svr.wait_until_ready();
  16664. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16665. // Regression test for GHSA-qq6v-r583-3h69
  16666. std::string long_filename(8000, 'A');
  16667. std::string body = "----------\r\n"
  16668. "Content-Disposition: form-data; name=\"file1\"; "
  16669. "filename*=\"Utf-8''" +
  16670. long_filename +
  16671. "\"\r\n"
  16672. "\r\n"
  16673. "hello\r\n"
  16674. "------------\r\n";
  16675. auto req = "POST /test HTTP/1.1\r\n"
  16676. "Host: localhost\r\n"
  16677. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16678. "Content-Length: " +
  16679. std::to_string(body.size()) + "\r\n\r\n" + body;
  16680. ASSERT_TRUE(send_request(1, req));
  16681. }
  16682. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16683. auto handled = false;
  16684. Server svr;
  16685. svr.Post("/test", [&](const Request &req, Response &) {
  16686. ASSERT_EQ(2u, req.form.fields.size());
  16687. const auto &text1 = req.form.get_field("text1");
  16688. ASSERT_EQ("text1", text1);
  16689. const auto &text2 = req.form.get_field("text2");
  16690. ASSERT_EQ("text2", text2);
  16691. handled = true;
  16692. });
  16693. thread t = thread([&] { svr.listen(HOST, PORT); });
  16694. auto se = detail::scope_exit([&] {
  16695. svr.stop();
  16696. t.join();
  16697. ASSERT_FALSE(svr.is_running());
  16698. ASSERT_TRUE(handled);
  16699. });
  16700. svr.wait_until_ready();
  16701. auto req = "POST /test HTTP/1.1\r\n"
  16702. "Host: localhost\r\n"
  16703. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16704. "Content-Length: 146\r\n"
  16705. "\r\n----------\r\n"
  16706. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16707. "\r\n"
  16708. "text1"
  16709. "\r\n----------\r\n"
  16710. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16711. "\r\n"
  16712. "text2"
  16713. "\r\n------------";
  16714. std::string response;
  16715. ASSERT_TRUE(send_request(1, req, &response));
  16716. ASSERT_EQ("200", response.substr(9, 3));
  16717. }
  16718. TEST(MultipartFormDataTest, ContentLength) {
  16719. auto handled = false;
  16720. Server svr;
  16721. svr.Post("/test", [&](const Request &req, Response &) {
  16722. ASSERT_EQ(2u, req.form.fields.size());
  16723. const auto &text1 = req.form.get_field("text1");
  16724. ASSERT_EQ("text1", text1);
  16725. const auto &text2 = req.form.get_field("text2");
  16726. ASSERT_EQ("text2", text2);
  16727. handled = true;
  16728. });
  16729. thread t = thread([&] { svr.listen(HOST, PORT); });
  16730. auto se = detail::scope_exit([&] {
  16731. svr.stop();
  16732. t.join();
  16733. ASSERT_FALSE(svr.is_running());
  16734. ASSERT_TRUE(handled);
  16735. });
  16736. svr.wait_until_ready();
  16737. auto req = "POST /test HTTP/1.1\r\n"
  16738. "Host: localhost\r\n"
  16739. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16740. "Content-Length: 167\r\n"
  16741. "\r\n----------\r\n"
  16742. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16743. "Content-Length: 5\r\n"
  16744. "\r\n"
  16745. "text1"
  16746. "\r\n----------\r\n"
  16747. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16748. "\r\n"
  16749. "text2"
  16750. "\r\n------------\r\n";
  16751. std::string response;
  16752. ASSERT_TRUE(send_request(1, req, &response));
  16753. ASSERT_EQ("200", response.substr(9, 3));
  16754. }
  16755. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16756. auto handled = false;
  16757. Server svr;
  16758. svr.Post("/test", [&](const Request &req, Response &) {
  16759. ASSERT_EQ(2u, req.form.fields.size());
  16760. const auto &text1 = req.form.get_field("text1");
  16761. ASSERT_EQ("text1", text1);
  16762. // TODO: Add header access for text fields if needed
  16763. const auto &text2 = req.form.get_field("text2");
  16764. ASSERT_EQ("text2", text2);
  16765. // TODO: Header access for text fields needs to be implemented
  16766. // auto &headers = it->second.headers;
  16767. // ASSERT_EQ(3U, headers.size());
  16768. // auto custom_header = headers.find("x-whatever");
  16769. // ASSERT_TRUE(custom_header != headers.end());
  16770. // ASSERT_NE("customvalue", custom_header->second);
  16771. // ASSERT_EQ("CustomValue", custom_header->second);
  16772. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16773. handled = true;
  16774. });
  16775. thread t = thread([&] { svr.listen(HOST, PORT); });
  16776. auto se = detail::scope_exit([&] {
  16777. svr.stop();
  16778. t.join();
  16779. ASSERT_FALSE(svr.is_running());
  16780. ASSERT_TRUE(handled);
  16781. });
  16782. svr.wait_until_ready();
  16783. auto req = "POST /test HTTP/1.1\r\n"
  16784. "Host: localhost\r\n"
  16785. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16786. "Content-Length: 232\r\n"
  16787. "\r\n----------\r\n"
  16788. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16789. "Content-Length: 5\r\n"
  16790. "X-Test: 1\r\n"
  16791. "\r\n"
  16792. "text1"
  16793. "\r\n----------\r\n"
  16794. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16795. "Content-Type: text/plain\r\n"
  16796. "X-Whatever: CustomValue\r\n"
  16797. "\r\n"
  16798. "text2"
  16799. "\r\n------------\r\n"
  16800. "That should be disregarded. Not even read";
  16801. std::string response;
  16802. ASSERT_TRUE(send_request(1, req, &response));
  16803. ASSERT_EQ("200", response.substr(9, 3));
  16804. }
  16805. TEST(MultipartFormDataTest, LargeHeader) {
  16806. auto handled = false;
  16807. Server svr;
  16808. svr.Post("/test", [&](const Request &req, Response &) {
  16809. ASSERT_EQ(1u, req.form.fields.size());
  16810. const auto &text = req.form.get_field("name1");
  16811. ASSERT_EQ("text1", text);
  16812. handled = true;
  16813. });
  16814. thread t = thread([&] { svr.listen(HOST, PORT); });
  16815. auto se = detail::scope_exit([&] {
  16816. svr.stop();
  16817. t.join();
  16818. ASSERT_FALSE(svr.is_running());
  16819. ASSERT_TRUE(handled);
  16820. });
  16821. svr.wait_until_ready();
  16822. auto boundary = std::string("cpp-httplib-multipart-data");
  16823. std::string content = "--" + boundary +
  16824. "\r\n"
  16825. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16826. "\r\n"
  16827. "text1\r\n"
  16828. "--" +
  16829. boundary + "--\r\n";
  16830. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16831. "Host: localhost\r\n"
  16832. "Content-Type: multipart/form-data;boundary=" +
  16833. boundary +
  16834. "\r\n"
  16835. "Content-Length: " +
  16836. std::to_string(content.size()) +
  16837. "\r\n"
  16838. "Dummy-Header: ";
  16839. std::string header_suffix = "\r\n"
  16840. "\r\n";
  16841. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16842. size_t header_dummy_size =
  16843. read_buff_size -
  16844. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16845. auto header_dummy = std::string(header_dummy_size, '@');
  16846. auto req = header_prefix + header_dummy + header_suffix + content;
  16847. std::string response;
  16848. ASSERT_TRUE(send_request(1, req, &response));
  16849. ASSERT_EQ("200", response.substr(9, 3));
  16850. }
  16851. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16852. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16853. // (not chunked Transfer-Encoding) after the streaming refactor.
  16854. auto handled = false;
  16855. Server svr;
  16856. svr.Post("/upload", [&](const Request &req, Response &res) {
  16857. auto cl_it = req.headers.find("Content-Length");
  16858. EXPECT_TRUE(cl_it != req.headers.end());
  16859. auto te_it = req.headers.find("Transfer-Encoding");
  16860. EXPECT_TRUE(te_it == req.headers.end());
  16861. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16862. res.set_content("ok", "text/plain");
  16863. handled = true;
  16864. });
  16865. auto port = svr.bind_to_any_port(HOST);
  16866. auto t = thread([&] { svr.listen_after_bind(); });
  16867. auto se = detail::scope_exit([&] {
  16868. svr.stop();
  16869. t.join();
  16870. ASSERT_FALSE(svr.is_running());
  16871. ASSERT_TRUE(handled);
  16872. });
  16873. svr.wait_until_ready();
  16874. UploadFormDataItems items = {
  16875. {"field1", "hello", "", "text/plain"},
  16876. {"file1", "world", "test.txt", "application/octet-stream"},
  16877. };
  16878. Client cli(HOST, port);
  16879. auto res = cli.Post("/upload", {}, items);
  16880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16881. EXPECT_EQ(StatusCode::OK_200, res->status);
  16882. }
  16883. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16884. // Verify that make_multipart_content_provider coalesces many small segments
  16885. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16886. constexpr size_t kItemCount = 1000;
  16887. UploadFormDataItems items;
  16888. items.reserve(kItemCount);
  16889. for (size_t i = 0; i < kItemCount; i++) {
  16890. items.push_back(
  16891. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16892. }
  16893. const std::string boundary = "----test-boundary";
  16894. auto content_length = detail::get_multipart_content_length(items, boundary);
  16895. auto provider = detail::make_multipart_content_provider(items, boundary);
  16896. // Drive the provider the same way write_content_with_progress does
  16897. size_t write_count = 0;
  16898. size_t total_bytes = 0;
  16899. DataSink sink;
  16900. size_t offset = 0;
  16901. sink.write = [&](const char *d, size_t l) -> bool {
  16902. (void)d;
  16903. write_count++;
  16904. total_bytes += l;
  16905. offset += l;
  16906. return true;
  16907. };
  16908. sink.is_writable = []() -> bool { return true; };
  16909. while (offset < content_length) {
  16910. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16911. }
  16912. EXPECT_EQ(content_length, total_bytes);
  16913. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16914. // With buffering into 64KB blocks, write_count should be much smaller.
  16915. auto segment_count = 3 * kItemCount + 1;
  16916. EXPECT_LT(write_count, segment_count / 10);
  16917. }
  16918. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16919. // Integration test: send many UploadFormDataItems and verify the server
  16920. // receives all of them correctly (#2410).
  16921. constexpr size_t kItemCount = 500;
  16922. auto handled = false;
  16923. Server svr;
  16924. svr.Post("/upload", [&](const Request &req, Response &res) {
  16925. EXPECT_EQ(kItemCount, req.form.fields.size());
  16926. for (size_t i = 0; i < kItemCount; i++) {
  16927. auto key = "field" + std::to_string(i);
  16928. auto val = "value" + std::to_string(i);
  16929. auto it = req.form.fields.find(key);
  16930. if (it != req.form.fields.end()) {
  16931. EXPECT_EQ(val, it->second.content);
  16932. } else {
  16933. ADD_FAILURE() << "Missing field: " << key;
  16934. }
  16935. }
  16936. res.set_content("ok", "text/plain");
  16937. handled = true;
  16938. });
  16939. auto port = svr.bind_to_any_port(HOST);
  16940. auto t = thread([&] { svr.listen_after_bind(); });
  16941. auto se = detail::scope_exit([&] {
  16942. svr.stop();
  16943. t.join();
  16944. ASSERT_FALSE(svr.is_running());
  16945. ASSERT_TRUE(handled);
  16946. });
  16947. svr.wait_until_ready();
  16948. UploadFormDataItems items;
  16949. items.reserve(kItemCount);
  16950. for (size_t i = 0; i < kItemCount; i++) {
  16951. items.push_back(
  16952. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16953. }
  16954. Client cli(HOST, port);
  16955. auto res = cli.Post("/upload", items);
  16956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16957. EXPECT_EQ(StatusCode::OK_200, res->status);
  16958. }
  16959. TEST(MultipartFormDataTest, MakeFileProvider) {
  16960. // Verify make_file_provider sends a file's contents correctly.
  16961. const std::string file_content(4096, 'Z');
  16962. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16963. {
  16964. std::ofstream ofs(tmp_path, std::ios::binary);
  16965. ofs.write(file_content.data(),
  16966. static_cast<std::streamsize>(file_content.size()));
  16967. }
  16968. auto handled = false;
  16969. Server svr;
  16970. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16971. const ContentReader &content_reader) {
  16972. ASSERT_TRUE(req.is_multipart_form_data());
  16973. std::vector<FormData> items;
  16974. content_reader(
  16975. [&](const FormData &file) {
  16976. items.push_back(file);
  16977. return true;
  16978. },
  16979. [&](const char *data, size_t data_length) {
  16980. items.back().content.append(data, data_length);
  16981. return true;
  16982. });
  16983. ASSERT_EQ(1u, items.size());
  16984. EXPECT_EQ("myfile", items[0].name);
  16985. EXPECT_EQ("data.bin", items[0].filename);
  16986. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16987. EXPECT_EQ(file_content, items[0].content);
  16988. handled = true;
  16989. });
  16990. auto port = svr.bind_to_any_port(HOST);
  16991. auto t = thread([&] { svr.listen_after_bind(); });
  16992. auto se = detail::scope_exit([&] {
  16993. svr.stop();
  16994. t.join();
  16995. ASSERT_FALSE(svr.is_running());
  16996. ASSERT_TRUE(handled);
  16997. std::remove(tmp_path.c_str());
  16998. });
  16999. svr.wait_until_ready();
  17000. FormDataProviderItems providers;
  17001. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17002. "application/octet-stream"));
  17003. Client cli(HOST, port);
  17004. auto res = cli.Post("/upload", {}, {}, providers);
  17005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17006. EXPECT_EQ(StatusCode::OK_200, res->status);
  17007. }
  17008. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17009. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17010. // (100) headers is rejected with a 400 Bad Request response.
  17011. Server svr;
  17012. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17013. res.set_content("ok", "text/plain");
  17014. });
  17015. thread t = thread([&] { svr.listen(HOST, PORT); });
  17016. auto se = detail::scope_exit([&] {
  17017. svr.stop();
  17018. t.join();
  17019. ASSERT_FALSE(svr.is_running());
  17020. });
  17021. svr.wait_until_ready();
  17022. // Build a multipart part with 101 custom headers (exceeding
  17023. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17024. std::stringstream body;
  17025. body << "--simpleboundary\r\n"
  17026. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17027. for (int i = 0; i < 101; i++) {
  17028. body << "X-Custom-Header-" << i << ": value\r\n";
  17029. }
  17030. body << "\r\n"
  17031. << "value1\r\n"
  17032. << "--simpleboundary--\r\n";
  17033. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17034. Client cli(HOST, PORT);
  17035. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17037. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17038. }
  17039. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17040. // A body that never contains the declared boundary must not be accumulated
  17041. // while the parser waits for it. Buffering it would also make every read
  17042. // rescan everything seen so far, which is quadratic in the body size.
  17043. Server svr;
  17044. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17045. res.set_content("ok", "text/plain");
  17046. });
  17047. auto port = svr.bind_to_any_port(HOST);
  17048. thread t = thread([&] { svr.listen_after_bind(); });
  17049. auto se = detail::scope_exit([&] {
  17050. svr.stop();
  17051. t.join();
  17052. ASSERT_FALSE(svr.is_running());
  17053. });
  17054. svr.wait_until_ready();
  17055. Client cli(HOST, port);
  17056. cli.set_read_timeout(60, 0);
  17057. cli.set_write_timeout(60, 0);
  17058. // '-' is the worst case: it matches the first character of the boundary, so
  17059. // every position has to be checked against it.
  17060. auto post_dashes = [&](size_t size) {
  17061. const std::string body(size, '-');
  17062. auto start = std::chrono::steady_clock::now();
  17063. auto res =
  17064. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17065. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17066. std::chrono::steady_clock::now() - start)
  17067. .count();
  17068. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17069. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17070. return ms;
  17071. };
  17072. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17073. // Windows.
  17074. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17075. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17076. // Comparing the two sizes rather than checking an absolute duration keeps
  17077. // this meaningful across build types and CI load, both of which move the
  17078. // absolute numbers by more than an order of magnitude. Four times the bytes
  17079. // costs about four times the time when parsing is linear, and about sixteen
  17080. // times when the body is buffered and rescanned.
  17081. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17082. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17083. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17084. << "ms, which suggests the body is being buffered and rescanned";
  17085. }
  17086. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17087. // A boundary can only be followed by CRLF or by "--", so anything else is
  17088. // malformed no matter what comes next. The parser must say so right away
  17089. // instead of buffering the rest of the declared body.
  17090. Server svr;
  17091. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17092. res.set_content("ok", "text/plain");
  17093. });
  17094. auto port = svr.bind_to_any_port(HOST);
  17095. thread t = thread([&] { svr.listen_after_bind(); });
  17096. auto se = detail::scope_exit([&] {
  17097. svr.stop();
  17098. t.join();
  17099. ASSERT_FALSE(svr.is_running());
  17100. });
  17101. svr.wait_until_ready();
  17102. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17103. // buffers instead of failing would still be waiting for the remaining bytes.
  17104. const std::string body = "--zzzz\r\n"
  17105. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17106. "\r\n"
  17107. "text1"
  17108. "\r\n--zzzzXX";
  17109. const std::string req = "POST /post HTTP/1.1\r\n"
  17110. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17111. "Content-Length: 1048576\r\n"
  17112. "\r\n" +
  17113. body;
  17114. std::string response;
  17115. ASSERT_TRUE(send_request(3, req, &response, port));
  17116. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17117. EXPECT_EQ("400", response.substr(9, 3));
  17118. }
  17119. // Posts a multipart body split into two writes, so that the server sees the
  17120. // split at whatever offset the caller chose, and expects the single "text1"
  17121. // field to come through.
  17122. static void expect_split_multipart_ok(const std::string &body1,
  17123. const std::string &body2) {
  17124. auto handled = false;
  17125. Server svr;
  17126. svr.Post("/post", [&](const Request &req, Response &) {
  17127. EXPECT_EQ(1u, req.form.fields.size());
  17128. EXPECT_EQ("text1", req.form.get_field("text1"));
  17129. handled = true;
  17130. });
  17131. auto port = svr.bind_to_any_port(HOST);
  17132. thread t = thread([&] { svr.listen_after_bind(); });
  17133. auto se = detail::scope_exit([&] {
  17134. svr.stop();
  17135. t.join();
  17136. ASSERT_FALSE(svr.is_running());
  17137. ASSERT_TRUE(handled);
  17138. });
  17139. svr.wait_until_ready();
  17140. // "Connection: close" makes the server close once it has answered, so the
  17141. // response drain ends immediately instead of idling until the read timeout.
  17142. const std::string head =
  17143. "POST /post HTTP/1.1\r\n"
  17144. "Host: localhost\r\n"
  17145. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17146. "Connection: close\r\n"
  17147. "Content-Length: " +
  17148. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17149. std::string response;
  17150. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17151. ASSERT_GE(response.size(), 12u) << "no response";
  17152. EXPECT_EQ("200", response.substr(9, 3));
  17153. }
  17154. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17155. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17156. // ignored, including when it does not arrive in the same read as the
  17157. // close-delimiter itself.
  17158. expect_split_multipart_ok("--zzzz\r\n"
  17159. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17160. "\r\n"
  17161. "text1"
  17162. "\r\n--zzzz--",
  17163. "\r\nthis epilogue must be ignored\r\n");
  17164. }
  17165. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17166. // The initial boundary may be preceded by a preamble of any length and may
  17167. // straddle a read boundary. Discarding data while waiting for it must not
  17168. // throw away a partial boundary sitting at the end of the buffer.
  17169. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17170. "zz\r\n"
  17171. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17172. "\r\n"
  17173. "text1"
  17174. "\r\n--zzzz--\r\n");
  17175. }
  17176. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17177. // The received boundary was only checked for being non-empty, so it could be
  17178. // as long as a header is allowed to be. The parser scans the body for
  17179. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17180. // costs a nearly full comparison at nearly every position, making the
  17181. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17182. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17183. Server svr;
  17184. svr.Post("/post", [](const Request &req, Response &res) {
  17185. EXPECT_EQ(1u, req.form.fields.size());
  17186. EXPECT_EQ("text1", req.form.get_field("text1"));
  17187. res.set_content("ok", "text/plain");
  17188. });
  17189. auto port = svr.bind_to_any_port(HOST);
  17190. thread t = thread([&] { svr.listen_after_bind(); });
  17191. auto se = detail::scope_exit([&] {
  17192. svr.stop();
  17193. t.join();
  17194. ASSERT_FALSE(svr.is_running());
  17195. });
  17196. svr.wait_until_ready();
  17197. Client cli(HOST, port);
  17198. auto post_with_boundary_of_length = [&](size_t len) {
  17199. const std::string boundary(len, 'a');
  17200. const std::string body =
  17201. "--" + boundary +
  17202. "\r\n"
  17203. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17204. "\r\n"
  17205. "text1"
  17206. "\r\n--" +
  17207. boundary + "--\r\n";
  17208. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17209. };
  17210. auto res = post_with_boundary_of_length(70);
  17211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17212. EXPECT_EQ(StatusCode::OK_200, res->status);
  17213. res = post_with_boundary_of_length(71);
  17214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17215. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17216. }
  17217. TEST(MakeFileBodyTest, Basic) {
  17218. const std::string file_content(4096, 'Z');
  17219. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17220. {
  17221. std::ofstream ofs(tmp_path, std::ios::binary);
  17222. ofs.write(file_content.data(),
  17223. static_cast<std::streamsize>(file_content.size()));
  17224. }
  17225. auto handled = false;
  17226. Server svr;
  17227. svr.Post("/upload", [&](const Request &req, Response &res) {
  17228. EXPECT_EQ(file_content, req.body);
  17229. handled = true;
  17230. res.status = StatusCode::OK_200;
  17231. });
  17232. auto port = svr.bind_to_any_port(HOST);
  17233. auto t = thread([&] { svr.listen_after_bind(); });
  17234. auto se = detail::scope_exit([&] {
  17235. svr.stop();
  17236. t.join();
  17237. ASSERT_FALSE(svr.is_running());
  17238. ASSERT_TRUE(handled);
  17239. std::remove(tmp_path.c_str());
  17240. });
  17241. svr.wait_until_ready();
  17242. auto fb = make_file_body(tmp_path);
  17243. ASSERT_GT(fb.first, 0u);
  17244. Client cli(HOST, port);
  17245. auto res =
  17246. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17248. EXPECT_EQ(StatusCode::OK_200, res->status);
  17249. }
  17250. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17251. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17252. {
  17253. std::ofstream ofs(path, std::ios::binary);
  17254. const std::string content(100, 'A');
  17255. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17256. }
  17257. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17258. auto body = make_file_body(path);
  17259. ASSERT_EQ(100u, body.first);
  17260. ASSERT_TRUE(static_cast<bool>(body.second));
  17261. // Rewritten shorter after its length was measured - and, on a server, after
  17262. // that length has already gone out as Content-Length.
  17263. {
  17264. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17265. const std::string content(10, 'A');
  17266. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17267. }
  17268. std::string written;
  17269. DataSink sink;
  17270. sink.write = [&](const char *d, size_t l) {
  17271. written.append(d, l);
  17272. return true;
  17273. };
  17274. // The provider has to report failure. write_content_with_progress() advances
  17275. // its offset only by what was written, so a provider that returns true
  17276. // without completing the length it promised is called again straight away,
  17277. // and again.
  17278. EXPECT_FALSE(body.second(0, body.first, sink));
  17279. EXPECT_EQ(std::string(10, 'A'), written);
  17280. }
  17281. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17282. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17283. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17284. {
  17285. std::ofstream ofs(path, std::ios::binary);
  17286. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17287. }
  17288. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17289. auto body = make_file_body(path);
  17290. ASSERT_EQ(content.size(), body.first);
  17291. ASSERT_TRUE(static_cast<bool>(body.second));
  17292. std::string written;
  17293. DataSink sink;
  17294. sink.write = [&](const char *d, size_t l) {
  17295. written.append(d, l);
  17296. return true;
  17297. };
  17298. EXPECT_TRUE(body.second(0, body.first, sink));
  17299. EXPECT_EQ(content, written);
  17300. }
  17301. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17302. static constexpr unsigned int number_of_tasks{1000000};
  17303. std::atomic_uint count{0};
  17304. std::unique_ptr<TaskQueue> task_queue{
  17305. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17306. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17307. auto queued = task_queue->enqueue(
  17308. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17309. EXPECT_TRUE(queued);
  17310. }
  17311. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17312. task_queue->shutdown();
  17313. #else
  17314. EXPECT_NO_THROW(task_queue->shutdown());
  17315. #endif
  17316. EXPECT_EQ(number_of_tasks, count.load());
  17317. }
  17318. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17319. static constexpr unsigned int number_of_tasks{1000000};
  17320. static constexpr unsigned int qlimit{2};
  17321. unsigned int queued_count{0};
  17322. std::atomic_uint count{0};
  17323. std::unique_ptr<TaskQueue> task_queue{
  17324. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17325. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17326. if (task_queue->enqueue(
  17327. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17328. queued_count++;
  17329. }
  17330. }
  17331. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17332. task_queue->shutdown();
  17333. #else
  17334. EXPECT_NO_THROW(task_queue->shutdown());
  17335. #endif
  17336. EXPECT_EQ(queued_count, count.load());
  17337. EXPECT_TRUE(queued_count <= number_of_tasks);
  17338. EXPECT_TRUE(queued_count >= qlimit);
  17339. }
  17340. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17341. // Use a short idle timeout so a dynamic thread spawns, times out and
  17342. // exits during the test, and the pool keeps working afterwards.
  17343. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17344. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17345. /*idle_timeout_sec=*/1}};
  17346. std::atomic_uint count{0};
  17347. std::condition_variable cv;
  17348. std::mutex mtx;
  17349. bool release = false;
  17350. // Block the base thread so the second task spawns a dynamic thread.
  17351. EXPECT_TRUE(task_queue->enqueue([&] {
  17352. std::unique_lock<std::mutex> lock(mtx);
  17353. while (!release) {
  17354. cv.wait(lock);
  17355. }
  17356. count++;
  17357. }));
  17358. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17359. // Let the dynamic thread finish its task and exceed the idle timeout.
  17360. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17361. {
  17362. std::unique_lock<std::mutex> lock(mtx);
  17363. release = true;
  17364. }
  17365. cv.notify_all();
  17366. // The pool must still accept and run tasks after the dynamic thread exited.
  17367. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17368. task_queue->shutdown();
  17369. EXPECT_EQ(3u, count.load());
  17370. }
  17371. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17372. static constexpr size_t number_of_tasks{32};
  17373. std::unique_ptr<TaskQueue> task_queue{
  17374. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17375. // Let the base threads go idle so the burst below finds them waiting.
  17376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17377. std::mutex mtx;
  17378. std::condition_variable cv;
  17379. size_t running = 0;
  17380. bool release = false;
  17381. for (size_t i = 0; i < number_of_tasks; i++) {
  17382. EXPECT_TRUE(task_queue->enqueue([&] {
  17383. std::unique_lock<std::mutex> lock(mtx);
  17384. running++;
  17385. cv.notify_all();
  17386. cv.wait(lock, [&] { return release; });
  17387. }));
  17388. }
  17389. {
  17390. std::unique_lock<std::mutex> lock(mtx);
  17391. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17392. [&] { return running == number_of_tasks; }));
  17393. release = true;
  17394. }
  17395. cv.notify_all();
  17396. task_queue->shutdown();
  17397. }
  17398. TEST(TaskQueueTest, MaxQueuedRequests) {
  17399. static constexpr unsigned int qlimit{3};
  17400. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17401. std::condition_variable sem_cv;
  17402. std::mutex sem_mtx;
  17403. int credits = 0;
  17404. bool queued;
  17405. /* Fill up the queue with tasks that will block until we give them credits to
  17406. * complete. */
  17407. for (unsigned int n = 0; n <= qlimit;) {
  17408. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17409. std::unique_lock<std::mutex> lock(sem_mtx);
  17410. while (credits <= 0) {
  17411. sem_cv.wait(lock);
  17412. }
  17413. /* Consume the credit and signal the test code if they are all gone. */
  17414. if (--credits == 0) { sem_cv.notify_one(); }
  17415. });
  17416. if (n < qlimit) {
  17417. /* The first qlimit enqueues must succeed. */
  17418. EXPECT_TRUE(queued);
  17419. } else {
  17420. /* The last one will succeed only when the worker thread
  17421. * starts and dequeues the first blocking task. Although
  17422. * not necessary for the correctness of this test, we sleep for
  17423. * a short while to avoid busy waiting. */
  17424. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17425. }
  17426. if (queued) { n++; }
  17427. }
  17428. /* Further enqueues must fail since the queue is full. */
  17429. for (auto i = 0; i < 4; i++) {
  17430. queued = task_queue->enqueue([] {});
  17431. EXPECT_FALSE(queued);
  17432. }
  17433. /* Give the credits to allow the previous tasks to complete. */
  17434. {
  17435. std::unique_lock<std::mutex> lock(sem_mtx);
  17436. credits += qlimit + 1;
  17437. }
  17438. sem_cv.notify_all();
  17439. /* Wait for all the credits to be consumed. */
  17440. {
  17441. std::unique_lock<std::mutex> lock(sem_mtx);
  17442. while (credits > 0) {
  17443. sem_cv.wait(lock);
  17444. }
  17445. }
  17446. /* Check that we are able again to enqueue at least qlimit tasks. */
  17447. for (unsigned int i = 0; i < qlimit; i++) {
  17448. queued = task_queue->enqueue([] {});
  17449. EXPECT_TRUE(queued);
  17450. }
  17451. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17452. task_queue->shutdown();
  17453. #else
  17454. EXPECT_NO_THROW(task_queue->shutdown());
  17455. #endif
  17456. }
  17457. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17458. Server svr;
  17459. std::string method;
  17460. std::string body;
  17461. auto has_content_length = false;
  17462. auto has_transfer_encoding = false;
  17463. std::atomic<int> bad_requests{0};
  17464. // Leftover body bytes get parsed as a malformed request and answered with
  17465. // 400
  17466. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17467. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17468. });
  17469. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17470. res.set_redirect("/down", StatusCode::SeeOther_303);
  17471. });
  17472. svr.Get("/down", [&](const Request &req, Response &res) {
  17473. method = req.method;
  17474. body = req.body;
  17475. has_content_length = req.has_header("Content-Length");
  17476. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17477. res.set_content("ok", "text/plain");
  17478. });
  17479. auto port = svr.bind_to_any_port(HOST);
  17480. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17481. auto se = detail::scope_exit([&] {
  17482. svr.stop();
  17483. thread.join();
  17484. ASSERT_FALSE(svr.is_running());
  17485. });
  17486. svr.wait_until_ready();
  17487. const std::string payload = "SECRET-BODY";
  17488. auto check = [&](Client &cli, const Result &res) {
  17489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17490. EXPECT_EQ(StatusCode::OK_200, res->status);
  17491. EXPECT_EQ("ok", res->body);
  17492. EXPECT_EQ("GET", method);
  17493. EXPECT_TRUE(body.empty());
  17494. EXPECT_FALSE(has_content_length);
  17495. EXPECT_FALSE(has_transfer_encoding);
  17496. // Nothing of the original body may be left on the connection
  17497. auto res2 = cli.Get("/down");
  17498. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17499. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17500. EXPECT_EQ("ok", res2->body);
  17501. EXPECT_EQ(0, bad_requests);
  17502. };
  17503. // With content length
  17504. {
  17505. Client cli(HOST, port);
  17506. cli.set_keep_alive(true);
  17507. cli.set_follow_location(true);
  17508. auto res = cli.Post(
  17509. "/up", payload.size(),
  17510. [&](size_t offset, size_t length, DataSink &sink) {
  17511. return sink.write(payload.data() + offset, length);
  17512. },
  17513. "text/plain");
  17514. check(cli, res);
  17515. }
  17516. // Without content length (chunked)
  17517. {
  17518. Client cli(HOST, port);
  17519. cli.set_keep_alive(true);
  17520. cli.set_follow_location(true);
  17521. auto res = cli.Post(
  17522. "/up",
  17523. [&](size_t /*offset*/, DataSink &sink) {
  17524. sink.write(payload.data(), payload.size());
  17525. sink.done();
  17526. return true;
  17527. },
  17528. "text/plain");
  17529. check(cli, res);
  17530. }
  17531. }
  17532. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17533. Server svr;
  17534. std::string target;
  17535. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17536. // Echo the still-encoded name back in the Location
  17537. const std::string prefix = "/start/";
  17538. res.status = StatusCode::Found_302;
  17539. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17540. });
  17541. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17542. target = req.target;
  17543. res.set_content("ok", "text/plain");
  17544. });
  17545. auto port = svr.bind_to_any_port(HOST);
  17546. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17547. auto se = detail::scope_exit([&] {
  17548. svr.stop();
  17549. thread.join();
  17550. ASSERT_FALSE(svr.is_running());
  17551. });
  17552. svr.wait_until_ready();
  17553. // Decoding the Location path would turn the first four into a path
  17554. // separator, a query delimiter, a fragment delimiter and a different
  17555. // percent-encoded octet. The rest must keep reaching the server as they are.
  17556. const std::vector<std::string> names = {
  17557. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17558. };
  17559. for (auto path_encode : {true, false}) {
  17560. Client cli(HOST, port);
  17561. cli.set_follow_location(true);
  17562. cli.set_path_encode(path_encode);
  17563. for (const auto &name : names) {
  17564. target.clear();
  17565. auto res = cli.Get("/start/" + name);
  17566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17567. EXPECT_EQ(StatusCode::OK_200, res->status);
  17568. EXPECT_EQ("/dest/" + name, target);
  17569. }
  17570. }
  17571. }
  17572. TEST(RedirectTest, NotModifiedIsReturned) {
  17573. Server svr;
  17574. svr.Get("/cached", [](const Request &, Response &res) {
  17575. res.status = StatusCode::NotModified_304;
  17576. });
  17577. auto port = svr.bind_to_any_port(HOST);
  17578. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17579. auto se = detail::scope_exit([&] {
  17580. svr.stop();
  17581. thread.join();
  17582. ASSERT_FALSE(svr.is_running());
  17583. });
  17584. svr.wait_until_ready();
  17585. Client cli(HOST, port);
  17586. cli.set_follow_location(true);
  17587. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17589. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17590. }
  17591. TEST(RedirectTest, NoLocationIsReturned) {
  17592. Server svr;
  17593. svr.Get("/no-location", [](const Request &, Response &res) {
  17594. res.status = StatusCode::Found_302;
  17595. res.set_content("no location", "text/plain");
  17596. });
  17597. auto port = svr.bind_to_any_port(HOST);
  17598. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17599. auto se = detail::scope_exit([&] {
  17600. svr.stop();
  17601. thread.join();
  17602. ASSERT_FALSE(svr.is_running());
  17603. });
  17604. svr.wait_until_ready();
  17605. Client cli(HOST, port);
  17606. cli.set_follow_location(true);
  17607. auto res = cli.Get("/no-location");
  17608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17609. EXPECT_EQ(StatusCode::Found_302, res->status);
  17610. EXPECT_EQ("no location", res->body);
  17611. // The callbacks see the body of the response that is returned
  17612. auto handler_called = false;
  17613. auto progress_called = false;
  17614. std::string body;
  17615. auto res2 = cli.Get(
  17616. "/no-location",
  17617. [&](const Response &) {
  17618. handler_called = true;
  17619. return true;
  17620. },
  17621. [&](const char *data, size_t data_length) {
  17622. body.append(data, data_length);
  17623. return true;
  17624. },
  17625. [&](size_t, size_t) {
  17626. progress_called = true;
  17627. return true;
  17628. });
  17629. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17630. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17631. EXPECT_TRUE(handler_called);
  17632. EXPECT_TRUE(progress_called);
  17633. EXPECT_EQ("no location", body);
  17634. }
  17635. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17636. Server svr;
  17637. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17638. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17639. });
  17640. svr.Get("/hello", [](const Request &req, Response &res) {
  17641. res.set_content(req.get_param_value("key"), "text/plain");
  17642. });
  17643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17644. auto se = detail::scope_exit([&] {
  17645. svr.stop();
  17646. thread.join();
  17647. ASSERT_FALSE(svr.is_running());
  17648. });
  17649. svr.wait_until_ready();
  17650. {
  17651. Client cli(HOST, PORT);
  17652. cli.set_follow_location(true);
  17653. auto res = cli.Get("/");
  17654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17655. EXPECT_EQ(StatusCode::OK_200, res->status);
  17656. EXPECT_EQ("val&key2=val2", res->body);
  17657. }
  17658. }
  17659. #endif
  17660. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17661. Server svr;
  17662. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17663. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17664. });
  17665. svr.Get("/hello", [](const Request &req, Response &res) {
  17666. res.set_content(req.get_param_value("key"), "text/plain");
  17667. });
  17668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17669. auto se = detail::scope_exit([&] {
  17670. svr.stop();
  17671. thread.join();
  17672. ASSERT_FALSE(svr.is_running());
  17673. });
  17674. svr.wait_until_ready();
  17675. {
  17676. Client cli(HOST, PORT);
  17677. cli.set_follow_location(true);
  17678. auto res = cli.Get("/");
  17679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17680. EXPECT_EQ(StatusCode::OK_200, res->status);
  17681. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17682. }
  17683. }
  17684. TEST(RedirectTest, RedirectWithPlusInPath) {
  17685. Server svr;
  17686. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17687. res.set_redirect("/a+b");
  17688. });
  17689. // Route pattern uses regex; escape + as \\+
  17690. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17691. res.set_content(req.path, "text/plain");
  17692. });
  17693. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17694. auto se = detail::scope_exit([&] {
  17695. svr.stop();
  17696. thread.join();
  17697. ASSERT_FALSE(svr.is_running());
  17698. });
  17699. svr.wait_until_ready();
  17700. {
  17701. Client cli(HOST, PORT);
  17702. cli.set_follow_location(true);
  17703. auto res = cli.Get("/");
  17704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17705. EXPECT_EQ(StatusCode::OK_200, res->status);
  17706. EXPECT_EQ("/a+b", res->body);
  17707. }
  17708. }
  17709. TEST(RedirectTest, ResolveRelativeLocation) {
  17710. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17711. const std::vector<std::pair<std::string, std::string>> cases = {
  17712. {"g", "/b/c/g"},
  17713. {"./g", "/b/c/g"},
  17714. {"g/", "/b/c/g/"},
  17715. {"?y", "/b/c/d;p?y"},
  17716. {"g?y", "/b/c/g?y"},
  17717. {"#s", "/b/c/d;p?q#s"},
  17718. {"g#s", "/b/c/g#s"},
  17719. {"g?y#s", "/b/c/g?y#s"},
  17720. {";x", "/b/c/;x"},
  17721. {"g;x", "/b/c/g;x"},
  17722. {".", "/b/c/"},
  17723. {"./", "/b/c/"},
  17724. {"..", "/b/"},
  17725. {"../", "/b/"},
  17726. {"../g", "/b/g"},
  17727. {"../..", "/"},
  17728. {"../../", "/"},
  17729. {"../../g", "/g"},
  17730. {"../../../g", "/g"},
  17731. {"g.", "/b/c/g."},
  17732. {".g", "/b/c/.g"},
  17733. {"g..", "/b/c/g.."},
  17734. {"..g", "/b/c/..g"},
  17735. {"./../g", "/b/g"},
  17736. {"./g/.", "/b/c/g/"},
  17737. {"g/./h", "/b/c/g/h"},
  17738. {"g/../h", "/b/c/h"},
  17739. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17740. {"g;x=1/../y", "/b/c/y"},
  17741. {"g?y/./x", "/b/c/g?y/./x"},
  17742. {"g#s/../x", "/b/c/g#s/../x"},
  17743. // Not relative-path references, so left for parse_url.
  17744. {"/g", "/g"},
  17745. {"//g", "//g"},
  17746. {"http://g/x", "http://g/x"},
  17747. {"g:h", "g:h"},
  17748. };
  17749. for (const auto &c : cases) {
  17750. EXPECT_EQ(c.second,
  17751. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17752. << c.first;
  17753. }
  17754. // A result starting with "//" is still a path, not a network-path reference
  17755. EXPECT_EQ("/.//g",
  17756. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  17757. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  17758. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  17759. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  17760. }
  17761. TEST(RedirectTest, RemoveDotSegments) {
  17762. // RFC 3986 section 5.2.4
  17763. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17764. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17765. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17766. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17767. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17768. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17769. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17770. }
  17771. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17772. Server svr;
  17773. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17774. res.set_redirect("/dir/../target?x=1");
  17775. });
  17776. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17777. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17778. "/dir/./../target");
  17779. });
  17780. svr.Get("/target", [](const Request &req, Response &res) {
  17781. res.set_content(req.path, "text/plain");
  17782. });
  17783. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17784. auto se = detail::scope_exit([&] {
  17785. svr.stop();
  17786. th.join();
  17787. ASSERT_FALSE(svr.is_running());
  17788. });
  17789. svr.wait_until_ready();
  17790. Client cli("localhost", PORT);
  17791. cli.set_follow_location(true);
  17792. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17793. auto res = cli.Get(path);
  17794. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17795. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17796. EXPECT_EQ("/target", res->body) << path;
  17797. }
  17798. }
  17799. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17800. Server svr;
  17801. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17802. res.set_redirect(req.get_param_value("to"));
  17803. });
  17804. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17805. res.set_content(req.target, "text/plain");
  17806. });
  17807. svr.Get("/other", [](const Request &req, Response &res) {
  17808. res.set_content(req.target, "text/plain");
  17809. });
  17810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17811. auto se = detail::scope_exit([&] {
  17812. svr.stop();
  17813. thread.join();
  17814. ASSERT_FALSE(svr.is_running());
  17815. });
  17816. svr.wait_until_ready();
  17817. const std::vector<std::pair<std::string, std::string>> cases = {
  17818. {"next", "/dir/next"},
  17819. {"./next?x=1", "/dir/next?x=1"},
  17820. {"../other", "/other"},
  17821. };
  17822. for (const auto &c : cases) {
  17823. Client cli(HOST, PORT);
  17824. cli.set_follow_location(true);
  17825. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17826. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17827. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17828. EXPECT_EQ(c.second, res->body) << c.first;
  17829. }
  17830. }
  17831. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  17832. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  17833. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  17834. Server other;
  17835. std::atomic<int> other_hits{0};
  17836. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  17837. other_hits++;
  17838. res.set_content("other", "text/plain");
  17839. });
  17840. auto other_port = other.bind_to_any_port("127.0.0.1");
  17841. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  17842. Server svr;
  17843. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17844. res.set_redirect(req.get_param_value("to"));
  17845. });
  17846. svr.Get(".*", [](const Request &req, Response &res) {
  17847. res.set_content(req.path, "text/plain");
  17848. });
  17849. auto port = svr.bind_to_any_port(HOST);
  17850. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17851. auto se = detail::scope_exit([&] {
  17852. svr.stop();
  17853. thread.join();
  17854. other.stop();
  17855. other_thread.join();
  17856. ASSERT_FALSE(svr.is_running());
  17857. ASSERT_FALSE(other.is_running());
  17858. });
  17859. svr.wait_until_ready();
  17860. other.wait_until_ready();
  17861. auto authority = "127.0.0.1:" + std::to_string(other_port);
  17862. for (const auto &to :
  17863. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  17864. Client cli(HOST, port);
  17865. cli.set_follow_location(true);
  17866. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  17867. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  17868. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  17869. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  17870. }
  17871. EXPECT_EQ(0, other_hits.load());
  17872. }
  17873. #ifdef CPPHTTPLIB_SSL_ENABLED
  17874. TEST(RedirectTest, Issue2185_Online) {
  17875. SSLClient client("github.com");
  17876. client.set_follow_location(true);
  17877. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17878. "Coollab-Windows.zip");
  17879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17880. EXPECT_EQ(StatusCode::OK_200, res->status);
  17881. EXPECT_EQ(9920427U, res->body.size());
  17882. }
  17883. #endif
  17884. TEST(VulnerabilityTest, CRLFInjection) {
  17885. Server svr;
  17886. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17887. res.set_content("Hello 1", "text/plain");
  17888. });
  17889. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17890. res.set_content("Hello 2", "text/plain");
  17891. });
  17892. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17893. res.set_content("Hello 3", "text/plain");
  17894. });
  17895. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17896. res.set_content("Hello 4", "text/plain");
  17897. });
  17898. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17899. for (const auto &x : req.headers) {
  17900. auto key = x.first;
  17901. EXPECT_STRNE("evil", key.c_str());
  17902. }
  17903. });
  17904. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17905. auto se = detail::scope_exit([&] {
  17906. svr.stop();
  17907. thread.join();
  17908. ASSERT_FALSE(svr.is_running());
  17909. });
  17910. svr.wait_until_ready();
  17911. {
  17912. Client cli(HOST, PORT);
  17913. cli.Post("/test1", "A=B",
  17914. "application/x-www-form-urlencoded\r\nevil: hello1");
  17915. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17916. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17917. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17918. }
  17919. }
  17920. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17921. auto server_thread = std::thread([] {
  17922. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17923. default_socket_options(srv);
  17924. sockaddr_in addr{};
  17925. addr.sin_family = AF_INET;
  17926. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17927. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17928. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17929. ::listen(srv, 1);
  17930. sockaddr_in cli_addr{};
  17931. socklen_t cli_len = sizeof(cli_addr);
  17932. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17933. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17934. std::string buf_all;
  17935. char buf[2048];
  17936. ssize_t n;
  17937. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17938. buf_all.append(buf, static_cast<size_t>(n));
  17939. size_t pos;
  17940. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17941. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17942. auto e = request_block.find("\r\n");
  17943. if (e != std::string::npos) {
  17944. auto request_line = request_block.substr(0, e);
  17945. std::string msg =
  17946. "CRLF injection detected in request line: '" + request_line + "'";
  17947. EXPECT_FALSE(true) << msg;
  17948. }
  17949. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17950. ::send(cli,
  17951. #ifdef _WIN32
  17952. static_cast<const char *>(resp.c_str()),
  17953. static_cast<int>(resp.size()),
  17954. #else
  17955. resp.c_str(), resp.size(),
  17956. #endif
  17957. 0);
  17958. buf_all.erase(0, pos + 4);
  17959. }
  17960. }
  17961. detail::close_socket(cli);
  17962. detail::close_socket(srv);
  17963. });
  17964. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17965. auto cli = Client("127.0.0.1", PORT + 1);
  17966. auto headers = Headers{
  17967. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17968. {"Connection", "keep-alive"}};
  17969. auto res = cli.Get("/hi", headers);
  17970. EXPECT_FALSE(res);
  17971. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17972. server_thread.join();
  17973. }
  17974. // A request rejected before any byte reaches the socket must fail right away
  17975. // instead of waiting for a response the server will never send.
  17976. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17977. // The kernel completes the TCP handshake from the listen backlog, so the
  17978. // client connects, but nothing ever reads, responds or closes.
  17979. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17980. default_socket_options(srv);
  17981. sockaddr_in addr{};
  17982. addr.sin_family = AF_INET;
  17983. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17984. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17985. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17986. ASSERT_EQ(0, ::listen(srv, 8));
  17987. auto cli = Client("127.0.0.1", PORT + 1);
  17988. cli.set_read_timeout(10, 0);
  17989. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17990. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17991. std::chrono::steady_clock::now() - start)
  17992. .count();
  17993. };
  17994. {
  17995. Request req;
  17996. req.method = "GE T";
  17997. req.path = "/";
  17998. auto start = std::chrono::steady_clock::now();
  17999. auto res = cli.send(req);
  18000. EXPECT_FALSE(res);
  18001. EXPECT_EQ(Error::Write, res.error());
  18002. EXPECT_LT(elapsed_ms(start), 1000);
  18003. }
  18004. {
  18005. auto start = std::chrono::steady_clock::now();
  18006. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18007. EXPECT_FALSE(res);
  18008. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18009. EXPECT_LT(elapsed_ms(start), 1000);
  18010. }
  18011. EXPECT_FALSE(cli.is_socket_open());
  18012. detail::close_socket(srv);
  18013. }
  18014. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18015. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18016. default_socket_options(srv);
  18017. sockaddr_in addr{};
  18018. addr.sin_family = AF_INET;
  18019. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18020. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18021. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18022. ASSERT_EQ(0, ::listen(srv, 1));
  18023. std::string received;
  18024. auto server_thread = std::thread([&] {
  18025. auto sock = ::accept(srv, nullptr, nullptr);
  18026. if (sock == INVALID_SOCKET) { return; }
  18027. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18028. char buf[2048];
  18029. ssize_t n;
  18030. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18031. received.append(buf, static_cast<size_t>(n));
  18032. }
  18033. detail::close_socket(sock);
  18034. });
  18035. {
  18036. auto cli = Client("127.0.0.1", PORT + 1);
  18037. // "Z" sorts after the default headers, so writing straight to the socket
  18038. // would have sent the request line and those headers before the rejection.
  18039. auto handle =
  18040. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18041. EXPECT_FALSE(handle.is_valid());
  18042. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18043. }
  18044. server_thread.join();
  18045. detail::close_socket(srv);
  18046. EXPECT_TRUE(received.empty()) << received;
  18047. }
  18048. TEST(PathParamsTest, StaticMatch) {
  18049. const auto pattern = "/users/all";
  18050. detail::PathParamsMatcher matcher(pattern);
  18051. Request request;
  18052. request.path = "/users/all";
  18053. ASSERT_TRUE(matcher.match(request));
  18054. std::unordered_map<std::string, std::string> expected_params = {};
  18055. EXPECT_EQ(request.path_params, expected_params);
  18056. }
  18057. TEST(PathParamsTest, StaticMismatch) {
  18058. const auto pattern = "/users/all";
  18059. detail::PathParamsMatcher matcher(pattern);
  18060. Request request;
  18061. request.path = "/users/1";
  18062. ASSERT_FALSE(matcher.match(request));
  18063. }
  18064. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18065. const auto pattern = "/users/:id/subscriptions";
  18066. detail::PathParamsMatcher matcher(pattern);
  18067. Request request;
  18068. request.path = "/users/42/subscriptions";
  18069. ASSERT_TRUE(matcher.match(request));
  18070. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18071. EXPECT_EQ(request.path_params, expected_params);
  18072. }
  18073. TEST(PathParamsTest, SingleParamInTheEnd) {
  18074. const auto pattern = "/users/:id";
  18075. detail::PathParamsMatcher matcher(pattern);
  18076. Request request;
  18077. request.path = "/users/24";
  18078. ASSERT_TRUE(matcher.match(request));
  18079. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18080. EXPECT_EQ(request.path_params, expected_params);
  18081. }
  18082. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18083. const auto pattern = "/users/:id/";
  18084. detail::PathParamsMatcher matcher(pattern);
  18085. Request request;
  18086. request.path = "/users/42/";
  18087. ASSERT_TRUE(matcher.match(request));
  18088. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18089. EXPECT_EQ(request.path_params, expected_params);
  18090. }
  18091. TEST(PathParamsTest, EmptyParam) {
  18092. const auto pattern = "/users/:id/";
  18093. detail::PathParamsMatcher matcher(pattern);
  18094. Request request;
  18095. request.path = "/users//";
  18096. ASSERT_TRUE(matcher.match(request));
  18097. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18098. EXPECT_EQ(request.path_params, expected_params);
  18099. }
  18100. TEST(PathParamsTest, FragmentMismatch) {
  18101. const auto pattern = "/users/:id/";
  18102. detail::PathParamsMatcher matcher(pattern);
  18103. Request request;
  18104. request.path = "/admins/24/";
  18105. ASSERT_FALSE(matcher.match(request));
  18106. }
  18107. TEST(PathParamsTest, ExtraFragments) {
  18108. const auto pattern = "/users/:id";
  18109. detail::PathParamsMatcher matcher(pattern);
  18110. Request request;
  18111. request.path = "/users/42/subscriptions";
  18112. ASSERT_FALSE(matcher.match(request));
  18113. }
  18114. TEST(PathParamsTest, MissingTrailingParam) {
  18115. const auto pattern = "/users/:id";
  18116. detail::PathParamsMatcher matcher(pattern);
  18117. Request request;
  18118. request.path = "/users";
  18119. ASSERT_FALSE(matcher.match(request));
  18120. }
  18121. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18122. const auto pattern = "/users/:id/subscriptions";
  18123. detail::PathParamsMatcher matcher(pattern);
  18124. Request request;
  18125. request.path = "/users/subscriptions";
  18126. ASSERT_FALSE(matcher.match(request));
  18127. }
  18128. TEST(PathParamsTest, MultipleParams) {
  18129. const auto pattern = "/users/:userid/subscriptions/:subid";
  18130. detail::PathParamsMatcher matcher(pattern);
  18131. Request request;
  18132. request.path = "/users/42/subscriptions/2";
  18133. ASSERT_TRUE(matcher.match(request));
  18134. std::unordered_map<std::string, std::string> expected_params = {
  18135. {"userid", "42"}, {"subid", "2"}};
  18136. EXPECT_EQ(request.path_params, expected_params);
  18137. }
  18138. TEST(PathParamsTest, SequenceOfParams) {
  18139. const auto pattern = "/values/:x/:y/:z";
  18140. detail::PathParamsMatcher matcher(pattern);
  18141. Request request;
  18142. request.path = "/values/1/2/3";
  18143. ASSERT_TRUE(matcher.match(request));
  18144. std::unordered_map<std::string, std::string> expected_params = {
  18145. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18146. EXPECT_EQ(request.path_params, expected_params);
  18147. }
  18148. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18149. const auto pattern = "/prefix:suffix";
  18150. detail::PathParamsMatcher matcher(pattern);
  18151. Request request;
  18152. request.path = "/prefix:suffix";
  18153. ASSERT_TRUE(matcher.match(request));
  18154. const std::unordered_map<std::string, std::string> expected_params = {};
  18155. EXPECT_EQ(request.path_params, expected_params);
  18156. }
  18157. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18158. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18159. // calling thread's stack on a long enough path for a quantified pattern;
  18160. // RegexMatcher must refuse to run regex matching on paths beyond
  18161. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18162. detail::RegexMatcher matcher("/files/(.*)");
  18163. Request within_limit;
  18164. within_limit.path = "/files/" + std::string(10, 'A');
  18165. EXPECT_TRUE(matcher.match(within_limit));
  18166. Request over_limit;
  18167. over_limit.path =
  18168. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18169. EXPECT_FALSE(matcher.match(over_limit));
  18170. }
  18171. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18172. Server svr;
  18173. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18174. res.set_content("ok", "text/plain");
  18175. });
  18176. auto port = svr.bind_to_any_port(HOST);
  18177. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18178. auto se = detail::scope_exit([&] {
  18179. svr.stop();
  18180. thread.join();
  18181. ASSERT_FALSE(svr.is_running());
  18182. });
  18183. svr.wait_until_ready();
  18184. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18185. // request URI limit; this used to be able to crash the process.
  18186. std::string path =
  18187. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18188. std::string req = "GET " + path +
  18189. " HTTP/1.1\r\n"
  18190. "Host: " +
  18191. std::string(HOST) + ":" + std::to_string(port) +
  18192. "\r\n"
  18193. "Connection: close\r\n"
  18194. "\r\n";
  18195. std::string response;
  18196. ASSERT_TRUE(send_request(5, req, &response, port));
  18197. EXPECT_NE(std::string::npos, response.find("404"));
  18198. }
  18199. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18200. Server svr;
  18201. auto handler = [](const Request & /*req*/, Response &res) {
  18202. res.set_content("hit", "text/plain");
  18203. };
  18204. // No regex metacharacter, so this one is compared literally
  18205. svr.Get("/literal/route", handler);
  18206. // '.' is a regex metacharacter, so this one must keep regex semantics
  18207. svr.Get("/a.c", handler);
  18208. auto port = svr.bind_to_any_port(HOST);
  18209. std::thread t([&]() { svr.listen_after_bind(); });
  18210. auto se = detail::scope_exit([&] {
  18211. svr.stop();
  18212. t.join();
  18213. ASSERT_FALSE(svr.is_running());
  18214. });
  18215. svr.wait_until_ready();
  18216. Client cli(HOST, port);
  18217. struct {
  18218. const char *path;
  18219. int status;
  18220. } cases[] = {
  18221. {"/literal/route", StatusCode::OK_200},
  18222. {"/literal/routes", StatusCode::NotFound_404},
  18223. {"/literal/rout", StatusCode::NotFound_404},
  18224. {"/abc", StatusCode::OK_200},
  18225. {"/a.c", StatusCode::OK_200},
  18226. };
  18227. for (const auto &x : cases) {
  18228. auto res = cli.Get(x.path);
  18229. ASSERT_TRUE(res) << x.path;
  18230. EXPECT_EQ(x.status, res->status) << x.path;
  18231. }
  18232. }
  18233. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18234. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18235. // from exhausting the stack, so it must only constrain routes that actually
  18236. // run a regular expression. A literal route is matched by comparison and
  18237. // stays usable at any length.
  18238. Server svr;
  18239. const std::string pattern =
  18240. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18241. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18242. res.set_content("hit", "text/plain");
  18243. });
  18244. auto port = svr.bind_to_any_port(HOST);
  18245. std::thread t([&]() { svr.listen_after_bind(); });
  18246. auto se = detail::scope_exit([&] {
  18247. svr.stop();
  18248. t.join();
  18249. ASSERT_FALSE(svr.is_running());
  18250. });
  18251. svr.wait_until_ready();
  18252. Client cli(HOST, port);
  18253. auto res = cli.Get(pattern);
  18254. ASSERT_TRUE(res);
  18255. EXPECT_EQ(StatusCode::OK_200, res->status);
  18256. }
  18257. TEST(ParseUrlTest, VariousPatterns) {
  18258. {
  18259. detail::UrlComponents uc;
  18260. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18261. EXPECT_EQ("http", uc.scheme);
  18262. EXPECT_EQ("example.com", uc.host);
  18263. EXPECT_EQ("8080", uc.port);
  18264. EXPECT_EQ("/path", uc.path);
  18265. EXPECT_EQ("?q=1", uc.query);
  18266. }
  18267. {
  18268. detail::UrlComponents uc;
  18269. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18270. EXPECT_EQ("https", uc.scheme);
  18271. EXPECT_EQ("example.com", uc.host);
  18272. EXPECT_TRUE(uc.port.empty());
  18273. EXPECT_EQ("/path", uc.path);
  18274. }
  18275. {
  18276. detail::UrlComponents uc;
  18277. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18278. EXPECT_EQ("::1", uc.host);
  18279. EXPECT_EQ("8080", uc.port);
  18280. EXPECT_EQ("/path", uc.path);
  18281. }
  18282. {
  18283. detail::UrlComponents uc;
  18284. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18285. }
  18286. {
  18287. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18288. // the path while the connection still targets the bracketed host.
  18289. detail::UrlComponents uc;
  18290. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18291. }
  18292. {
  18293. detail::UrlComponents uc;
  18294. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18295. }
  18296. {
  18297. detail::UrlComponents uc;
  18298. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18299. EXPECT_EQ("::1", uc.host);
  18300. EXPECT_TRUE(uc.port.empty());
  18301. EXPECT_EQ("/path", uc.path);
  18302. }
  18303. {
  18304. detail::UrlComponents uc;
  18305. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18306. EXPECT_TRUE(uc.scheme.empty());
  18307. EXPECT_EQ("example.com", uc.host);
  18308. EXPECT_EQ("/path", uc.path);
  18309. EXPECT_EQ("?q=1", uc.query);
  18310. }
  18311. {
  18312. detail::UrlComponents uc;
  18313. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18314. EXPECT_TRUE(uc.host.empty());
  18315. EXPECT_EQ("/path", uc.path);
  18316. EXPECT_EQ("?q=1", uc.query);
  18317. }
  18318. {
  18319. detail::UrlComponents uc;
  18320. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18321. EXPECT_EQ("example.com", uc.host);
  18322. EXPECT_EQ("8080", uc.port);
  18323. }
  18324. {
  18325. // Unix socket path — must not be parsed as host
  18326. detail::UrlComponents uc;
  18327. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18328. EXPECT_TRUE(uc.host.empty());
  18329. }
  18330. {
  18331. detail::UrlComponents uc;
  18332. ASSERT_TRUE(detail::parse_url("", uc));
  18333. EXPECT_TRUE(uc.host.empty());
  18334. EXPECT_TRUE(uc.path.empty());
  18335. }
  18336. {
  18337. detail::UrlComponents uc;
  18338. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18339. }
  18340. {
  18341. detail::UrlComponents uc;
  18342. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18343. }
  18344. {
  18345. // Accepted by parse_url; callers restrict to http/https
  18346. detail::UrlComponents uc;
  18347. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18348. EXPECT_EQ("ftp", uc.scheme);
  18349. }
  18350. {
  18351. detail::UrlComponents uc;
  18352. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18353. }
  18354. {
  18355. detail::UrlComponents uc;
  18356. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18357. }
  18358. }
  18359. TEST(ParseUrlTest, FragmentHandling) {
  18360. {
  18361. detail::UrlComponents uc;
  18362. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18363. EXPECT_EQ("/path", uc.path);
  18364. EXPECT_TRUE(uc.query.empty());
  18365. }
  18366. {
  18367. detail::UrlComponents uc;
  18368. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18369. EXPECT_TRUE(uc.path.empty());
  18370. EXPECT_TRUE(uc.query.empty());
  18371. }
  18372. }
  18373. TEST(ParseUrlTest, UserinfoHandling) {
  18374. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18375. // parsers would see evil.com as the host.
  18376. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18377. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18378. for (auto url : urls) {
  18379. detail::UrlComponents uc;
  18380. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18381. }
  18382. }
  18383. TEST(ParseUrlTest, IPv6EdgeCases) {
  18384. {
  18385. detail::UrlComponents uc;
  18386. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18387. EXPECT_TRUE(uc.scheme.empty());
  18388. EXPECT_EQ("::1", uc.host);
  18389. EXPECT_EQ("8080", uc.port);
  18390. }
  18391. {
  18392. // Zone ID '%25' is not in [a-fA-F0-9:]
  18393. detail::UrlComponents uc;
  18394. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18395. }
  18396. }
  18397. TEST(ParseUrlTest, SchemeEdgeCases) {
  18398. {
  18399. detail::UrlComponents uc;
  18400. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18401. }
  18402. {
  18403. detail::UrlComponents uc;
  18404. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18405. }
  18406. {
  18407. detail::UrlComponents uc;
  18408. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18409. }
  18410. }
  18411. TEST(ParseUrlTest, PortEdgeCases) {
  18412. {
  18413. detail::UrlComponents uc;
  18414. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18415. EXPECT_TRUE(uc.port.empty());
  18416. EXPECT_EQ("/path", uc.path);
  18417. }
  18418. {
  18419. // parse_url accepts any port string; validation is done by parse_port
  18420. detail::UrlComponents uc;
  18421. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18422. EXPECT_EQ("abc", uc.port);
  18423. }
  18424. }
  18425. TEST(ParseUrlTest, WebSocketPatterns) {
  18426. {
  18427. detail::UrlComponents uc;
  18428. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18429. EXPECT_EQ("ws", uc.scheme);
  18430. EXPECT_EQ("echo.example.com", uc.host);
  18431. EXPECT_EQ("8080", uc.port);
  18432. EXPECT_EQ("/ws", uc.path);
  18433. }
  18434. {
  18435. detail::UrlComponents uc;
  18436. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18437. EXPECT_EQ("wss", uc.scheme);
  18438. EXPECT_EQ("echo.example.com", uc.host);
  18439. EXPECT_TRUE(uc.port.empty());
  18440. EXPECT_EQ("/ws", uc.path);
  18441. }
  18442. }
  18443. TEST(ParseUrlTest, QueryOnly) {
  18444. detail::UrlComponents uc;
  18445. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18446. EXPECT_TRUE(uc.host.empty());
  18447. EXPECT_TRUE(uc.path.empty());
  18448. EXPECT_EQ("?q=1&r=2", uc.query);
  18449. }
  18450. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18451. detail::UrlComponents uc;
  18452. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18453. EXPECT_TRUE(uc.scheme.empty());
  18454. EXPECT_EQ("example.com", uc.host);
  18455. EXPECT_EQ("443", uc.port);
  18456. EXPECT_EQ("/path", uc.path);
  18457. }
  18458. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18459. // If ipv6 regex working, regex match codepath is taken.
  18460. // else port will default to 80 in Client impl
  18461. int clientImplMagicPort = 80;
  18462. int port = 4321;
  18463. // above ports must be different to avoid false negative
  18464. EXPECT_NE(clientImplMagicPort, port);
  18465. std::string ipV6TestURL = "http://[ff06::c3]";
  18466. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18467. CLIENT_PRIVATE_KEY_FILE);
  18468. EXPECT_EQ(cli.port(), port);
  18469. }
  18470. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18471. auto file_path = "./www/dir/index.html";
  18472. auto dir_path = "./www/dir";
  18473. detail::FileStat stat_file(file_path);
  18474. EXPECT_TRUE(stat_file.is_file());
  18475. EXPECT_FALSE(stat_file.is_dir());
  18476. detail::FileStat stat_dir(dir_path);
  18477. EXPECT_FALSE(stat_dir.is_file());
  18478. EXPECT_TRUE(stat_dir.is_dir());
  18479. }
  18480. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18481. // IPv4 with default HTTP port (80)
  18482. EXPECT_EQ("example.com",
  18483. detail::make_host_and_port_string("example.com", 80, false));
  18484. // IPv4 with default HTTPS port (443)
  18485. EXPECT_EQ("example.com",
  18486. detail::make_host_and_port_string("example.com", 443, true));
  18487. // IPv4 with non-default HTTP port
  18488. EXPECT_EQ("example.com:8080",
  18489. detail::make_host_and_port_string("example.com", 8080, false));
  18490. // IPv4 with non-default HTTPS port
  18491. EXPECT_EQ("example.com:8443",
  18492. detail::make_host_and_port_string("example.com", 8443, true));
  18493. // IPv6 with default HTTP port (80)
  18494. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18495. // IPv6 with default HTTPS port (443)
  18496. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18497. // IPv6 with non-default HTTP port
  18498. EXPECT_EQ("[::1]:8080",
  18499. detail::make_host_and_port_string("::1", 8080, false));
  18500. // IPv6 with non-default HTTPS port
  18501. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18502. // IPv6 full address with default port
  18503. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18504. detail::make_host_and_port_string(
  18505. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18506. // IPv6 full address with non-default port
  18507. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18508. detail::make_host_and_port_string(
  18509. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18510. // IPv6 localhost with non-default port
  18511. EXPECT_EQ("[::1]:3000",
  18512. detail::make_host_and_port_string("::1", 3000, false));
  18513. // IPv6 with zone ID (link-local address) with default port
  18514. EXPECT_EQ("[fe80::1%eth0]",
  18515. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18516. // IPv6 with zone ID (link-local address) with non-default port
  18517. EXPECT_EQ("[fe80::1%eth0]:8080",
  18518. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18519. // Edge case: Port 443 with is_ssl=false (should add port)
  18520. EXPECT_EQ("example.com:443",
  18521. detail::make_host_and_port_string("example.com", 443, false));
  18522. // Edge case: Port 80 with is_ssl=true (should add port)
  18523. EXPECT_EQ("example.com:80",
  18524. detail::make_host_and_port_string("example.com", 80, true));
  18525. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18526. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18527. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18528. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18529. // Security fix: Already bracketed IPv6 should not get double brackets
  18530. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18531. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18532. EXPECT_EQ("[::1]:8080",
  18533. detail::make_host_and_port_string("[::1]", 8080, false));
  18534. EXPECT_EQ("[2001:db8::1]:8080",
  18535. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18536. EXPECT_EQ("[fe80::1%eth0]",
  18537. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18538. EXPECT_EQ("[fe80::1%eth0]:8080",
  18539. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18540. // Edge case: Empty host (should return as-is)
  18541. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18542. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18543. // This is a known limitation but shouldn't crash
  18544. EXPECT_EQ("[host:name]",
  18545. detail::make_host_and_port_string("host:name", 80, false));
  18546. // Port number edge cases (no validation, but should not crash)
  18547. EXPECT_EQ("example.com:0",
  18548. detail::make_host_and_port_string("example.com", 0, false));
  18549. EXPECT_EQ("example.com:-1",
  18550. detail::make_host_and_port_string("example.com", -1, false));
  18551. EXPECT_EQ("example.com:65535",
  18552. detail::make_host_and_port_string("example.com", 65535, false));
  18553. EXPECT_EQ("example.com:65536",
  18554. detail::make_host_and_port_string("example.com", 65536, false));
  18555. }
  18556. namespace httplib {
  18557. namespace detail {
  18558. std::string
  18559. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18560. const std::string &host, int port);
  18561. } // namespace detail
  18562. } // namespace httplib
  18563. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18564. std::map<std::string, std::string> addr_map = {
  18565. {"ipv4.example", "192.0.2.10"},
  18566. {"ipv6.example", "2001:db8::1"},
  18567. {"name.example", "internal.example.lan"},
  18568. {"empty.example", ""}};
  18569. EXPECT_EQ("192.0.2.10:443",
  18570. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18571. EXPECT_EQ("[2001:db8::1]:443",
  18572. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18573. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18574. addr_map, "name.example", 8443));
  18575. // An empty or absent mapping keeps the hostname as the target
  18576. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18577. addr_map, "empty.example", 443));
  18578. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18579. addr_map, "other.example", 443));
  18580. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18581. }
  18582. #ifdef CPPHTTPLIB_SSL_ENABLED
  18583. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18584. httplib::SSLClient cli("roblox.com", 443);
  18585. cli.set_follow_location(true);
  18586. auto res = cli.Get("/");
  18587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18588. EXPECT_EQ(StatusCode::OK_200, res->status);
  18589. }
  18590. #endif
  18591. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18592. Server svr;
  18593. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18594. EXPECT_EQ(res.status, 400);
  18595. });
  18596. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18597. auto se = detail::scope_exit([&] {
  18598. svr.stop();
  18599. thread.join();
  18600. ASSERT_FALSE(svr.is_running());
  18601. });
  18602. svr.wait_until_ready();
  18603. Client cli(HOST, PORT);
  18604. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18605. }
  18606. TEST(InvalidHeaderCharsTest, is_field_name) {
  18607. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18608. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18609. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18610. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18611. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18612. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18613. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18614. EXPECT_FALSE(detail::fields::is_field_name(""));
  18615. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18616. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18617. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18618. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18619. }
  18620. TEST(InvalidHeaderCharsTest, is_field_value) {
  18621. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18622. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18623. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18624. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18625. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18626. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18627. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18628. EXPECT_TRUE(detail::fields::is_field_value(""));
  18629. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18630. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18631. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18632. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18633. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18634. }
  18635. TEST(InvalidHeaderCharsTest, OnServer) {
  18636. Server svr;
  18637. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18638. std::string header = "Not Set";
  18639. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18640. res.set_header(header, "value");
  18641. res.set_content("Page Content Page Content", "text/plain");
  18642. });
  18643. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18644. std::string header = "Not Set";
  18645. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18646. res.set_header("X-Test", header);
  18647. res.set_content("Page Content Page Content", "text/plain");
  18648. });
  18649. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18650. auto se = detail::scope_exit([&] {
  18651. svr.stop();
  18652. thread.join();
  18653. ASSERT_FALSE(svr.is_running());
  18654. });
  18655. svr.wait_until_ready();
  18656. Client cli(HOST, PORT);
  18657. {
  18658. auto res = cli.Get(
  18659. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18661. EXPECT_EQ("Page Content Page Content", res->body);
  18662. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18663. }
  18664. {
  18665. auto res = cli.Get(
  18666. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18668. EXPECT_EQ("Page Content Page Content", res->body);
  18669. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18670. }
  18671. }
  18672. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18673. auto handled = false;
  18674. Server svr;
  18675. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18676. thread t = thread([&] { svr.listen(HOST, PORT); });
  18677. auto se = detail::scope_exit([&] {
  18678. svr.stop();
  18679. t.join();
  18680. ASSERT_FALSE(svr.is_running());
  18681. ASSERT_FALSE(handled);
  18682. });
  18683. svr.wait_until_ready();
  18684. auto req = "POST /test HTTP/1.1\r\n"
  18685. "Content-Length: x\r\n"
  18686. "\r\n";
  18687. std::string response;
  18688. ASSERT_TRUE(send_request(1, req, &response));
  18689. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18690. response.substr(0, response.find("\r\n")));
  18691. }
  18692. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18693. // case-insensitive, and a server that receives a 100-continue expectation in
  18694. // an HTTP/1.0 request MUST ignore it.
  18695. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18696. std::string response;
  18697. ASSERT_TRUE(send_request(1, req, &response, port));
  18698. *got_100 = response.find("100 Continue") != std::string::npos;
  18699. }
  18700. class ExpectTokenTest : public ::testing::Test {
  18701. protected:
  18702. void SetUp() override {
  18703. svr_.Post("/p", [](const Request &, Response &res) {
  18704. res.set_content("ok", "text/plain");
  18705. });
  18706. port_ = svr_.bind_to_any_port(HOST);
  18707. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18708. svr_.wait_until_ready();
  18709. }
  18710. void TearDown() override {
  18711. svr_.stop();
  18712. if (thread_.joinable()) { thread_.join(); }
  18713. }
  18714. std::string request(const char *version, const char *expect_value) const {
  18715. return std::string("POST /p ") + version +
  18716. "\r\n"
  18717. "Host: localhost\r\n"
  18718. "Content-Length: 2\r\n"
  18719. "Connection: close\r\n"
  18720. "Expect: " +
  18721. expect_value +
  18722. "\r\n"
  18723. "\r\n"
  18724. "hi";
  18725. }
  18726. Server svr_;
  18727. int port_ = 0;
  18728. thread thread_;
  18729. };
  18730. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18731. bool got_100 = false;
  18732. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18733. EXPECT_TRUE(got_100);
  18734. }
  18735. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18736. bool got_100 = true;
  18737. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18738. EXPECT_FALSE(got_100);
  18739. }
  18740. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18741. bool got_100 = false;
  18742. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18743. EXPECT_TRUE(got_100);
  18744. }
  18745. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18746. bool got_100 = false;
  18747. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18748. EXPECT_TRUE(got_100);
  18749. }
  18750. // `100 Continue` is sent only when the server starts reading the body, so a
  18751. // request rejected before that never invites the client to send it. The
  18752. // requests below carry the expectation but withhold the body, as a client
  18753. // waiting for `100 Continue` would.
  18754. // A POST that expects `100 Continue` and withholds its two-byte body.
  18755. static std::string expect_headers_only(const std::string &path) {
  18756. return "POST " + path +
  18757. " HTTP/1.1\r\n"
  18758. "Host: localhost\r\n"
  18759. "Content-Length: 2\r\n"
  18760. "Expect: 100-continue\r\n"
  18761. "\r\n";
  18762. }
  18763. class ExpectLazyContinueTest : public ::testing::Test {
  18764. protected:
  18765. void SetUp() override {
  18766. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18767. if (req.path == "/pre-routing") {
  18768. res.status = StatusCode::Unauthorized_401;
  18769. return Server::HandlerResponse::Handled;
  18770. }
  18771. return Server::HandlerResponse::Unhandled;
  18772. });
  18773. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18774. if (req.matched_route == "/pre-request") {
  18775. res.status = StatusCode::Forbidden_403;
  18776. return Server::HandlerResponse::Handled;
  18777. }
  18778. return Server::HandlerResponse::Unhandled;
  18779. });
  18780. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18781. res.set_content("ok", "text/plain");
  18782. });
  18783. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18784. res.set_content("ok", "text/plain");
  18785. });
  18786. svr_.Post("/reader-used", [](const Request &, Response &res,
  18787. const ContentReader &content_reader) {
  18788. std::string body;
  18789. content_reader([&](const char *data, size_t len) {
  18790. body.append(data, len);
  18791. return true;
  18792. });
  18793. res.set_content(body, "text/plain");
  18794. });
  18795. svr_.Post("/reader-unused",
  18796. [](const Request &, Response &res, const ContentReader &) {
  18797. res.set_content("ignored", "text/plain");
  18798. });
  18799. port_ = svr_.bind_to_any_port(HOST);
  18800. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18801. svr_.wait_until_ready();
  18802. }
  18803. void TearDown() override {
  18804. svr_.stop();
  18805. if (thread_.joinable()) { thread_.join(); }
  18806. }
  18807. // Sends `req` and reads until the server closes the connection. Returns
  18808. // false if the read had to wait for the client-side timeout instead.
  18809. bool send_until_closed(const std::string &req, std::string *resp) const {
  18810. auto start = std::chrono::steady_clock::now();
  18811. if (!send_request(3, req, resp, port_)) { return false; }
  18812. auto elapsed = std::chrono::steady_clock::now() - start;
  18813. return elapsed < std::chrono::seconds(2);
  18814. }
  18815. // The final response comes without `100 Continue`, and the server closes
  18816. // the connection since the body may or may not follow.
  18817. void expect_final_without_interim(const std::string &path,
  18818. const char *status_line) const {
  18819. std::string resp;
  18820. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18821. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18822. EXPECT_EQ(0u, resp.find(status_line));
  18823. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18824. }
  18825. Server svr_;
  18826. int port_ = 0;
  18827. thread thread_;
  18828. };
  18829. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18830. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18831. }
  18832. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18833. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18834. }
  18835. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18836. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18837. }
  18838. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18839. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18840. }
  18841. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18842. // The body follows once `100 Continue` has had time to arrive.
  18843. auto req = expect_headers_only("/reader-used");
  18844. req.insert(req.size() - 2, "Connection: close\r\n");
  18845. std::string resp;
  18846. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18847. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18848. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18849. EXPECT_NE(std::string::npos, resp.find("hi"));
  18850. }
  18851. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18852. // Large enough for the client to add `Expect: 100-continue` itself.
  18853. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18854. std::atomic<bool> body_sent{false};
  18855. Client cli(HOST, port_);
  18856. auto res = cli.Post(
  18857. "/pre-request", length,
  18858. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18859. body_sent = true;
  18860. std::string chunk(len, 'x');
  18861. sink.write(chunk.data(), chunk.size());
  18862. return true;
  18863. },
  18864. "application/octet-stream");
  18865. ASSERT_TRUE(res);
  18866. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18867. EXPECT_FALSE(body_sent);
  18868. }
  18869. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18870. Server svr;
  18871. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18872. return StatusCode::ExpectationFailed_417;
  18873. });
  18874. svr.Post("/p", [](const Request &, Response &res) {
  18875. res.set_content("ok", "text/plain");
  18876. });
  18877. auto port = svr.bind_to_any_port(HOST);
  18878. thread t = thread([&] { svr.listen_after_bind(); });
  18879. auto se = detail::scope_exit([&] {
  18880. svr.stop();
  18881. t.join();
  18882. });
  18883. svr.wait_until_ready();
  18884. std::string resp;
  18885. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18886. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18887. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18888. // Exactly one response: the route handler must not run after the 417.
  18889. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18890. }
  18891. #ifndef _WIN32
  18892. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18893. static constexpr char reject[] = "Unauthorized";
  18894. static constexpr char accept[] = "Upload accepted";
  18895. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18896. Server svr;
  18897. svr.set_expect_100_continue_handler(
  18898. [](const Request & /*req*/, Response &res) {
  18899. res.status = StatusCode::Unauthorized_401;
  18900. res.set_content(reject, "text/plain");
  18901. return res.status;
  18902. });
  18903. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18904. res.set_content(accept, "text/plain");
  18905. });
  18906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18907. auto se = detail::scope_exit([&] {
  18908. svr.stop();
  18909. thread.join();
  18910. ASSERT_FALSE(svr.is_running());
  18911. });
  18912. svr.wait_until_ready();
  18913. {
  18914. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18915. curl_easy_init(), &curl_easy_cleanup};
  18916. ASSERT_NE(curl, nullptr);
  18917. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18918. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18919. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18920. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18921. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18922. &curl_slist_free_all};
  18923. ASSERT_NE(list, nullptr);
  18924. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18925. struct read_data {
  18926. uint64_t read_size;
  18927. uint64_t total_size;
  18928. } data = {0, total_size};
  18929. using read_callback_t =
  18930. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18931. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18932. void *userdata) -> size_t {
  18933. read_data *d = (read_data *)userdata;
  18934. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18935. std::fill_n(ptr, size * nmemb, 'A');
  18936. d->read_size += size * nmemb;
  18937. return size * nmemb;
  18938. };
  18939. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18940. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18941. std::vector<char> buffer;
  18942. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18943. using write_callback_t =
  18944. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18945. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18946. void *userdata) -> size_t {
  18947. std::vector<char> *buf = (std::vector<char> *)userdata;
  18948. buf->reserve(buf->size() + size * nmemb + 1);
  18949. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18950. return size * nmemb;
  18951. };
  18952. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18953. {
  18954. const auto res = curl_easy_perform(curl.get());
  18955. ASSERT_EQ(res, CURLE_OK);
  18956. }
  18957. {
  18958. auto response_code = long{};
  18959. const auto res =
  18960. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18961. ASSERT_EQ(res, CURLE_OK);
  18962. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18963. }
  18964. {
  18965. auto dl = curl_off_t{};
  18966. const auto res =
  18967. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18968. ASSERT_EQ(res, CURLE_OK);
  18969. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18970. }
  18971. {
  18972. buffer.push_back('\0');
  18973. ASSERT_STRCASEEQ(buffer.data(), reject);
  18974. }
  18975. }
  18976. }
  18977. #endif
  18978. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18979. // Regression test for #2458.
  18980. //
  18981. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18982. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18983. // ticket can make the client socket spuriously readable during the
  18984. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18985. // the client withholds the body and then blocks reading a response that never
  18986. // comes, failing with `Failed to read connection`.
  18987. //
  18988. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18989. // within the timeout. This raw OpenSSL server deliberately never sends
  18990. // `100 Continue`; the client must still deliver the body and receive 200.
  18991. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18992. signal(SIGPIPE, SIG_IGN);
  18993. const auto port = PORT + 4;
  18994. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18995. ASSERT_NE(srv, INVALID_SOCKET);
  18996. int opt = 1;
  18997. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18998. sockaddr_in addr{};
  18999. addr.sin_family = AF_INET;
  19000. addr.sin_port = htons(static_cast<uint16_t>(port));
  19001. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19002. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19003. ASSERT_EQ(0, ::listen(srv, 1));
  19004. std::atomic<size_t> server_body_bytes{0};
  19005. auto server_thread = std::thread([&] {
  19006. sockaddr_in cli_addr{};
  19007. socklen_t cli_len = sizeof(cli_addr);
  19008. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19009. if (cli == INVALID_SOCKET) { return; }
  19010. // Bound the lifetime of the server side so a buggy client (which never
  19011. // sends the body) cannot make this thread block forever on join.
  19012. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19013. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19014. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19015. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19016. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19017. SSL *ssl = SSL_new(ctx);
  19018. SSL_set_fd(ssl, static_cast<int>(cli));
  19019. if (SSL_accept(ssl) > 0) {
  19020. // Read the request headers. Reading here also flushes the TLS 1.3
  19021. // session tickets to the client. Deliberately do NOT send
  19022. // `100 Continue`.
  19023. std::string buf;
  19024. char tmp[1024];
  19025. while (buf.find("\r\n\r\n") == std::string::npos) {
  19026. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19027. if (n <= 0) { break; }
  19028. buf.append(tmp, static_cast<size_t>(n));
  19029. }
  19030. // A correct client sends the body now; count what arrives.
  19031. auto pos = buf.find("\r\n\r\n");
  19032. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19033. while (body < 4096) {
  19034. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19035. if (n <= 0) { break; }
  19036. body += static_cast<size_t>(n);
  19037. }
  19038. server_body_bytes = body;
  19039. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19040. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19041. SSL_shutdown(ssl);
  19042. }
  19043. SSL_free(ssl);
  19044. detail::close_socket(cli);
  19045. SSL_CTX_free(ctx);
  19046. });
  19047. auto se = detail::scope_exit([&] {
  19048. server_thread.join();
  19049. detail::close_socket(srv);
  19050. });
  19051. SSLClient cli("127.0.0.1", port);
  19052. cli.enable_server_certificate_verification(false);
  19053. cli.set_connection_timeout(5, 0);
  19054. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19055. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19056. std::string body(4096, 'A');
  19057. auto res = cli.Put("/api/test", body, "application/json");
  19058. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19059. EXPECT_EQ(StatusCode::OK_200, res->status);
  19060. EXPECT_EQ(body.size(), server_body_bytes.load());
  19061. }
  19062. #endif
  19063. template <typename S, typename C>
  19064. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19065. svr.Get("/stream", [&](const Request &, Response &res) {
  19066. auto data = new std::string("01234567890123456789");
  19067. res.set_content_provider(
  19068. data->size(), "text/plain",
  19069. [&, data](size_t offset, size_t length, DataSink &sink) {
  19070. const size_t DATA_CHUNK_SIZE = 4;
  19071. const auto &d = *data;
  19072. std::this_thread::sleep_for(std::chrono::seconds(1));
  19073. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19074. return true;
  19075. },
  19076. [data](bool success) {
  19077. EXPECT_FALSE(success);
  19078. delete data;
  19079. });
  19080. });
  19081. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19082. auto i = new size_t(0);
  19083. res.set_content_provider(
  19084. "text/plain",
  19085. [i](size_t, DataSink &sink) {
  19086. if (*i < 5) {
  19087. std::this_thread::sleep_for(std::chrono::seconds(1));
  19088. sink.write("abcd", 4);
  19089. (*i)++;
  19090. } else {
  19091. sink.done();
  19092. }
  19093. return true;
  19094. },
  19095. [i](bool success) {
  19096. EXPECT_FALSE(success);
  19097. delete i;
  19098. });
  19099. });
  19100. svr.Get("/chunked", [&](const Request &, Response &res) {
  19101. auto i = new size_t(0);
  19102. res.set_chunked_content_provider(
  19103. "text/plain",
  19104. [i](size_t, DataSink &sink) {
  19105. if (*i < 5) {
  19106. std::this_thread::sleep_for(std::chrono::seconds(1));
  19107. sink.os << "abcd";
  19108. (*i)++;
  19109. } else {
  19110. sink.done();
  19111. }
  19112. return true;
  19113. },
  19114. [i](bool success) {
  19115. EXPECT_FALSE(success);
  19116. delete i;
  19117. });
  19118. });
  19119. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19120. auto se = detail::scope_exit([&] {
  19121. svr.stop();
  19122. listen_thread.join();
  19123. ASSERT_FALSE(svr.is_running());
  19124. });
  19125. svr.wait_until_ready();
  19126. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19127. {
  19128. auto start = std::chrono::steady_clock::now();
  19129. auto res = cli.Get("/stream");
  19130. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19131. std::chrono::steady_clock::now() - start)
  19132. .count();
  19133. ASSERT_FALSE(res);
  19134. EXPECT_EQ(Error::Read, res.error());
  19135. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19136. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19137. }
  19138. {
  19139. auto start = std::chrono::steady_clock::now();
  19140. auto res = cli.Get("/stream_without_length");
  19141. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19142. std::chrono::steady_clock::now() - start)
  19143. .count();
  19144. ASSERT_FALSE(res);
  19145. EXPECT_EQ(Error::Read, res.error());
  19146. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19147. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19148. }
  19149. {
  19150. auto start = std::chrono::steady_clock::now();
  19151. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19152. EXPECT_EQ("abcd", string(data, data_length));
  19153. return true;
  19154. });
  19155. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19156. std::chrono::steady_clock::now() - start)
  19157. .count();
  19158. ASSERT_FALSE(res);
  19159. EXPECT_EQ(Error::Read, res.error());
  19160. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19161. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19162. }
  19163. }
  19164. TEST(MaxTimeoutTest, ContentStream) {
  19165. time_t timeout = 2000;
  19166. time_t threshold = 200;
  19167. Server svr;
  19168. Client cli("localhost", PORT);
  19169. max_timeout_test(svr, cli, timeout, threshold);
  19170. }
  19171. #ifdef CPPHTTPLIB_SSL_ENABLED
  19172. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19173. time_t timeout = 2000;
  19174. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19176. SSLClient cli("localhost", PORT);
  19177. cli.enable_server_certificate_verification(false);
  19178. max_timeout_test(svr, cli, timeout, threshold);
  19179. }
  19180. #endif
  19181. class EventDispatcher {
  19182. public:
  19183. EventDispatcher() {}
  19184. bool wait_event(DataSink *sink) {
  19185. unique_lock<mutex> lk(m_);
  19186. int id = id_;
  19187. // Wait with timeout to prevent hanging if client disconnects
  19188. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19189. [&] { return cid_ == id; })) {
  19190. return false; // Timeout occurred
  19191. }
  19192. sink->write(message_.data(), message_.size());
  19193. return true;
  19194. }
  19195. void send_event(const string &message) {
  19196. lock_guard<mutex> lk(m_);
  19197. cid_ = id_++;
  19198. message_ = message;
  19199. cv_.notify_all();
  19200. }
  19201. private:
  19202. mutex m_;
  19203. condition_variable cv_;
  19204. atomic_int id_{0};
  19205. atomic_int cid_{-1};
  19206. string message_;
  19207. };
  19208. TEST(ClientInThreadTest, Issue2068) {
  19209. EventDispatcher ed;
  19210. Server svr;
  19211. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19212. res.set_chunked_content_provider("text/event-stream",
  19213. [&](size_t /*offset*/, DataSink &sink) {
  19214. return ed.wait_event(&sink);
  19215. });
  19216. });
  19217. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19218. svr.wait_until_ready();
  19219. thread event_thread([&] {
  19220. int id = 0;
  19221. while (svr.is_running()) {
  19222. this_thread::sleep_for(chrono::milliseconds(500));
  19223. std::stringstream ss;
  19224. ss << "data: " << id << "\n\n";
  19225. ed.send_event(ss.str());
  19226. id++;
  19227. }
  19228. });
  19229. auto se = detail::scope_exit([&] {
  19230. svr.stop();
  19231. listen_thread.join();
  19232. event_thread.join();
  19233. ASSERT_FALSE(svr.is_running());
  19234. });
  19235. {
  19236. auto client = detail::make_unique<Client>(HOST, PORT);
  19237. client->set_read_timeout(std::chrono::minutes(10));
  19238. std::atomic<bool> stop{false};
  19239. std::thread t([&] {
  19240. client->Get("/event1",
  19241. [&](const char *, size_t) -> bool { return !stop; });
  19242. });
  19243. std::this_thread::sleep_for(std::chrono::seconds(2));
  19244. stop = true;
  19245. client->stop();
  19246. t.join();
  19247. // Reset client after thread has finished
  19248. client.reset();
  19249. }
  19250. }
  19251. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19252. auto handled = false;
  19253. Server svr;
  19254. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19255. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19256. auto se = detail::scope_exit([&] {
  19257. svr.stop();
  19258. t.join();
  19259. ASSERT_FALSE(svr.is_running());
  19260. ASSERT_FALSE(handled);
  19261. });
  19262. svr.wait_until_ready();
  19263. // Two Content-Length headers with different values — must be rejected
  19264. auto req = "POST /test HTTP/1.1\r\n"
  19265. "Content-Length: 5\r\n"
  19266. "Content-Length: 10\r\n"
  19267. "\r\n"
  19268. "hello";
  19269. std::string response;
  19270. ASSERT_TRUE(send_request(1, req, &response));
  19271. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19272. response.substr(0, response.find("\r\n")));
  19273. }
  19274. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19275. auto handled = false;
  19276. Server svr;
  19277. svr.Post("/test", [&](const Request &, Response &res) {
  19278. handled = true;
  19279. res.set_content("ok", "text/plain");
  19280. });
  19281. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19282. auto se = detail::scope_exit([&] {
  19283. svr.stop();
  19284. t.join();
  19285. ASSERT_FALSE(svr.is_running());
  19286. ASSERT_TRUE(handled);
  19287. });
  19288. svr.wait_until_ready();
  19289. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19290. auto req = "POST /test HTTP/1.1\r\n"
  19291. "Host: localhost\r\n"
  19292. "Content-Length: 5\r\n"
  19293. "Content-Length: 5\r\n"
  19294. "\r\n"
  19295. "hello";
  19296. std::string response;
  19297. ASSERT_TRUE(send_request(1, req, &response));
  19298. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19299. }
  19300. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19301. Server svr;
  19302. svr.Get("/test", [](const Request &, Response &res) {
  19303. res.set_content("ok", "text/plain");
  19304. });
  19305. auto port = svr.bind_to_any_port(HOST);
  19306. thread t = thread([&] { svr.listen_after_bind(); });
  19307. auto se = detail::scope_exit([&] {
  19308. svr.stop();
  19309. t.join();
  19310. ASSERT_FALSE(svr.is_running());
  19311. });
  19312. svr.wait_until_ready();
  19313. auto status_line = [&](const std::string &host_lines) {
  19314. std::string res;
  19315. send_request(
  19316. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19317. &res, port);
  19318. return res.substr(0, res.find("\r\n"));
  19319. };
  19320. const char *accepted[] = {
  19321. "Host: localhost\r\n",
  19322. "Host: a.example:8080\r\n",
  19323. "Host: my_service\r\n",
  19324. "Host: [::1]:8080\r\n",
  19325. "Host: [fe80::1%25eth0]\r\n",
  19326. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19327. };
  19328. for (auto host_lines : accepted) {
  19329. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19330. }
  19331. const char *rejected[] = {
  19332. "Host: a.example\r\nHost: b.example\r\n",
  19333. "Host: a.example\r\nHost: a.example\r\n",
  19334. "Host: a@b.example\r\n",
  19335. "Host: a.example/b\r\n",
  19336. "Host: a.example\\b\r\n",
  19337. "Host: a.example?b\r\n",
  19338. "Host: a.example#b\r\n",
  19339. "Host: a.example b.example\r\n",
  19340. };
  19341. for (auto host_lines : rejected) {
  19342. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19343. << host_lines;
  19344. }
  19345. }
  19346. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19347. Server svr;
  19348. svr.Get("/", [](const Request &req, Response &res) {
  19349. EXPECT_EQ(2U, req.trailers.size());
  19350. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19351. // Denied
  19352. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19353. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19354. // Accepted
  19355. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19356. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19357. EXPECT_TRUE(req.has_trailer("X-World"));
  19358. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19359. res.set_content("ok", "text/plain");
  19360. });
  19361. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19362. auto se = detail::scope_exit([&] {
  19363. svr.stop();
  19364. t.join();
  19365. ASSERT_FALSE(svr.is_running());
  19366. });
  19367. svr.wait_until_ready();
  19368. const std::string req = "GET / HTTP/1.1\r\n"
  19369. "Transfer-Encoding: chunked\r\n"
  19370. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19371. "\r\n"
  19372. "0\r\n"
  19373. "Content-Length: 10\r\n"
  19374. "Host: internal.local\r\n"
  19375. "Content-Type: malicious/content\r\n"
  19376. "Cookie: any\r\n"
  19377. "Set-Cookie: any\r\n"
  19378. "X-Forwarded-For: attacker.com\r\n"
  19379. "X-Real-Ip: 1.1.1.1\r\n"
  19380. "X-Hello: hello\r\n"
  19381. "X-World: world\r\n"
  19382. "\r\n";
  19383. std::string res;
  19384. ASSERT_TRUE(send_request(1, req, &res));
  19385. }
  19386. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19387. // several field lines, and the combined value is what has to be parsed. A
  19388. // Trailer field split across lines therefore declares every name it lists;
  19389. // reading only the first line silently drops the trailers the later lines
  19390. // declare. The prohibited-trailer filter still applies to every line.
  19391. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19392. Server svr;
  19393. size_t observed_trailer_count = 0;
  19394. std::string observed_hello;
  19395. std::string observed_world;
  19396. bool observed_content_length = true;
  19397. svr.Get("/", [&](const Request &req, Response &res) {
  19398. observed_trailer_count = req.trailers.size();
  19399. observed_hello = req.get_trailer_value("X-Hello");
  19400. observed_world = req.get_trailer_value("X-World");
  19401. observed_content_length = req.has_trailer("Content-Length");
  19402. res.set_content("ok", "text/plain");
  19403. });
  19404. auto port = svr.bind_to_any_port(HOST);
  19405. thread t = thread([&]() { svr.listen_after_bind(); });
  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. const std::string req = "GET / HTTP/1.1\r\n"
  19413. "Host: localhost\r\n"
  19414. "Transfer-Encoding: chunked\r\n"
  19415. "Trailer: X-Hello\r\n"
  19416. "Trailer: X-World, Content-Length\r\n"
  19417. "\r\n"
  19418. "0\r\n"
  19419. "X-Hello: hello\r\n"
  19420. "X-World: world\r\n"
  19421. "Content-Length: 10\r\n"
  19422. "\r\n";
  19423. std::string res;
  19424. ASSERT_TRUE(send_request(1, req, &res, port));
  19425. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19426. // Accepted: both field lines contribute to the declared set
  19427. EXPECT_EQ(2U, observed_trailer_count);
  19428. EXPECT_EQ(observed_hello, "hello");
  19429. EXPECT_EQ(observed_world, "world");
  19430. // Denied: a prohibited name stays prohibited on a later field line
  19431. EXPECT_FALSE(observed_content_length);
  19432. }
  19433. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19434. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19435. // unbounded run of fields that are never declared, because the counter would
  19436. // only advance for declared fields.
  19437. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19438. Server svr;
  19439. bool handler_called = false;
  19440. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19441. handler_called = true;
  19442. res.set_content("ok", "text/plain");
  19443. });
  19444. auto port = svr.bind_to_any_port(HOST);
  19445. thread t = thread([&]() { svr.listen_after_bind(); });
  19446. auto se = detail::scope_exit([&] {
  19447. svr.stop();
  19448. t.join();
  19449. ASSERT_FALSE(svr.is_running());
  19450. });
  19451. svr.wait_until_ready();
  19452. // Declare nothing, then send far more undeclared trailer fields than the
  19453. // header-count limit. Parsing must stop and reject the request rather than
  19454. // read every line.
  19455. std::string req = "GET / HTTP/1.1\r\n"
  19456. "Transfer-Encoding: chunked\r\n"
  19457. "\r\n"
  19458. "0\r\n";
  19459. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19460. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19461. }
  19462. req += "\r\n";
  19463. std::string res;
  19464. ASSERT_TRUE(send_request(1, req, &res, port));
  19465. // The request is rejected before the handler runs.
  19466. EXPECT_FALSE(handler_called);
  19467. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19468. }
  19469. // The set of declared trailer names is capped so a peer cannot grow it without
  19470. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19471. // declared past the cap is not honored, even if the field is actually sent.
  19472. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19473. Server svr;
  19474. // One name inside the cap and one past it, so the test tracks the cap rather
  19475. // than a fixed count.
  19476. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19477. const std::string within_cap_name = "X-T-0";
  19478. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19479. bool observed_within_cap = false;
  19480. bool observed_past_cap = false;
  19481. svr.Get("/", [&](const Request &req, Response &res) {
  19482. observed_within_cap = req.has_trailer(within_cap_name);
  19483. observed_past_cap = req.has_trailer(past_cap_name);
  19484. res.set_content("ok", "text/plain");
  19485. });
  19486. auto port = svr.bind_to_any_port(HOST);
  19487. thread t = thread([&]() { svr.listen_after_bind(); });
  19488. auto se = detail::scope_exit([&] {
  19489. svr.stop();
  19490. t.join();
  19491. ASSERT_FALSE(svr.is_running());
  19492. });
  19493. svr.wait_until_ready();
  19494. // Declare more trailer names than the cap in a single Trailer field, then
  19495. // actually send the first (within the cap) and the last (past it).
  19496. std::string trailer_decl = "Trailer: ";
  19497. for (int i = 0; i < declared_count; i++) {
  19498. if (i != 0) { trailer_decl += ", "; }
  19499. trailer_decl += "X-T-" + std::to_string(i);
  19500. }
  19501. trailer_decl += "\r\n";
  19502. const std::string req = "GET / HTTP/1.1\r\n"
  19503. "Host: localhost\r\n"
  19504. "Transfer-Encoding: chunked\r\n" +
  19505. trailer_decl +
  19506. "\r\n"
  19507. "0\r\n" +
  19508. within_cap_name + ": a\r\n" + past_cap_name +
  19509. ": b\r\n"
  19510. "\r\n";
  19511. std::string res;
  19512. ASSERT_TRUE(send_request(1, req, &res, port));
  19513. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19514. // A name within the cap is honored; one declared past the cap is dropped.
  19515. EXPECT_TRUE(observed_within_cap);
  19516. EXPECT_FALSE(observed_past_cap);
  19517. }
  19518. // A direct client that is not listed in trusted_proxies must not be able to
  19519. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19520. // the peer address on the actual TCP connection determines whether the
  19521. // header is honored.
  19522. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19523. Server svr;
  19524. // Deliberately does NOT include the loopback address the test client
  19525. // actually connects from, so the direct connection is not a trusted proxy.
  19526. svr.set_trusted_proxies({"203.0.113.66"});
  19527. std::string observed_remote_addr;
  19528. svr.Get("/ip", [&](const Request &req, Response &res) {
  19529. observed_remote_addr = req.remote_addr;
  19530. res.set_content("ok", "text/plain");
  19531. });
  19532. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19533. auto se = detail::scope_exit([&] {
  19534. svr.stop();
  19535. t.join();
  19536. ASSERT_FALSE(svr.is_running());
  19537. });
  19538. svr.wait_until_ready();
  19539. Client cli(HOST, PORT);
  19540. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19542. EXPECT_EQ(StatusCode::OK_200, res->status);
  19543. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19544. // ignored entirely and the real connection-level address retained.
  19545. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19546. observed_remote_addr == "127.0.0.1");
  19547. }
  19548. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19549. Server svr;
  19550. std::string observed_remote_addr;
  19551. std::string observed_xff;
  19552. svr.Get("/ip", [&](const Request &req, Response &res) {
  19553. observed_remote_addr = req.remote_addr;
  19554. observed_xff = req.get_header_value("X-Forwarded-For");
  19555. res.set_content("ok", "text/plain");
  19556. });
  19557. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19558. auto se = detail::scope_exit([&] {
  19559. svr.stop();
  19560. t.join();
  19561. ASSERT_FALSE(svr.is_running());
  19562. });
  19563. svr.wait_until_ready();
  19564. Client cli(HOST, PORT);
  19565. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19567. EXPECT_EQ(StatusCode::OK_200, res->status);
  19568. EXPECT_EQ(observed_xff, "203.0.113.66");
  19569. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19570. observed_remote_addr == "127.0.0.1");
  19571. }
  19572. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19573. Server svr;
  19574. svr.set_trusted_proxies({"203.0.113.66"});
  19575. std::string observed_remote_addr;
  19576. std::string observed_xff;
  19577. svr.Get("/ip", [&](const Request &req, Response &res) {
  19578. observed_remote_addr = req.remote_addr;
  19579. observed_xff = req.get_header_value("X-Forwarded-For");
  19580. res.set_content("ok", "text/plain");
  19581. });
  19582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19583. auto se = detail::scope_exit([&] {
  19584. svr.stop();
  19585. t.join();
  19586. ASSERT_FALSE(svr.is_running());
  19587. });
  19588. svr.wait_until_ready();
  19589. Client cli(HOST, PORT);
  19590. auto res = cli.Get("/ip");
  19591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19592. EXPECT_EQ(StatusCode::OK_200, res->status);
  19593. EXPECT_EQ(observed_xff, "");
  19594. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19595. observed_remote_addr == "127.0.0.1");
  19596. }
  19597. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19598. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19599. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19600. Server svr;
  19601. svr.set_trusted_proxies({"127.0.0.1"});
  19602. svr.Get("/ip", [](const Request &req, Response &res) {
  19603. res.set_content(req.remote_addr, "text/plain");
  19604. });
  19605. auto port = svr.bind_to_any_port("::");
  19606. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19607. thread t = thread([&] { svr.listen_after_bind(); });
  19608. auto se = detail::scope_exit([&] {
  19609. svr.stop();
  19610. t.join();
  19611. ASSERT_FALSE(svr.is_running());
  19612. });
  19613. svr.wait_until_ready();
  19614. Client cli("127.0.0.1", port);
  19615. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19617. EXPECT_EQ("198.51.100.23", res->body);
  19618. }
  19619. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19620. Server svr;
  19621. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19622. svr.Get("/ip", [](const Request &req, Response &res) {
  19623. res.set_content(req.remote_addr, "text/plain");
  19624. });
  19625. auto port = svr.bind_to_any_port(HOST);
  19626. ASSERT_GT(port, 0);
  19627. thread t = thread([&] { svr.listen_after_bind(); });
  19628. auto se = detail::scope_exit([&] {
  19629. svr.stop();
  19630. t.join();
  19631. ASSERT_FALSE(svr.is_running());
  19632. });
  19633. svr.wait_until_ready();
  19634. Client cli(HOST, port);
  19635. auto res = cli.Get(
  19636. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19638. EXPECT_EQ("198.51.100.23", res->body);
  19639. }
  19640. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19641. Server svr;
  19642. // Include the loopback address the test client actually connects from, so
  19643. // the direct connection itself is recognized as the trusted proxy hop.
  19644. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19645. std::string observed_remote_addr;
  19646. std::string observed_xff;
  19647. svr.Get("/ip", [&](const Request &req, Response &res) {
  19648. observed_remote_addr = req.remote_addr;
  19649. observed_xff = req.get_header_value("X-Forwarded-For");
  19650. res.set_content("ok", "text/plain");
  19651. });
  19652. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19653. auto se = detail::scope_exit([&] {
  19654. svr.stop();
  19655. t.join();
  19656. ASSERT_FALSE(svr.is_running());
  19657. });
  19658. svr.wait_until_ready();
  19659. Client cli(HOST, PORT);
  19660. auto res = cli.Get(
  19661. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19663. EXPECT_EQ(StatusCode::OK_200, res->status);
  19664. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19665. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19666. }
  19667. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19668. Server svr;
  19669. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19670. std::string observed_remote_addr;
  19671. std::string observed_xff;
  19672. svr.Get("/ip", [&](const Request &req, Response &res) {
  19673. observed_remote_addr = req.remote_addr;
  19674. observed_xff = req.get_header_value("X-Forwarded-For");
  19675. res.set_content("ok", "text/plain");
  19676. });
  19677. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19678. auto se = detail::scope_exit([&] {
  19679. svr.stop();
  19680. t.join();
  19681. ASSERT_FALSE(svr.is_running());
  19682. });
  19683. svr.wait_until_ready();
  19684. Client cli(HOST, PORT);
  19685. auto res = cli.Get(
  19686. "/ip",
  19687. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19689. EXPECT_EQ(StatusCode::OK_200, res->status);
  19690. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19691. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19692. }
  19693. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19694. Server svr;
  19695. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19696. std::string observed_remote_addr;
  19697. std::string observed_xff;
  19698. svr.Get("/ip", [&](const Request &req, Response &res) {
  19699. observed_remote_addr = req.remote_addr;
  19700. observed_xff = req.get_header_value("X-Forwarded-For");
  19701. res.set_content("ok", "text/plain");
  19702. });
  19703. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19704. auto se = detail::scope_exit([&] {
  19705. svr.stop();
  19706. t.join();
  19707. ASSERT_FALSE(svr.is_running());
  19708. });
  19709. svr.wait_until_ready();
  19710. Client cli(HOST, PORT);
  19711. auto res = cli.Get(
  19712. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19714. EXPECT_EQ(StatusCode::OK_200, res->status);
  19715. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19716. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19717. // and must not be selected.
  19718. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19719. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19720. }
  19721. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19722. Server svr;
  19723. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19724. std::string observed_remote_addr;
  19725. svr.Get("/ip", [&](const Request &req, Response &res) {
  19726. observed_remote_addr = req.remote_addr;
  19727. res.set_content("ok", "text/plain");
  19728. });
  19729. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19730. auto se = detail::scope_exit([&] {
  19731. svr.stop();
  19732. t.join();
  19733. ASSERT_FALSE(svr.is_running());
  19734. });
  19735. svr.wait_until_ready();
  19736. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19737. // a forged address and the trusted proxy's own address; the forged value must
  19738. // not win over the address the trusted proxy actually recorded.
  19739. Client cli(HOST, PORT);
  19740. auto res = cli.Get(
  19741. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19743. EXPECT_EQ(StatusCode::OK_200, res->status);
  19744. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19745. }
  19746. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19747. Server svr;
  19748. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19749. std::string observed_remote_addr;
  19750. std::string observed_xff;
  19751. svr.Get("/ip", [&](const Request &req, Response &res) {
  19752. observed_remote_addr = req.remote_addr;
  19753. observed_xff = req.get_header_value("X-Forwarded-For");
  19754. res.set_content("ok", "text/plain");
  19755. });
  19756. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19757. auto se = detail::scope_exit([&] {
  19758. svr.stop();
  19759. t.join();
  19760. ASSERT_FALSE(svr.is_running());
  19761. });
  19762. svr.wait_until_ready();
  19763. Client cli(HOST, PORT);
  19764. auto res = cli.Get(
  19765. "/ip",
  19766. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19768. EXPECT_EQ(StatusCode::OK_200, res->status);
  19769. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19770. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19771. }
  19772. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19773. Server svr;
  19774. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19775. std::string observed_remote_addr;
  19776. std::string observed_xff;
  19777. svr.Get("/ip", [&](const Request &req, Response &res) {
  19778. observed_remote_addr = req.remote_addr;
  19779. observed_xff = req.get_header_value("X-Forwarded-For");
  19780. res.set_content("ok", "text/plain");
  19781. });
  19782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19783. auto se = detail::scope_exit([&] {
  19784. svr.stop();
  19785. t.join();
  19786. ASSERT_FALSE(svr.is_running());
  19787. });
  19788. svr.wait_until_ready();
  19789. std::string raw_req =
  19790. "GET /ip HTTP/1.1\r\n"
  19791. "Host: localhost\r\n"
  19792. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19793. "Connection: close\r\n"
  19794. "\r\n";
  19795. std::string out;
  19796. ASSERT_TRUE(send_request(5, raw_req, &out));
  19797. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19798. // Header parser trims surrounding whitespace of the header value
  19799. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19800. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19801. }
  19802. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19803. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19804. // their own X-Forwarded-For as a separate field line rather than extending the
  19805. // one the client sent, so every occurrence has to be taken into account.
  19806. // Reading only the first one hands back the address the client chose.
  19807. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19808. Server svr;
  19809. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19810. std::string observed_remote_addr;
  19811. size_t observed_xff_count = 0;
  19812. svr.Get("/ip", [&](const Request &req, Response &res) {
  19813. observed_remote_addr = req.remote_addr;
  19814. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19815. res.set_content("ok", "text/plain");
  19816. });
  19817. auto port = svr.bind_to_any_port(HOST);
  19818. thread t = thread([&]() { svr.listen_after_bind(); });
  19819. auto se = detail::scope_exit([&] {
  19820. svr.stop();
  19821. t.join();
  19822. ASSERT_FALSE(svr.is_running());
  19823. });
  19824. svr.wait_until_ready();
  19825. // The client supplies the first field line; the trusted proxy appends the
  19826. // address it observed as a second one.
  19827. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19828. "Host: localhost\r\n"
  19829. "X-Forwarded-For: 1.2.3.4\r\n"
  19830. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19831. "Connection: close\r\n"
  19832. "\r\n";
  19833. std::string out;
  19834. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19835. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19836. EXPECT_EQ(observed_xff_count, 2U);
  19837. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19838. // The same chain spread over one field line per hop derives the same client
  19839. // address, i.e. the split and the comma-joined representations agree.
  19840. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19841. "Host: localhost\r\n"
  19842. "X-Forwarded-For: 1.2.3.4\r\n"
  19843. "X-Forwarded-For: 198.51.100.23\r\n"
  19844. "X-Forwarded-For: 192.0.2.45\r\n"
  19845. "Connection: close\r\n"
  19846. "\r\n";
  19847. out.clear();
  19848. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19849. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19850. EXPECT_EQ(observed_xff_count, 3U);
  19851. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19852. }
  19853. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19854. // crash the server (it used to call front() on an empty vector inside
  19855. // get_client_ip). The connection-level remote address must be retained instead.
  19856. static void run_malformed_xff_test(const std::string &xff_value) {
  19857. Server svr;
  19858. svr.set_trusted_proxies({"192.0.2.45"});
  19859. std::string observed_remote_addr;
  19860. svr.Get("/ip", [&](const Request &req, Response &res) {
  19861. observed_remote_addr = req.remote_addr;
  19862. res.set_content("ok", "text/plain");
  19863. });
  19864. int port = 0;
  19865. thread t = thread([&]() {
  19866. port = svr.bind_to_any_port(HOST);
  19867. svr.listen_after_bind();
  19868. });
  19869. auto se = detail::scope_exit([&] {
  19870. svr.stop();
  19871. t.join();
  19872. ASSERT_FALSE(svr.is_running());
  19873. });
  19874. svr.wait_until_ready();
  19875. Client cli(HOST, port);
  19876. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19878. EXPECT_EQ(StatusCode::OK_200, res->status);
  19879. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19880. observed_remote_addr == "127.0.0.1");
  19881. }
  19882. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19883. run_malformed_xff_test("");
  19884. }
  19885. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19886. run_malformed_xff_test(",");
  19887. }
  19888. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19889. run_malformed_xff_test(", , ,");
  19890. }
  19891. // The same rule applies to Accept: a request whose acceptable types are spread
  19892. // over several field lines must be negotiated against all of them.
  19893. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19894. // case-insensitive connection options. Comparing the whole field value against
  19895. // one option misses a client that sends several of them, and misses every
  19896. // casing but the one written in the comparison.
  19897. //
  19898. // Sends req, reads the response, then reuses the same socket for a second
  19899. // request to find out whether the server kept the connection.
  19900. static void probe_connection_reuse(int port, const std::string &req,
  19901. bool *announced_close, bool *reusable) {
  19902. auto error = Error::Success;
  19903. auto sock = detail::create_client_socket(
  19904. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19905. /*connection_timeout_sec=*/5, 0,
  19906. /*read_timeout_sec=*/1, 0,
  19907. /*write_timeout_sec=*/5, 0, std::string(), error);
  19908. ASSERT_NE(sock, INVALID_SOCKET);
  19909. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19910. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19911. "Host: localhost\r\n"
  19912. "Connection: close\r\n"
  19913. "\r\n";
  19914. std::string first_response;
  19915. std::string second_response;
  19916. detail::process_client_socket(
  19917. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19918. [&](Stream &strm) {
  19919. if (strm.write(req.data(), req.size()) !=
  19920. static_cast<ssize_t>(req.size())) {
  19921. return false;
  19922. }
  19923. char buf[512];
  19924. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19925. // Headers plus the two-byte body of the handler below
  19926. while (reader.getline()) {
  19927. first_response += reader.ptr();
  19928. if (first_response.find("ok") != std::string::npos) { break; }
  19929. }
  19930. if (strm.write(second.data(), second.size()) !=
  19931. static_cast<ssize_t>(second.size())) {
  19932. return true;
  19933. }
  19934. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19935. while (reader2.getline()) {
  19936. second_response += reader2.ptr();
  19937. if (second_response.find("ok") != std::string::npos) { break; }
  19938. }
  19939. return true;
  19940. });
  19941. *announced_close =
  19942. first_response.find("Connection: close") != std::string::npos;
  19943. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19944. }
  19945. class ConnectionTokenTest : public ::testing::Test {
  19946. protected:
  19947. void SetUp() override {
  19948. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19949. res.set_content("ok", "text/plain");
  19950. });
  19951. port_ = svr_.bind_to_any_port(HOST);
  19952. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19953. svr_.wait_until_ready();
  19954. }
  19955. void TearDown() override {
  19956. svr_.stop();
  19957. if (thread_.joinable()) { thread_.join(); }
  19958. }
  19959. Server svr_;
  19960. int port_ = 0;
  19961. thread thread_;
  19962. };
  19963. // "close" alongside another option still closes the connection, and the
  19964. // response says so rather than leaving the peer to discover it.
  19965. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19966. bool announced_close = false;
  19967. bool reusable = true;
  19968. probe_connection_reuse(port_,
  19969. "GET /keepalive HTTP/1.1\r\n"
  19970. "Host: localhost\r\n"
  19971. "Connection: keep-alive, close\r\n"
  19972. "\r\n",
  19973. &announced_close, &reusable);
  19974. EXPECT_TRUE(announced_close);
  19975. EXPECT_FALSE(reusable);
  19976. }
  19977. // "close" split over two field lines is the same list, so it is honored too.
  19978. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19979. bool announced_close = false;
  19980. bool reusable = true;
  19981. probe_connection_reuse(port_,
  19982. "GET /keepalive HTTP/1.1\r\n"
  19983. "Host: localhost\r\n"
  19984. "Connection: keep-alive\r\n"
  19985. "Connection: close\r\n"
  19986. "\r\n",
  19987. &announced_close, &reusable);
  19988. EXPECT_TRUE(announced_close);
  19989. EXPECT_FALSE(reusable);
  19990. }
  19991. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19992. // keep-alive in the spelling everyone actually sends keeps its connection.
  19993. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19994. bool announced_close = false;
  19995. bool reusable = false;
  19996. probe_connection_reuse(port_,
  19997. "GET /keepalive HTTP/1.0\r\n"
  19998. "Host: localhost\r\n"
  19999. "Connection: keep-alive\r\n"
  20000. "\r\n",
  20001. &announced_close, &reusable);
  20002. EXPECT_FALSE(announced_close);
  20003. EXPECT_TRUE(reusable);
  20004. }
  20005. // A token the value merely contains is not the token itself.
  20006. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20007. bool announced_close = false;
  20008. bool reusable = false;
  20009. probe_connection_reuse(port_,
  20010. "GET /keepalive HTTP/1.1\r\n"
  20011. "Host: localhost\r\n"
  20012. "Connection: notclose\r\n"
  20013. "\r\n",
  20014. &announced_close, &reusable);
  20015. EXPECT_FALSE(announced_close);
  20016. EXPECT_TRUE(reusable);
  20017. }
  20018. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20019. Server svr;
  20020. std::vector<std::string> observed_types;
  20021. svr.Get("/", [&](const Request &req, Response &res) {
  20022. observed_types = req.accept_content_types;
  20023. res.set_content("ok", "text/plain");
  20024. });
  20025. auto port = svr.bind_to_any_port(HOST);
  20026. thread t = thread([&]() { svr.listen_after_bind(); });
  20027. auto se = detail::scope_exit([&] {
  20028. svr.stop();
  20029. t.join();
  20030. ASSERT_FALSE(svr.is_running());
  20031. });
  20032. svr.wait_until_ready();
  20033. Client cli(HOST, port);
  20034. Headers headers;
  20035. headers.emplace("Accept", "text/plain;q=0.5");
  20036. headers.emplace("Accept", "application/json");
  20037. auto res = cli.Get("/", headers);
  20038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20039. EXPECT_EQ(StatusCode::OK_200, res->status);
  20040. // Sorted by q-value, so the second field line's type comes first
  20041. ASSERT_EQ(2U, observed_types.size());
  20042. EXPECT_EQ("application/json", observed_types[0]);
  20043. EXPECT_EQ("text/plain", observed_types[1]);
  20044. }
  20045. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20046. // empty field line must not contribute a bare comma to the combined value.
  20047. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20048. Server svr;
  20049. std::vector<std::string> observed_types;
  20050. svr.Get("/", [&](const Request &req, Response &res) {
  20051. observed_types = req.accept_content_types;
  20052. res.set_content("ok", "text/plain");
  20053. });
  20054. auto port = svr.bind_to_any_port(HOST);
  20055. thread t = thread([&]() { svr.listen_after_bind(); });
  20056. auto se = detail::scope_exit([&] {
  20057. svr.stop();
  20058. t.join();
  20059. ASSERT_FALSE(svr.is_running());
  20060. });
  20061. svr.wait_until_ready();
  20062. // Empty first field line, then a real one
  20063. std::string raw_req = "GET / HTTP/1.1\r\n"
  20064. "Host: localhost\r\n"
  20065. "Accept:\r\n"
  20066. "Accept: application/json\r\n"
  20067. "Connection: close\r\n"
  20068. "\r\n";
  20069. std::string out;
  20070. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20071. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20072. ASSERT_EQ(1U, observed_types.size());
  20073. EXPECT_EQ("application/json", observed_types[0]);
  20074. }
  20075. // The skip in get_combined_header_value() is what keeps an empty field line
  20076. // from contributing a bare comma. Only a trailing empty field line exercises
  20077. // it: a leading one is already covered by the "combined is still empty" check,
  20078. // and parse_accept_header() now ignores the empty element either way, so the
  20079. // request-level test above can no longer tell the two apart.
  20080. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20081. Headers headers;
  20082. headers.emplace("Accept", "text/html");
  20083. headers.emplace("Accept", "");
  20084. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20085. headers.clear();
  20086. headers.emplace("Accept", "");
  20087. headers.emplace("Accept", "application/json");
  20088. EXPECT_EQ("application/json",
  20089. detail::get_combined_header_value(headers, "Accept"));
  20090. }
  20091. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20092. // An encoding offered on a later Accept-Encoding field line is still offered.
  20093. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20094. Server svr;
  20095. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20096. res.set_content(std::string(1024, 'x'), "text/plain");
  20097. });
  20098. auto port = svr.bind_to_any_port(HOST);
  20099. thread t = thread([&]() { svr.listen_after_bind(); });
  20100. auto se = detail::scope_exit([&] {
  20101. svr.stop();
  20102. t.join();
  20103. ASSERT_FALSE(svr.is_running());
  20104. });
  20105. svr.wait_until_ready();
  20106. Client cli(HOST, port);
  20107. cli.set_decompress(false);
  20108. Headers headers;
  20109. headers.emplace("Accept-Encoding", "identity");
  20110. headers.emplace("Accept-Encoding", "gzip");
  20111. auto res = cli.Get("/", headers);
  20112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20113. EXPECT_EQ(StatusCode::OK_200, res->status);
  20114. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20115. }
  20116. #endif
  20117. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20118. // Transfer-Encoding is not its body.
  20119. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20120. Server svr;
  20121. svr.set_payload_max_length(8);
  20122. svr.Post("/test", [](const Request &, Response &res) {
  20123. res.set_content("ok", "text/plain");
  20124. });
  20125. auto port = svr.bind_to_any_port(HOST);
  20126. ASSERT_GT(port, 0);
  20127. thread t = thread([&] { svr.listen_after_bind(); });
  20128. auto se = detail::scope_exit([&] {
  20129. svr.stop();
  20130. t.join();
  20131. ASSERT_FALSE(svr.is_running());
  20132. });
  20133. svr.wait_until_ready();
  20134. std::string resp;
  20135. ASSERT_TRUE(send_request(1,
  20136. "POST /test HTTP/1.1\r\n"
  20137. "Host: localhost\r\n"
  20138. "Connection: close\r\n"
  20139. "\r\n" +
  20140. std::string(16, 'X'),
  20141. &resp, port));
  20142. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20143. }
  20144. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20145. Server svr;
  20146. svr.Post("/post", [&](const Request &req, Response &res) {
  20147. res.set_content(req.body, "text/plain");
  20148. });
  20149. svr.Put("/put", [&](const Request &req, Response &res) {
  20150. res.set_content(req.body, "text/plain");
  20151. });
  20152. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20153. res.set_content(req.body, "text/plain");
  20154. });
  20155. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20156. res.set_content(req.body, "text/plain");
  20157. });
  20158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20159. auto se = detail::scope_exit([&] {
  20160. svr.stop();
  20161. t.join();
  20162. ASSERT_FALSE(svr.is_running());
  20163. });
  20164. svr.wait_until_ready();
  20165. std::string resp;
  20166. // POST without Content-Length
  20167. ASSERT_TRUE(send_request(5,
  20168. "POST /post HTTP/1.1\r\n"
  20169. "Host: localhost\r\n"
  20170. "Connection: close\r\n"
  20171. "\r\n",
  20172. &resp));
  20173. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20174. // PUT without Content-Length
  20175. resp.clear();
  20176. ASSERT_TRUE(send_request(5,
  20177. "PUT /put HTTP/1.1\r\n"
  20178. "Host: localhost\r\n"
  20179. "Connection: close\r\n"
  20180. "\r\n",
  20181. &resp));
  20182. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20183. // PATCH without Content-Length
  20184. resp.clear();
  20185. ASSERT_TRUE(send_request(5,
  20186. "PATCH /patch HTTP/1.1\r\n"
  20187. "Host: localhost\r\n"
  20188. "Connection: close\r\n"
  20189. "\r\n",
  20190. &resp));
  20191. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20192. // DELETE without Content-Length
  20193. resp.clear();
  20194. ASSERT_TRUE(send_request(5,
  20195. "DELETE /delete HTTP/1.1\r\n"
  20196. "Host: localhost\r\n"
  20197. "Connection: close\r\n"
  20198. "\r\n",
  20199. &resp));
  20200. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20201. }
  20202. //==============================================================================
  20203. // open_stream() Tests
  20204. //==============================================================================
  20205. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20206. std::string result;
  20207. char buf[8192];
  20208. ssize_t n;
  20209. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20210. result.append(buf, static_cast<size_t>(n));
  20211. }
  20212. return result;
  20213. }
  20214. // Mock stream for unit tests
  20215. class MockStream : public Stream {
  20216. public:
  20217. std::string data;
  20218. size_t pos = 0;
  20219. ssize_t error_after = -1; // -1 = no error
  20220. explicit MockStream(const std::string &d, ssize_t err = -1)
  20221. : data(d), error_after(err) {}
  20222. bool is_readable() const override { return true; }
  20223. bool wait_readable() const override { return true; }
  20224. bool wait_writable() const override { return true; }
  20225. ssize_t read(char *ptr, size_t size) override {
  20226. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20227. if (pos >= data.size()) return 0;
  20228. size_t limit =
  20229. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20230. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20231. std::memcpy(ptr, data.data() + pos, to_read);
  20232. pos += to_read;
  20233. return static_cast<ssize_t>(to_read);
  20234. }
  20235. ssize_t write(const char *, size_t) override { return -1; }
  20236. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20237. ip = "127.0.0.1";
  20238. port = 0;
  20239. }
  20240. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20241. ip = "127.0.0.1";
  20242. port = 0;
  20243. }
  20244. socket_t socket() const override { return INVALID_SOCKET; }
  20245. time_t duration() const override { return 0; }
  20246. };
  20247. TEST(StreamHandleTest, Basic) {
  20248. ClientImpl::StreamHandle handle;
  20249. EXPECT_FALSE(handle.is_valid());
  20250. handle.response = detail::make_unique<Response>();
  20251. handle.error = Error::Connection;
  20252. EXPECT_FALSE(handle.is_valid());
  20253. handle.error = Error::Success;
  20254. EXPECT_TRUE(handle.is_valid());
  20255. }
  20256. TEST(BodyReaderTest, Basic) {
  20257. MockStream stream("Hello, World!");
  20258. detail::BodyReader reader;
  20259. reader.stream = &stream;
  20260. reader.content_length = 13;
  20261. char buf[32];
  20262. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20263. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20264. EXPECT_TRUE(reader.eof);
  20265. }
  20266. TEST(BodyReaderTest, NoStream) {
  20267. detail::BodyReader reader;
  20268. char buf[32];
  20269. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20270. EXPECT_EQ(Error::Connection, reader.last_error);
  20271. }
  20272. TEST(BodyReaderTest, Error) {
  20273. MockStream stream("Hello, World!", 5);
  20274. detail::BodyReader reader;
  20275. reader.stream = &stream;
  20276. reader.content_length = 13;
  20277. char buf[32];
  20278. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20279. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20280. EXPECT_EQ(Error::Read, reader.last_error);
  20281. }
  20282. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20283. // Mock-based StreamHandle tests relying on private internals are removed.
  20284. class OpenStreamTest : public ::testing::Test {
  20285. protected:
  20286. void SetUp() override {
  20287. svr_.Get("/hello", [](const Request &, Response &res) {
  20288. res.set_content("Hello World!", "text/plain");
  20289. });
  20290. svr_.Get("/large", [](const Request &, Response &res) {
  20291. res.set_content(std::string(10000, 'X'), "text/plain");
  20292. });
  20293. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20294. res.set_content("Hello World!", "image/jpeg");
  20295. res.set_header("Content-Encoding", "UTF-8");
  20296. });
  20297. svr_.Get("/chunked", [](const Request &, Response &res) {
  20298. res.set_chunked_content_provider("text/plain",
  20299. [](size_t offset, DataSink &sink) {
  20300. if (offset < 15) {
  20301. sink.write("chunk", 5);
  20302. return true;
  20303. }
  20304. sink.done();
  20305. return true;
  20306. });
  20307. });
  20308. svr_.Get("/compressible", [](const Request &, Response &res) {
  20309. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20310. DataSink &sink) {
  20311. if (offset < 100 * 1024) {
  20312. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20313. sink.write(chunk.data(), chunk.size());
  20314. return true;
  20315. }
  20316. sink.done();
  20317. return true;
  20318. });
  20319. });
  20320. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20321. [](const Request & /*req*/, Response &res) {
  20322. auto i = new int(0);
  20323. res.set_header("Trailer", "Content-Length, X-Allowed");
  20324. res.set_chunked_content_provider(
  20325. "text/plain",
  20326. [i](size_t /*offset*/, DataSink &sink) {
  20327. switch (*i) {
  20328. case 0: sink.os << "123"; break;
  20329. case 1: sink.os << "456"; break;
  20330. case 2: sink.os << "789"; break;
  20331. case 3: {
  20332. sink.done_with_trailer(
  20333. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20334. } break;
  20335. }
  20336. (*i)++;
  20337. return true;
  20338. },
  20339. [i](bool success) {
  20340. EXPECT_TRUE(success);
  20341. delete i;
  20342. });
  20343. });
  20344. // Echo headers endpoint for header-related tests
  20345. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20346. std::string body;
  20347. for (const auto &h : req.headers) {
  20348. body.append(h.first);
  20349. body.push_back(':');
  20350. body.append(h.second);
  20351. body.push_back('\n');
  20352. }
  20353. res.set_content(body, "text/plain");
  20354. });
  20355. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20356. std::string body;
  20357. for (const auto &h : req.headers) {
  20358. body.append(h.first);
  20359. body.push_back(':');
  20360. body.append(h.second);
  20361. body.push_back('\n');
  20362. }
  20363. res.set_content(body, "text/plain");
  20364. });
  20365. port_ = svr_.bind_to_any_port("127.0.0.1");
  20366. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20367. svr_.wait_until_ready();
  20368. }
  20369. void TearDown() override {
  20370. svr_.stop();
  20371. if (thread_.joinable()) thread_.join();
  20372. }
  20373. Server svr_;
  20374. std::thread thread_;
  20375. int port_ = 0;
  20376. };
  20377. TEST_F(OpenStreamTest, Basic) {
  20378. Client cli("127.0.0.1", port_);
  20379. auto handle = cli.open_stream("GET", "/hello");
  20380. EXPECT_TRUE(handle.is_valid());
  20381. EXPECT_EQ("Hello World!", read_all(handle));
  20382. }
  20383. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20384. Client cli("127.0.0.1", port_);
  20385. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20386. ASSERT_TRUE(handle.is_valid());
  20387. EXPECT_EQ("Hello World!", read_all(handle));
  20388. }
  20389. TEST_F(OpenStreamTest, SmallBuffer) {
  20390. Client cli("127.0.0.1", port_);
  20391. auto handle = cli.open_stream("GET", "/hello");
  20392. std::string result;
  20393. char buf[4];
  20394. ssize_t n;
  20395. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20396. result.append(buf, static_cast<size_t>(n));
  20397. EXPECT_EQ("Hello World!", result);
  20398. }
  20399. TEST_F(OpenStreamTest, DefaultHeaders) {
  20400. Client cli("127.0.0.1", port_);
  20401. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20402. {
  20403. auto handle = cli.open_stream("GET", "/echo-headers");
  20404. ASSERT_TRUE(handle.is_valid());
  20405. auto body = read_all(handle);
  20406. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20407. std::string::npos);
  20408. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20409. std::string::npos);
  20410. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20411. }
  20412. // open_stream POST with body and no explicit content_type should NOT add
  20413. // text/plain Content-Type (behavior differs from non-streaming path), but
  20414. // should include Content-Length
  20415. {
  20416. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20417. ASSERT_TRUE(handle.is_valid());
  20418. auto body = read_all(handle);
  20419. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20420. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20421. }
  20422. // open_stream POST with explicit Content-Type should preserve it
  20423. {
  20424. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20425. {{"Content-Type", "application/custom"}},
  20426. "{}", "application/custom");
  20427. ASSERT_TRUE(handle.is_valid());
  20428. auto body = read_all(handle);
  20429. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20430. }
  20431. // User-specified User-Agent must not be overwritten for stream API
  20432. {
  20433. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20434. {{"User-Agent", "MyAgent/1.2"}});
  20435. ASSERT_TRUE(handle.is_valid());
  20436. auto body = read_all(handle);
  20437. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20438. }
  20439. }
  20440. TEST_F(OpenStreamTest, Large) {
  20441. Client cli("127.0.0.1", port_);
  20442. auto handle = cli.open_stream("GET", "/large");
  20443. EXPECT_EQ(10000u, read_all(handle).size());
  20444. }
  20445. TEST_F(OpenStreamTest, ConnectionError) {
  20446. Client cli("127.0.0.1", 9999);
  20447. auto handle = cli.open_stream("GET", "/hello");
  20448. EXPECT_FALSE(handle.is_valid());
  20449. }
  20450. TEST_F(OpenStreamTest, Chunked) {
  20451. Client cli("127.0.0.1", port_);
  20452. auto handle = cli.open_stream("GET", "/chunked");
  20453. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20454. "Transfer-Encoding") == "chunked");
  20455. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20456. }
  20457. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20458. Client cli("127.0.0.1", port_);
  20459. auto handle =
  20460. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20461. ASSERT_TRUE(handle.is_valid());
  20462. // Consume body to allow trailers to be received/parsed
  20463. auto body = read_all(handle);
  20464. // Explicitly parse trailers (ensure trailers are available for assertion)
  20465. handle.parse_trailers_if_needed();
  20466. EXPECT_EQ(std::string("123456789"), body);
  20467. // The response should include a Trailer header declaring both names
  20468. ASSERT_TRUE(handle.response);
  20469. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20470. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20471. handle.response->get_header_value("Trailer"));
  20472. // Prohibited trailer must not be present
  20473. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20474. // Allowed trailer should be present
  20475. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20476. EXPECT_EQ(std::string("yes"),
  20477. handle.response->get_trailer_value("X-Allowed"));
  20478. // Verify trailers are NOT present as regular headers
  20479. EXPECT_EQ(std::string(""),
  20480. handle.response->get_header_value("Content-Length"));
  20481. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20482. }
  20483. // Accepts one connection on an OS-assigned port, which it hands over through
  20484. // port_promise, reads the request head and sends back response. after_send,
  20485. // if given, runs on the connection before it is closed.
  20486. static std::thread
  20487. serve_single_response(std::promise<int> &port_promise,
  20488. const std::string &response,
  20489. std::function<void(socket_t)> after_send = nullptr) {
  20490. return std::thread([&port_promise, response, after_send] {
  20491. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20492. default_socket_options(srv);
  20493. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20494. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20495. sockaddr_in addr{};
  20496. addr.sin_family = AF_INET;
  20497. addr.sin_port = htons(0); // Let OS assign a free port
  20498. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20499. int opt = 1;
  20500. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20501. #ifdef _WIN32
  20502. reinterpret_cast<const char *>(&opt),
  20503. #else
  20504. &opt,
  20505. #endif
  20506. sizeof(opt));
  20507. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20508. ::listen(srv, 1) != 0) {
  20509. port_promise.set_value(-1);
  20510. detail::close_socket(srv);
  20511. return;
  20512. }
  20513. socklen_t addr_len = sizeof(addr);
  20514. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20515. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20516. sockaddr_in cli_addr{};
  20517. socklen_t cli_len = sizeof(cli_addr);
  20518. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20519. if (cli != INVALID_SOCKET) {
  20520. // Read the complete HTTP request (until the blank line that terminates
  20521. // headers) before sending the response. If the server closes the socket
  20522. // while the client's request data is still unread in the kernel receive
  20523. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20524. // connection on both sides: it discards the client's receive buffer
  20525. // (which already holds our response) and causes any in-progress write on
  20526. // the client to fail with ECONNRESET. Reading all request data first
  20527. // ensures close() emits a graceful FIN.
  20528. {
  20529. char rbuf[256];
  20530. std::string req;
  20531. while (req.find("\r\n\r\n") == std::string::npos) {
  20532. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20533. if (n <= 0) { break; }
  20534. req.append(rbuf, static_cast<size_t>(n));
  20535. }
  20536. }
  20537. ::send(cli,
  20538. #ifdef _WIN32
  20539. static_cast<const char *>(response.c_str()),
  20540. static_cast<int>(response.size()),
  20541. #else
  20542. response.c_str(), response.size(),
  20543. #endif
  20544. 0);
  20545. if (after_send) { after_send(cli); }
  20546. detail::close_socket(cli);
  20547. }
  20548. detail::close_socket(srv);
  20549. });
  20550. }
  20551. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20552. #ifndef _WIN32
  20553. signal(SIGPIPE, SIG_IGN);
  20554. #endif
  20555. std::promise<int> port_promise;
  20556. auto port_future = port_promise.get_future();
  20557. auto server_thread =
  20558. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20559. "Content-Type: text/plain\r\n"
  20560. "Content-Length: not-a-number\r\n"
  20561. "Connection: close\r\n"
  20562. "\r\n"
  20563. "hello");
  20564. auto port = port_future.get();
  20565. ASSERT_GT(port, 0);
  20566. Client cli("127.0.0.1", port);
  20567. auto handle = cli.open_stream("GET", "/");
  20568. EXPECT_FALSE(handle.is_valid());
  20569. server_thread.join();
  20570. }
  20571. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20572. #ifndef _WIN32
  20573. signal(SIGPIPE, SIG_IGN);
  20574. #endif
  20575. std::promise<int> port_promise;
  20576. auto port_future = port_promise.get_future();
  20577. auto server_thread = serve_single_response(
  20578. port_promise, "HTTP/1.1 200 OK\r\n"
  20579. "Content-Type: text/plain\r\n"
  20580. "Content-Length: 99999999999999999999999999\r\n"
  20581. "Connection: close\r\n"
  20582. "\r\n"
  20583. "hello");
  20584. auto port = port_future.get();
  20585. ASSERT_GT(port, 0);
  20586. // Historically std::stoull would throw std::out_of_range here and crash
  20587. // the process, then parsing silently clamped to a bogus framing length and
  20588. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20589. // so the stream fails to open, matching the not-a-number case above. The
  20590. // process still must NOT terminate.
  20591. Client cli("127.0.0.1", port);
  20592. auto handle = cli.open_stream("GET", "/");
  20593. EXPECT_FALSE(handle.is_valid());
  20594. server_thread.join();
  20595. }
  20596. #ifndef _WIN32
  20597. // As above for the body of a streamed request: a send() cut short by the write
  20598. // timeout must not leave the rest of the body unsent.
  20599. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20600. signal(SIGPIPE, SIG_IGN);
  20601. Server svr;
  20602. svr.set_socket_options([](socket_t sock) {
  20603. int size = 8192;
  20604. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20605. reinterpret_cast<const char *>(&size), sizeof(size));
  20606. });
  20607. svr.Post("/size", [](const Request &, Response &res,
  20608. const ContentReader &content_reader) {
  20609. // Outlast the client's write timeout before reading the body.
  20610. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20611. size_t received = 0;
  20612. content_reader([&](const char *, size_t len) {
  20613. received += len;
  20614. return true;
  20615. });
  20616. res.set_content(std::to_string(received), "text/plain");
  20617. });
  20618. auto port = svr.bind_to_any_port(HOST);
  20619. std::thread t([&]() { svr.listen_after_bind(); });
  20620. auto se = detail::scope_exit([&] {
  20621. svr.stop();
  20622. t.join();
  20623. });
  20624. svr.wait_until_ready();
  20625. Client cli(HOST, port);
  20626. cli.set_write_timeout(0, 500000);
  20627. cli.set_socket_options([](socket_t sock) {
  20628. int size = 8192;
  20629. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20630. reinterpret_cast<const char *>(&size), sizeof(size));
  20631. });
  20632. const std::string body(4 * 1024 * 1024, 'A');
  20633. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20634. "application/octet-stream");
  20635. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20636. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20637. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20638. }
  20639. #endif
  20640. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  20641. std::promise<void> slow_started;
  20642. auto slow_started_future = slow_started.get_future();
  20643. Server svr;
  20644. svr.Get("/slow", [&](const Request &, Response &res) {
  20645. slow_started.set_value();
  20646. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20647. res.set_content("slow", "text/plain");
  20648. });
  20649. svr.Get("/fast", [](const Request &, Response &res) {
  20650. res.set_content("fast", "text/plain");
  20651. });
  20652. auto port = svr.bind_to_any_port(HOST);
  20653. std::thread t([&]() { svr.listen_after_bind(); });
  20654. auto se = detail::scope_exit([&] {
  20655. svr.stop();
  20656. t.join();
  20657. });
  20658. svr.wait_until_ready();
  20659. Client cli(HOST, port);
  20660. std::string slow_body;
  20661. std::thread slow_thread([&] {
  20662. auto res = cli.Get("/slow");
  20663. if (res) { slow_body = res->body; }
  20664. });
  20665. slow_started_future.wait();
  20666. auto result = stream::Get(cli, "/fast");
  20667. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  20668. slow_thread.join();
  20669. EXPECT_EQ("slow", slow_body);
  20670. EXPECT_EQ("fast", fast_body);
  20671. }
  20672. // Serves `response` to the single request `fn` makes with a fresh client.
  20673. template <typename Fn>
  20674. static void with_single_response(const std::string &response, Fn fn) {
  20675. #ifndef _WIN32
  20676. signal(SIGPIPE, SIG_IGN);
  20677. #endif
  20678. std::promise<int> port_promise;
  20679. auto port_future = port_promise.get_future();
  20680. auto server_thread = serve_single_response(port_promise, response);
  20681. auto se = detail::scope_exit([&] { server_thread.join(); });
  20682. auto port = port_future.get();
  20683. ASSERT_GT(port, 0);
  20684. Client cli("127.0.0.1", port);
  20685. fn(cli);
  20686. }
  20687. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20688. // too, also in a build without the decoder for the advertised coding.
  20689. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20690. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20691. const auto response = "HTTP/1.1 200 OK\r\n"
  20692. "Content-Encoding: gzip\r\n"
  20693. "Content-Length: " +
  20694. std::to_string(gzipped.size()) +
  20695. "\r\n"
  20696. "Connection: close\r\n\r\n" +
  20697. gzipped;
  20698. with_single_response(response, [&](Client &cli) {
  20699. cli.set_decompress(false);
  20700. auto handle = cli.open_stream("GET", "/");
  20701. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20702. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20703. EXPECT_EQ(gzipped, read_all(handle));
  20704. EXPECT_FALSE(handle.has_read_error());
  20705. });
  20706. with_single_response(response, [&](Client &cli) {
  20707. cli.set_decompress(false);
  20708. auto res = stream::Get(cli, "/", 7);
  20709. ASSERT_TRUE(res) << to_string(res.error());
  20710. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20711. EXPECT_EQ(gzipped, res.read_all());
  20712. EXPECT_FALSE(res.has_read_error());
  20713. });
  20714. }
  20715. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20716. // Neither Content-Length nor chunked: the body ends at the close
  20717. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20718. "Connection: close\r\n"
  20719. "\r\n"
  20720. "hello";
  20721. with_single_response(close_delimited, [](Client &cli) {
  20722. auto handle = cli.open_stream("GET", "/");
  20723. ASSERT_TRUE(handle.is_valid());
  20724. EXPECT_EQ("hello", read_all(handle));
  20725. EXPECT_FALSE(handle.has_read_error());
  20726. });
  20727. // A close before the end of the Content-Length is still an error
  20728. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20729. "Content-Length: 10\r\n"
  20730. "\r\n"
  20731. "hello";
  20732. with_single_response(short_content_length, [](Client &cli) {
  20733. auto handle = cli.open_stream("GET", "/");
  20734. ASSERT_TRUE(handle.is_valid());
  20735. read_all(handle);
  20736. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20737. });
  20738. // So is a close before the last chunk
  20739. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20740. "Transfer-Encoding: chunked\r\n"
  20741. "\r\n"
  20742. "5\r\nhello\r\n";
  20743. with_single_response(short_chunked, [](Client &cli) {
  20744. auto handle = cli.open_stream("GET", "/");
  20745. ASSERT_TRUE(handle.is_valid());
  20746. read_all(handle);
  20747. EXPECT_TRUE(handle.has_read_error());
  20748. });
  20749. }
  20750. #ifdef CPPHTTPLIB_SSL_ENABLED
  20751. // Serves `response` to one request, then closes with or without a close_notify
  20752. template <typename Fn>
  20753. static void with_single_tls_response(const std::string &response,
  20754. bool close_notify, Fn fn) {
  20755. #ifndef _WIN32
  20756. signal(SIGPIPE, SIG_IGN);
  20757. #endif
  20758. std::promise<int> port_promise;
  20759. auto port_future = port_promise.get_future();
  20760. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20761. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20762. default_socket_options(srv);
  20763. sockaddr_in addr{};
  20764. addr.sin_family = AF_INET;
  20765. addr.sin_port = htons(0);
  20766. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20767. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20768. ::listen(srv, 1) != 0) {
  20769. port_promise.set_value(-1);
  20770. detail::close_socket(srv);
  20771. return;
  20772. }
  20773. socklen_t addr_len = sizeof(addr);
  20774. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20775. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20776. auto cli = ::accept(srv, nullptr, nullptr);
  20777. if (cli != INVALID_SOCKET) {
  20778. auto ctx = tls::create_server_context();
  20779. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20780. nullptr);
  20781. auto session = tls::create_session(ctx, cli);
  20782. tls::TlsError err;
  20783. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20784. // The request head first, so that closing the socket sends a FIN
  20785. // rather than an RST for the unread bytes.
  20786. std::string req;
  20787. char buf[256];
  20788. while (req.find("\r\n\r\n") == std::string::npos) {
  20789. auto n = tls::read(session, buf, sizeof(buf), err);
  20790. if (n <= 0) { break; }
  20791. req.append(buf, static_cast<size_t>(n));
  20792. }
  20793. size_t sent = 0;
  20794. while (sent < response.size()) {
  20795. auto n = tls::write(session, response.data() + sent,
  20796. response.size() - sent, err);
  20797. if (n <= 0) { break; }
  20798. sent += static_cast<size_t>(n);
  20799. }
  20800. if (close_notify) { tls::shutdown(session, true); }
  20801. }
  20802. tls::free_session(session);
  20803. detail::close_socket(cli);
  20804. tls::free_context(ctx);
  20805. }
  20806. detail::close_socket(srv);
  20807. });
  20808. auto se = detail::scope_exit([&] { server_thread.join(); });
  20809. auto port = port_future.get();
  20810. ASSERT_GT(port, 0);
  20811. SSLClient cli("127.0.0.1", port);
  20812. cli.enable_server_certificate_verification(false);
  20813. fn(cli);
  20814. }
  20815. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20816. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20817. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20818. "Connection: close\r\n"
  20819. "\r\n"
  20820. "hello";
  20821. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20822. auto res = cli.Get("/");
  20823. ASSERT_TRUE(res) << to_string(res.error());
  20824. EXPECT_EQ("hello", res->body);
  20825. });
  20826. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20827. auto res = cli.Get("/");
  20828. ASSERT_FALSE(res);
  20829. EXPECT_EQ(Error::Read, res.error());
  20830. });
  20831. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20832. auto handle = cli.open_stream("GET", "/");
  20833. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20834. read_all(handle);
  20835. EXPECT_TRUE(handle.has_read_error());
  20836. });
  20837. // A framed body ends where its framing says, with or without the alert
  20838. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20839. "Content-Length: 5\r\n"
  20840. "Connection: close\r\n"
  20841. "\r\n"
  20842. "hello";
  20843. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20844. auto res = cli.Get("/");
  20845. ASSERT_TRUE(res) << to_string(res.error());
  20846. EXPECT_EQ("hello", res->body);
  20847. });
  20848. }
  20849. #endif
  20850. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20851. const char *responses[] = {
  20852. "HTTP/1.1 103 Early Hints\r\n"
  20853. "Link: </style.css>; rel=preload\r\n"
  20854. "\r\n"
  20855. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20856. "HTTP/1.1 100 Continue\r\n"
  20857. "X-Note: interim\r\n"
  20858. "\r\n"
  20859. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20860. };
  20861. for (auto response : responses) {
  20862. with_single_response(response, [](Client &cli) {
  20863. auto res = cli.Get("/");
  20864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20865. EXPECT_EQ(StatusCode::OK_200, res->status);
  20866. EXPECT_EQ("ok", res->body);
  20867. });
  20868. }
  20869. }
  20870. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20871. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20872. const std::string final_response =
  20873. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20874. std::string interims;
  20875. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20876. interims += interim;
  20877. }
  20878. with_single_response(interims + final_response, [](Client &cli) {
  20879. auto res = cli.Get("/");
  20880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20881. EXPECT_EQ("ok", res->body);
  20882. });
  20883. with_single_response(interims + interim + final_response, [](Client &cli) {
  20884. auto res = cli.Get("/");
  20885. ASSERT_FALSE(res);
  20886. EXPECT_EQ(Error::Read, res.error());
  20887. });
  20888. }
  20889. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20890. #ifndef _WIN32
  20891. signal(SIGPIPE, SIG_IGN);
  20892. #endif
  20893. // The server answers the head without asking for the body. Bytes it then
  20894. // reads on the connection would be taken for the body the request declared.
  20895. auto closed_by_client = false;
  20896. std::promise<int> port_promise;
  20897. auto server_thread = serve_single_response(
  20898. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20899. [&](socket_t sock) {
  20900. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20901. char buf[256];
  20902. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20903. });
  20904. Client cli("127.0.0.1", port_promise.get_future().get());
  20905. cli.set_keep_alive(true);
  20906. cli.set_read_timeout(1, 0);
  20907. // Long enough for the client to send Expect: 100-continue.
  20908. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20910. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20911. cli.Get("/second");
  20912. server_thread.join();
  20913. EXPECT_TRUE(closed_by_client);
  20914. }
  20915. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20916. // Long enough for the client to send Expect: 100-continue
  20917. with_single_response(
  20918. "HTTP/1.1 103 Early Hints\r\n"
  20919. "Link: </style.css>; rel=preload\r\n"
  20920. "\r\n"
  20921. "HTTP/1.1 401 Unauthorized\r\n"
  20922. "Content-Length: 0\r\n\r\n",
  20923. [](Client &cli) {
  20924. cli.set_read_timeout(2, 0);
  20925. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20927. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20928. });
  20929. }
  20930. #ifdef CPPHTTPLIB_SSL_ENABLED
  20931. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20932. #ifndef _WIN32
  20933. signal(SIGPIPE, SIG_IGN);
  20934. #endif
  20935. auto reused = false;
  20936. std::promise<int> port_promise;
  20937. auto server_thread = serve_single_response(
  20938. port_promise,
  20939. "HTTP/1.1 401 Unauthorized\r\n"
  20940. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20941. "Content-Length: 0\r\n\r\n",
  20942. [&](socket_t sock) {
  20943. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20944. char buf[256];
  20945. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20946. });
  20947. Client cli("127.0.0.1", port_promise.get_future().get());
  20948. cli.set_keep_alive(true);
  20949. cli.set_digest_auth("user", "pass");
  20950. cli.set_read_timeout(1, 0);
  20951. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20952. server_thread.join();
  20953. EXPECT_FALSE(reused);
  20954. }
  20955. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20956. // Any other answer to CONNECT would read as the origin's response.
  20957. struct {
  20958. const char *response;
  20959. bool passed_on;
  20960. } cases[] = {
  20961. {"HTTP/1.1 201 Created\r\n"
  20962. "Set-Cookie: session=from-proxy\r\n"
  20963. "Content-Length: 0\r\n\r\n",
  20964. false},
  20965. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20966. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20967. "Content-Length: 0\r\n\r\n",
  20968. true},
  20969. };
  20970. for (const auto &c : cases) {
  20971. std::promise<int> port_promise;
  20972. auto server_thread = serve_single_response(port_promise, c.response);
  20973. SSLClient cli("example.com", 443);
  20974. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20975. auto res = cli.Get("/");
  20976. server_thread.join();
  20977. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20978. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20979. if (res) {
  20980. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20981. }
  20982. }
  20983. }
  20984. #endif
  20985. // Records the client's error logger calls as "error METHOD path", or
  20986. // "error null" for a call without a request
  20987. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20988. return [&log](const Error &err, const Request *req) {
  20989. log.push_back(to_string(err) + " " +
  20990. (req ? req->method + " " + req->path : "null"));
  20991. };
  20992. }
  20993. // A failed request is reported once, with the request the caller made
  20994. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20995. Server svr;
  20996. svr.Get("/big", [](const Request &, Response &res) {
  20997. res.set_content(std::string(100000, 'b'), "text/plain");
  20998. });
  20999. auto port = svr.bind_to_any_port(HOST);
  21000. std::thread t([&]() { svr.listen_after_bind(); });
  21001. auto se = detail::scope_exit([&] {
  21002. svr.stop();
  21003. t.join();
  21004. });
  21005. svr.wait_until_ready();
  21006. Client cli(HOST, port);
  21007. std::vector<std::string> log;
  21008. cli.set_error_logger(record_errors(log));
  21009. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21010. cli.Get("/big", [](const char *, size_t) { return false; });
  21011. EXPECT_EQ(expected, log);
  21012. log.clear();
  21013. cli.Get("/big", [](size_t, size_t) { return false; });
  21014. EXPECT_EQ(expected, log);
  21015. }
  21016. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21017. // Fails while the body is read
  21018. auto broken = [](const Request &, Response &res) {
  21019. res.set_content_provider(10, "text/plain",
  21020. [](size_t, size_t, DataSink &) { return false; });
  21021. };
  21022. Server other;
  21023. other.Get("/broken", broken);
  21024. auto other_port = other.bind_to_any_port(HOST);
  21025. std::thread other_t([&]() { other.listen_after_bind(); });
  21026. auto other_se = detail::scope_exit([&] {
  21027. other.stop();
  21028. other_t.join();
  21029. });
  21030. other.wait_until_ready();
  21031. Server svr;
  21032. svr.Get("/broken", broken);
  21033. svr.Get("/same-origin",
  21034. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21035. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21036. res.set_redirect("http://" + std::string(HOST) + ":" +
  21037. std::to_string(other_port) + "/broken");
  21038. });
  21039. auto port = svr.bind_to_any_port(HOST);
  21040. std::thread t([&]() { svr.listen_after_bind(); });
  21041. auto se = detail::scope_exit([&] {
  21042. svr.stop();
  21043. t.join();
  21044. });
  21045. svr.wait_until_ready();
  21046. Client cli(HOST, port);
  21047. cli.set_follow_location(true);
  21048. std::vector<std::string> log;
  21049. cli.set_error_logger(record_errors(log));
  21050. for (auto path : {"/same-origin", "/cross-origin"}) {
  21051. log.clear();
  21052. auto res = cli.Get(path);
  21053. ASSERT_FALSE(res);
  21054. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21055. log);
  21056. }
  21057. }
  21058. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21059. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21060. std::vector<std::string> log;
  21061. cli.set_error_logger(record_errors(log));
  21062. auto handle = cli.open_stream("GET", "/x");
  21063. EXPECT_FALSE(handle.is_valid());
  21064. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21065. log);
  21066. });
  21067. }
  21068. #ifdef CPPHTTPLIB_SSL_ENABLED
  21069. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21070. // Not a TLS server, so the handshake fails. It waits for a request line in
  21071. // the handshake bytes, so a short read timeout lets it close quickly.
  21072. Server svr;
  21073. svr.set_read_timeout(0, 100000);
  21074. svr.Get("/x", [](const Request &, Response &res) {
  21075. res.set_content("x", "text/plain");
  21076. });
  21077. auto port = svr.bind_to_any_port(HOST);
  21078. std::thread t([&]() { svr.listen_after_bind(); });
  21079. auto se = detail::scope_exit([&] {
  21080. svr.stop();
  21081. t.join();
  21082. });
  21083. svr.wait_until_ready();
  21084. std::vector<std::string> log;
  21085. SSLClient cli(HOST, port);
  21086. cli.enable_server_certificate_verification(false);
  21087. cli.set_error_logger(record_errors(log));
  21088. auto res = cli.Get("/x");
  21089. ASSERT_FALSE(res);
  21090. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21091. log.clear();
  21092. auto handle = cli.open_stream("GET", "/x");
  21093. EXPECT_FALSE(handle.is_valid());
  21094. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21095. log.clear();
  21096. SSLClient no_ca(HOST, port);
  21097. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21098. no_ca.set_error_logger(record_errors(log));
  21099. res = no_ca.Get("/x");
  21100. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21101. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21102. }
  21103. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21104. #ifndef _WIN32
  21105. signal(SIGPIPE, SIG_IGN);
  21106. #endif
  21107. // Refused, answered with a challenge, or closed without an answer
  21108. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21109. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21110. "Content-Length: 0\r\n\r\n",
  21111. ""}) {
  21112. std::promise<int> port_promise;
  21113. auto server_thread = serve_single_response(port_promise, response);
  21114. SSLClient cli("example.com", 443);
  21115. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21116. std::vector<std::string> log;
  21117. cli.set_error_logger(record_errors(log));
  21118. auto res = cli.Get("/");
  21119. server_thread.join();
  21120. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21121. << response;
  21122. }
  21123. }
  21124. #endif
  21125. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21126. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21127. // the chunked coding and drop Content-Length, so a front-end that trusts
  21128. // Content-Length would disagree about where the body ends (response
  21129. // smuggling). The client must reject such a response.
  21130. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21131. for (const char *te : {"chunked", "gzip, chunked"}) {
  21132. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21133. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21134. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21135. "5\r\nhello\r\n0\r\n\r\n";
  21136. with_single_response(response, [&](Client &cli) {
  21137. auto res = cli.Get("/");
  21138. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21139. EXPECT_EQ(Error::Read, res.error()) << te;
  21140. });
  21141. with_single_response(response, [&](Client &cli) {
  21142. auto handle = cli.open_stream("GET", "/");
  21143. EXPECT_FALSE(handle.is_valid()) << te;
  21144. EXPECT_EQ(Error::Read, handle.error) << te;
  21145. });
  21146. }
  21147. }
  21148. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21149. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21150. // closing the connection (unlike a request, which must be rejected).
  21151. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21152. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21153. "Transfer-Encoding: chunked\r\n"
  21154. "Connection: close\r\n"
  21155. "\r\n"
  21156. "5\r\nhello\r\n0\r\n\r\n",
  21157. "HTTP/1.1 200 OK\r\n"
  21158. "Transfer-Encoding: gzip\r\n"
  21159. "Connection: close\r\n"
  21160. "\r\n"
  21161. "hello"}) {
  21162. with_single_response(response, [&](Client &cli) {
  21163. auto res = cli.Get("/");
  21164. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21165. EXPECT_EQ("hello", res->body);
  21166. });
  21167. with_single_response(response, [&](Client &cli) {
  21168. auto handle = cli.open_stream("GET", "/");
  21169. ASSERT_TRUE(handle.is_valid()) << response;
  21170. EXPECT_EQ("hello", read_all(handle));
  21171. });
  21172. }
  21173. }
  21174. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21175. // framing headers describe nothing to read and must not be rejected.
  21176. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21177. const std::string framing = "Content-Length: 5\r\n"
  21178. "Transfer-Encoding: chunked\r\n"
  21179. "Connection: close\r\n"
  21180. "\r\n";
  21181. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21182. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21183. });
  21184. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21185. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21186. });
  21187. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21188. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21189. with_single_response(response, [&](Client &cli) {
  21190. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21191. });
  21192. with_single_response(response, [&](Client &cli) {
  21193. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21194. });
  21195. }
  21196. }
  21197. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21198. // header section, so a stream opened on one has nothing to read, whatever
  21199. // framing or coding headers it carries.
  21200. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21201. struct Case {
  21202. const char *method;
  21203. const char *status;
  21204. };
  21205. // A reader of the declared body reports an early close when nothing
  21206. // follows, and hands back what does.
  21207. struct Framing {
  21208. const char *headers;
  21209. const char *after;
  21210. };
  21211. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21212. Case{"GET", "304 Not Modified"}}) {
  21213. for (const auto &f :
  21214. {Framing{"Content-Length: 5\r\n", ""},
  21215. Framing{"Content-Length: 5\r\n", "hello"},
  21216. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21217. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21218. // Not decoded, so a build without Brotli opens it too
  21219. Framing{"Content-Encoding: br\r\n", ""}}) {
  21220. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21221. "Connection: close\r\n"
  21222. "\r\n" +
  21223. f.after;
  21224. with_single_response(response, [&](Client &cli) {
  21225. auto handle = cli.open_stream(c.method, "/");
  21226. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21227. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21228. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21229. });
  21230. }
  21231. }
  21232. }
  21233. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21234. // response, is faulty framing, so the connection is not reused after it.
  21235. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21236. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21237. "Content-Length: 0\r\n"
  21238. "Transfer-Encoding: chunked\r\n"
  21239. "\r\n"
  21240. "5\r\nhello\r\n0\r\n\r\n",
  21241. "HTTP/1.0 200 Connection established\r\n"
  21242. "Connection: keep-alive\r\n"
  21243. "Transfer-Encoding: chunked\r\n"
  21244. "\r\n"
  21245. "5\r\nhello\r\n0\r\n\r\n"}) {
  21246. with_single_response(response, [&](Client &cli) {
  21247. cli.set_keep_alive(true);
  21248. auto res = cli.Get("/");
  21249. ASSERT_TRUE(res) << response;
  21250. EXPECT_EQ("hello", res->body);
  21251. EXPECT_FALSE(cli.is_socket_open()) << response;
  21252. });
  21253. }
  21254. }
  21255. // A payload max length of 0 means no limit, however the body is framed.
  21256. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21257. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21258. "Transfer-Encoding: chunked\r\n"
  21259. "\r\n"
  21260. "5\r\nhello\r\n0\r\n\r\n",
  21261. "HTTP/1.1 200 OK\r\n"
  21262. "Connection: close\r\n"
  21263. "\r\n"
  21264. "hello"}) {
  21265. with_single_response(response, [&](Client &cli) {
  21266. cli.set_payload_max_length(0);
  21267. auto res = cli.Get("/");
  21268. ASSERT_TRUE(res) << response;
  21269. EXPECT_EQ("hello", res->body) << response;
  21270. });
  21271. }
  21272. }
  21273. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21274. Server svr;
  21275. svr.set_payload_max_length(0);
  21276. svr.Post("/echo", [](const Request &req, Response &res) {
  21277. res.set_content(req.body, "text/plain");
  21278. });
  21279. auto port = svr.bind_to_any_port(HOST);
  21280. thread t = thread([&] { svr.listen_after_bind(); });
  21281. auto se = detail::scope_exit([&] {
  21282. svr.stop();
  21283. t.join();
  21284. ASSERT_FALSE(svr.is_running());
  21285. });
  21286. svr.wait_until_ready();
  21287. Client cli(HOST, port);
  21288. auto res = cli.Post(
  21289. "/echo",
  21290. [](size_t /*offset*/, DataSink &sink) {
  21291. sink.write("hello", 5);
  21292. sink.done();
  21293. return true;
  21294. },
  21295. "text/plain");
  21296. ASSERT_TRUE(res);
  21297. EXPECT_EQ(StatusCode::OK_200, res->status);
  21298. EXPECT_EQ("hello", res->body);
  21299. }
  21300. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21301. TEST_F(OpenStreamTest, Gzip) {
  21302. Client cli("127.0.0.1", port_);
  21303. auto handle = cli.open_stream("GET", "/compressible", {},
  21304. {{"Accept-Encoding", "gzip"}});
  21305. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21306. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21307. }
  21308. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21309. Client cli("127.0.0.1", port_);
  21310. auto handle =
  21311. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21312. {{"Accept-Encoding", "gzip"}});
  21313. ASSERT_TRUE(handle.is_valid());
  21314. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21315. EXPECT_EQ("123456789", read_all(handle));
  21316. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21317. }
  21318. #endif
  21319. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21320. TEST_F(OpenStreamTest, Brotli) {
  21321. Client cli("127.0.0.1", port_);
  21322. auto handle =
  21323. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21324. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21325. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21326. }
  21327. #endif
  21328. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21329. TEST_F(OpenStreamTest, Zstd) {
  21330. Client cli("127.0.0.1", port_);
  21331. auto handle = cli.open_stream("GET", "/compressible", {},
  21332. {{"Accept-Encoding", "zstd"}});
  21333. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21334. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21335. }
  21336. #endif
  21337. #ifdef CPPHTTPLIB_SSL_ENABLED
  21338. class SSLOpenStreamTest : public ::testing::Test {
  21339. protected:
  21340. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21341. void SetUp() override {
  21342. svr_.Get("/hello", [](const Request &, Response &res) {
  21343. res.set_content("Hello SSL World!", "text/plain");
  21344. });
  21345. svr_.Get("/chunked", [](const Request &, Response &res) {
  21346. res.set_chunked_content_provider("text/plain",
  21347. [](size_t offset, DataSink &sink) {
  21348. if (offset < 15) {
  21349. sink.write("chunk", 5);
  21350. return true;
  21351. }
  21352. sink.done();
  21353. return true;
  21354. });
  21355. });
  21356. svr_.Post("/echo", [](const Request &req, Response &res) {
  21357. res.set_content(req.body, req.get_header_value("Content-Type"));
  21358. });
  21359. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21360. std::string body = req.body;
  21361. res.set_chunked_content_provider(
  21362. "text/plain", [body](size_t offset, DataSink &sink) {
  21363. if (offset < body.size()) {
  21364. sink.write(body.data() + offset, body.size() - offset);
  21365. }
  21366. sink.done();
  21367. return true;
  21368. });
  21369. });
  21370. port_ = svr_.bind_to_any_port("127.0.0.1");
  21371. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21372. svr_.wait_until_ready();
  21373. }
  21374. void TearDown() override {
  21375. svr_.stop();
  21376. if (thread_.joinable()) thread_.join();
  21377. }
  21378. SSLServer svr_;
  21379. std::thread thread_;
  21380. int port_ = 0;
  21381. };
  21382. TEST_F(SSLOpenStreamTest, Basic) {
  21383. SSLClient cli("127.0.0.1", port_);
  21384. cli.enable_server_certificate_verification(false);
  21385. auto handle = cli.open_stream("GET", "/hello");
  21386. ASSERT_TRUE(handle.is_valid());
  21387. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21388. }
  21389. TEST_F(SSLOpenStreamTest, Chunked) {
  21390. SSLClient cli("127.0.0.1", port_);
  21391. cli.enable_server_certificate_verification(false);
  21392. auto handle = cli.open_stream("GET", "/chunked");
  21393. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21394. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21395. "Transfer-Encoding") == "chunked");
  21396. auto body = read_all(handle);
  21397. EXPECT_EQ("chunkchunkchunk", body);
  21398. }
  21399. TEST_F(SSLOpenStreamTest, Post) {
  21400. SSLClient cli("127.0.0.1", port_);
  21401. cli.enable_server_certificate_verification(false);
  21402. auto handle =
  21403. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21404. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21405. EXPECT_EQ(200, handle.response->status);
  21406. auto body = read_all(handle);
  21407. EXPECT_EQ("Hello SSL POST", body);
  21408. }
  21409. TEST_F(SSLOpenStreamTest, PostChunked) {
  21410. SSLClient cli("127.0.0.1", port_);
  21411. cli.enable_server_certificate_verification(false);
  21412. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21413. "Chunked SSL Data", "text/plain");
  21414. ASSERT_TRUE(handle.is_valid());
  21415. EXPECT_EQ(200, handle.response->status);
  21416. auto body = read_all(handle);
  21417. EXPECT_EQ("Chunked SSL Data", body);
  21418. }
  21419. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21420. // Content-Length is terminated by the server closing the connection. When the
  21421. // SSL peer sends a close_notify after the body, the client must treat it as a
  21422. // clean EOF and return a successful response rather than an error.
  21423. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21425. ASSERT_TRUE(svr.is_valid());
  21426. svr.set_keep_alive_max_count(1);
  21427. const std::string expected_body = "Hello from connection-close response!";
  21428. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21429. res.set_content_provider("text/plain",
  21430. [&](size_t offset, DataSink &sink) -> bool {
  21431. if (offset < expected_body.size()) {
  21432. sink.write(expected_body.data() + offset,
  21433. expected_body.size() - offset);
  21434. }
  21435. sink.done();
  21436. return true;
  21437. });
  21438. });
  21439. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21440. auto se = detail::scope_exit([&] {
  21441. svr.stop();
  21442. listen_thread.join();
  21443. ASSERT_FALSE(svr.is_running());
  21444. });
  21445. svr.wait_until_ready();
  21446. SSLClient cli(HOST, PORT);
  21447. cli.enable_server_certificate_verification(false);
  21448. auto res = cli.Get("/no-content-length");
  21449. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21450. EXPECT_EQ(StatusCode::OK_200, res->status);
  21451. EXPECT_EQ(expected_body, res->body);
  21452. }
  21453. // Without Content-Length, the full buffer size reaches tls::read().
  21454. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21455. if (sizeof(size_t) <= sizeof(int)) {
  21456. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21457. }
  21458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21459. ASSERT_TRUE(svr.is_valid());
  21460. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21461. res.set_content_provider("text/plain",
  21462. [&](size_t offset, DataSink &sink) -> bool {
  21463. if (offset == 0) { sink.write("Hello", 5); }
  21464. sink.done();
  21465. return true;
  21466. });
  21467. });
  21468. auto port = svr.bind_to_any_port(HOST);
  21469. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21470. auto se = detail::scope_exit([&] {
  21471. svr.stop();
  21472. listen_thread.join();
  21473. });
  21474. svr.wait_until_ready();
  21475. SSLClient cli(HOST, port);
  21476. cli.enable_server_certificate_verification(false);
  21477. auto handle = cli.open_stream("GET", "/no-content-length");
  21478. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21479. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21480. std::unique_ptr<char[]> buf(new char[len]);
  21481. std::string body;
  21482. ssize_t n;
  21483. while ((n = handle.read(buf.get(), len)) > 0) {
  21484. body.append(buf.get(), static_cast<size_t>(n));
  21485. }
  21486. EXPECT_EQ(0, n);
  21487. EXPECT_EQ("Hello", body);
  21488. }
  21489. #endif // CPPHTTPLIB_SSL_ENABLED
  21490. //==============================================================================
  21491. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21492. // results for various scenarios.
  21493. //==============================================================================
  21494. TEST(ParityTest, GetVsOpenStream) {
  21495. Server svr;
  21496. const std::string path = "/parity";
  21497. const std::string content = "Parity test content: hello world";
  21498. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21499. res.set_content(content, "text/plain");
  21500. });
  21501. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21502. auto se = detail::scope_exit([&] {
  21503. svr.stop();
  21504. t.join();
  21505. ASSERT_FALSE(svr.is_running());
  21506. });
  21507. svr.wait_until_ready();
  21508. Client cli(HOST, PORT);
  21509. // Non-stream path
  21510. auto r1 = cli.Get(path);
  21511. ASSERT_TRUE(r1);
  21512. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21513. // Stream path
  21514. auto h = cli.open_stream("GET", path);
  21515. ASSERT_TRUE(h.is_valid());
  21516. EXPECT_EQ(r1->body, read_all(h));
  21517. }
  21518. // Helper to compress data with provided compressor type T
  21519. template <typename Compressor>
  21520. static std::string compress_payload_for_parity(const std::string &in) {
  21521. std::string out;
  21522. Compressor compressor;
  21523. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21524. [&](const char *data, size_t n) {
  21525. out.append(data, n);
  21526. return true;
  21527. });
  21528. EXPECT_TRUE(ok);
  21529. return out;
  21530. }
  21531. // Helper function for compression parity tests
  21532. template <typename Compressor>
  21533. static void test_compression_parity(const std::string &original,
  21534. const std::string &path,
  21535. const std::string &encoding) {
  21536. const std::string compressed =
  21537. compress_payload_for_parity<Compressor>(original);
  21538. Server svr;
  21539. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21540. res.set_content(compressed, "application/octet-stream");
  21541. res.set_header("Content-Encoding", encoding);
  21542. });
  21543. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21544. auto se = detail::scope_exit([&] {
  21545. svr.stop();
  21546. t.join();
  21547. ASSERT_FALSE(svr.is_running());
  21548. });
  21549. svr.wait_until_ready();
  21550. Client cli(HOST, PORT);
  21551. // Non-streaming
  21552. {
  21553. auto res = cli.Get(path);
  21554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21555. EXPECT_EQ(StatusCode::OK_200, res->status);
  21556. EXPECT_EQ(original, res->body);
  21557. }
  21558. // Streaming
  21559. {
  21560. auto h = cli.open_stream("GET", path);
  21561. ASSERT_TRUE(h.is_valid());
  21562. EXPECT_EQ(original, read_all(h));
  21563. }
  21564. }
  21565. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21566. TEST(ParityTest, Gzip) {
  21567. test_compression_parity<detail::gzip_compressor>(
  21568. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21569. }
  21570. #endif
  21571. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21572. TEST(ParityTest, Brotli) {
  21573. test_compression_parity<detail::brotli_compressor>(
  21574. "Hello, brotli parity test payload", "/parity-br", "br");
  21575. }
  21576. #endif
  21577. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21578. TEST(ParityTest, Zstd) {
  21579. test_compression_parity<detail::zstd_compressor>(
  21580. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21581. }
  21582. #endif
  21583. //==============================================================================
  21584. // New Stream API Tests
  21585. //==============================================================================
  21586. inline std::string read_body(httplib::stream::Result &result) {
  21587. std::string body;
  21588. while (result.next()) {
  21589. body.append(result.data(), result.size());
  21590. }
  21591. return body;
  21592. }
  21593. TEST(ClientConnectionTest, Basic) {
  21594. httplib::ClientConnection conn;
  21595. EXPECT_FALSE(conn.is_open());
  21596. conn.sock = 1;
  21597. EXPECT_TRUE(conn.is_open());
  21598. httplib::ClientConnection conn2(std::move(conn));
  21599. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21600. conn2.sock = INVALID_SOCKET;
  21601. }
  21602. // Unified test server for all stream::* tests
  21603. class StreamApiTest : public ::testing::Test {
  21604. protected:
  21605. void SetUp() override {
  21606. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21607. res.set_content("Hello World!", "text/plain");
  21608. });
  21609. svr_.Get("/echo-params",
  21610. [](const httplib::Request &req, httplib::Response &res) {
  21611. std::string r;
  21612. for (const auto &p : req.params) {
  21613. if (!r.empty()) r += "&";
  21614. r += p.first + "=" + p.second;
  21615. }
  21616. res.set_content(r, "text/plain");
  21617. });
  21618. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21619. res.set_content(req.body, req.get_header_value("Content-Type"));
  21620. });
  21621. svr_.Post("/echo-headers",
  21622. [](const httplib::Request &req, httplib::Response &res) {
  21623. std::string r;
  21624. for (const auto &h : req.headers)
  21625. r += h.first + ": " + h.second + "\n";
  21626. res.set_content(r, "text/plain");
  21627. });
  21628. svr_.Post("/echo-params",
  21629. [](const httplib::Request &req, httplib::Response &res) {
  21630. std::string r = "params:";
  21631. for (const auto &p : req.params)
  21632. r += p.first + "=" + p.second + ";";
  21633. res.set_content(r + " body:" + req.body, "text/plain");
  21634. });
  21635. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21636. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21637. });
  21638. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21639. res.set_content("PUT:" + req.body, "text/plain");
  21640. });
  21641. svr_.Patch("/echo",
  21642. [](const httplib::Request &req, httplib::Response &res) {
  21643. res.set_content("PATCH:" + req.body, "text/plain");
  21644. });
  21645. svr_.Delete(
  21646. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21647. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21648. "text/plain");
  21649. });
  21650. svr_.Get("/head-test",
  21651. [](const httplib::Request &, httplib::Response &res) {
  21652. res.set_content("body for HEAD", "text/plain");
  21653. });
  21654. svr_.Options("/options",
  21655. [](const httplib::Request &, httplib::Response &res) {
  21656. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21657. });
  21658. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21659. svr_.wait_until_ready();
  21660. }
  21661. void TearDown() override {
  21662. svr_.stop();
  21663. if (thread_.joinable()) thread_.join();
  21664. }
  21665. httplib::Server svr_;
  21666. std::thread thread_;
  21667. };
  21668. // stream::Get tests
  21669. TEST_F(StreamApiTest, GetBasic) {
  21670. httplib::Client cli(HOST, PORT);
  21671. auto result = httplib::stream::Get(cli, "/hello");
  21672. ASSERT_TRUE(result.is_valid());
  21673. EXPECT_EQ(200, result.status());
  21674. EXPECT_EQ("Hello World!", read_body(result));
  21675. }
  21676. TEST_F(StreamApiTest, GetWithParams) {
  21677. httplib::Client cli(HOST, PORT);
  21678. httplib::Params params{{"foo", "bar"}};
  21679. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21680. ASSERT_TRUE(result.is_valid());
  21681. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21682. }
  21683. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21684. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21685. httplib::Client cli(HOST, PORT);
  21686. cli.set_payload_max_length(0);
  21687. auto result = httplib::stream::Get(cli, "/hello");
  21688. ASSERT_TRUE(result.is_valid());
  21689. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21690. EXPECT_EQ("Hello World!", read_body(result));
  21691. }
  21692. #endif
  21693. TEST_F(StreamApiTest, GetConnectionError) {
  21694. httplib::Client cli(HOST, 9999);
  21695. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21696. }
  21697. TEST_F(StreamApiTest, Get404) {
  21698. httplib::Client cli(HOST, PORT);
  21699. auto result = httplib::stream::Get(cli, "/nonexistent");
  21700. EXPECT_TRUE(result.is_valid());
  21701. EXPECT_EQ(404, result.status());
  21702. }
  21703. // stream::Post tests
  21704. TEST_F(StreamApiTest, PostBasic) {
  21705. httplib::Client cli(HOST, PORT);
  21706. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21707. "application/json");
  21708. ASSERT_TRUE(result.is_valid());
  21709. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21710. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21711. }
  21712. TEST_F(StreamApiTest, PostWithHeaders) {
  21713. httplib::Client cli(HOST, PORT);
  21714. httplib::Headers headers{{"X-Custom", "value"}};
  21715. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21716. "text/plain");
  21717. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21718. }
  21719. TEST_F(StreamApiTest, PostWithParams) {
  21720. httplib::Client cli(HOST, PORT);
  21721. httplib::Params params{{"k", "v"}};
  21722. auto result =
  21723. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21724. auto body = read_body(result);
  21725. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21726. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21727. }
  21728. TEST_F(StreamApiTest, PostLarge) {
  21729. httplib::Client cli(HOST, PORT);
  21730. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21731. size_t total = 0;
  21732. while (result.next()) {
  21733. total += result.size();
  21734. }
  21735. EXPECT_EQ(100u * 1024u, total);
  21736. }
  21737. // stream::Put/Patch tests
  21738. TEST_F(StreamApiTest, PutAndPatch) {
  21739. httplib::Client cli(HOST, PORT);
  21740. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21741. EXPECT_EQ("PUT:test", read_body(put));
  21742. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21743. EXPECT_EQ("PATCH:test", read_body(patch));
  21744. }
  21745. // stream::Delete tests
  21746. TEST_F(StreamApiTest, Delete) {
  21747. httplib::Client cli(HOST, PORT);
  21748. auto del1 = httplib::stream::Delete(cli, "/resource");
  21749. EXPECT_EQ("Deleted", read_body(del1));
  21750. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21751. EXPECT_EQ("Deleted:data", read_body(del2));
  21752. }
  21753. // stream::Head/Options tests
  21754. TEST_F(StreamApiTest, HeadAndOptions) {
  21755. httplib::Client cli(HOST, PORT);
  21756. auto head = httplib::stream::Head(cli, "/head-test");
  21757. EXPECT_TRUE(head.is_valid());
  21758. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21759. auto opts = httplib::stream::Options(cli, "/options");
  21760. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21761. }
  21762. // SSL stream::* tests
  21763. #ifdef CPPHTTPLIB_SSL_ENABLED
  21764. class SSLStreamApiTest : public ::testing::Test {
  21765. protected:
  21766. void SetUp() override {
  21767. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21768. res.set_content("Hello SSL!", "text/plain");
  21769. });
  21770. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21771. res.set_content(req.body, "text/plain");
  21772. });
  21773. port_ = svr_.bind_to_any_port("127.0.0.1");
  21774. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21775. svr_.wait_until_ready();
  21776. }
  21777. void TearDown() override {
  21778. svr_.stop();
  21779. if (thread_.joinable()) thread_.join();
  21780. }
  21781. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21782. std::thread thread_;
  21783. int port_ = 0;
  21784. };
  21785. TEST_F(SSLStreamApiTest, GetAndPost) {
  21786. httplib::SSLClient cli("127.0.0.1", port_);
  21787. cli.enable_server_certificate_verification(false);
  21788. auto get = httplib::stream::Get(cli, "/hello");
  21789. EXPECT_EQ("Hello SSL!", read_body(get));
  21790. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21791. EXPECT_EQ("test", read_body(post));
  21792. }
  21793. #endif
  21794. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21795. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21796. // BodyReader
  21797. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21798. // Test that read timeout during streaming is detected
  21799. // Use a large content-length response where server delays mid-stream
  21800. Server svr;
  21801. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21802. // Send a large response with delay in the middle
  21803. res.set_content_provider(
  21804. 1000, // content_length
  21805. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21806. if (offset < 100) {
  21807. // Send first 100 bytes immediately
  21808. std::string data(100, 'A');
  21809. sink.write(data.c_str(), data.size());
  21810. return true;
  21811. }
  21812. // Then delay longer than client timeout
  21813. std::this_thread::sleep_for(std::chrono::seconds(3));
  21814. std::string data(900, 'B');
  21815. sink.write(data.c_str(), data.size());
  21816. return true;
  21817. });
  21818. });
  21819. auto port = 8091;
  21820. std::thread t([&]() { svr.listen("localhost", port); });
  21821. svr.wait_until_ready();
  21822. Client cli("localhost", port);
  21823. cli.set_read_timeout(1, 0); // 1 second timeout
  21824. auto handle = cli.open_stream("GET", "/slow-stream");
  21825. ASSERT_TRUE(handle.is_valid());
  21826. char buf[256];
  21827. ssize_t total = 0;
  21828. ssize_t n;
  21829. bool got_error = false;
  21830. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21831. total += n;
  21832. }
  21833. if (n < 0) {
  21834. got_error = true;
  21835. // Should be timeout or read error
  21836. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21837. handle.get_read_error() == Error::Read)
  21838. << "Actual error: " << to_string(handle.get_read_error());
  21839. }
  21840. // Either we got an error, or we got less data than expected
  21841. EXPECT_TRUE(got_error || total < 1000)
  21842. << "Expected timeout but got all " << total << " bytes";
  21843. svr.stop();
  21844. t.join();
  21845. }
  21846. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21847. // Test connection closed detection via BodyReader
  21848. Server svr;
  21849. std::atomic<bool> close_now{false};
  21850. svr.Get("/will-close", [&](const Request &, Response &res) {
  21851. res.set_content_provider(
  21852. 10000, // Large content_length that we won't fully send
  21853. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21854. if (offset < 100) {
  21855. std::string data(100, 'X');
  21856. sink.write(data.c_str(), data.size());
  21857. return true;
  21858. }
  21859. // Wait for signal then abort
  21860. while (!close_now) {
  21861. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21862. }
  21863. return false; // Abort - server will close connection
  21864. });
  21865. });
  21866. auto port = 8092;
  21867. std::thread t([&]() { svr.listen("localhost", port); });
  21868. svr.wait_until_ready();
  21869. Client cli("localhost", port);
  21870. auto handle = cli.open_stream("GET", "/will-close");
  21871. ASSERT_TRUE(handle.is_valid());
  21872. char buf[256];
  21873. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21874. EXPECT_GT(n, 0) << "First read should succeed";
  21875. // Signal server to close
  21876. close_now = true;
  21877. // Keep reading until error or EOF
  21878. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21879. // Keep reading
  21880. }
  21881. // Should get an error since content_length wasn't satisfied
  21882. if (n < 0) {
  21883. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21884. handle.get_read_error() == Error::Read)
  21885. << "Actual error: " << to_string(handle.get_read_error());
  21886. }
  21887. svr.stop();
  21888. t.join();
  21889. }
  21890. #ifdef CPPHTTPLIB_SSL_ENABLED
  21891. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21892. // Test that read timeout during SSL streaming is detected
  21893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21894. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21895. res.set_content_provider(
  21896. 1000, "text/plain",
  21897. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21898. if (offset < 100) {
  21899. std::string data(100, 'A');
  21900. sink.write(data.c_str(), data.size());
  21901. return true;
  21902. }
  21903. std::this_thread::sleep_for(std::chrono::seconds(3));
  21904. std::string data(900, 'B');
  21905. sink.write(data.c_str(), data.size());
  21906. return true;
  21907. });
  21908. });
  21909. auto port = 8093;
  21910. std::thread t([&]() { svr.listen("localhost", port); });
  21911. svr.wait_until_ready();
  21912. SSLClient cli("localhost", port);
  21913. cli.enable_server_certificate_verification(false);
  21914. cli.set_read_timeout(1, 0); // 1 second timeout
  21915. auto handle = cli.open_stream("GET", "/slow-stream");
  21916. ASSERT_TRUE(handle.is_valid());
  21917. char buf[256];
  21918. ssize_t total = 0;
  21919. ssize_t n;
  21920. bool got_error = false;
  21921. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21922. total += n;
  21923. }
  21924. if (n < 0) {
  21925. got_error = true;
  21926. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21927. handle.get_read_error() == Error::Read)
  21928. << "Actual error: " << to_string(handle.get_read_error());
  21929. }
  21930. EXPECT_TRUE(got_error || total < 1000)
  21931. << "Expected timeout but got all " << total << " bytes";
  21932. svr.stop();
  21933. t.join();
  21934. }
  21935. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21936. // Test SSL connection closed detection
  21937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21938. std::atomic<bool> close_now{false};
  21939. svr.Get("/will-close", [&](const Request &, Response &res) {
  21940. res.set_content_provider(
  21941. 10000, "text/plain",
  21942. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21943. if (offset < 100) {
  21944. std::string data(100, 'X');
  21945. sink.write(data.c_str(), data.size());
  21946. return true;
  21947. }
  21948. while (!close_now) {
  21949. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21950. }
  21951. return false;
  21952. });
  21953. });
  21954. auto port = 8094;
  21955. std::thread t([&]() { svr.listen("localhost", port); });
  21956. svr.wait_until_ready();
  21957. SSLClient cli("localhost", port);
  21958. cli.enable_server_certificate_verification(false);
  21959. auto handle = cli.open_stream("GET", "/will-close");
  21960. ASSERT_TRUE(handle.is_valid());
  21961. char buf[256];
  21962. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21963. EXPECT_GT(n, 0);
  21964. // Signal server to close
  21965. close_now = true;
  21966. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21967. // Keep reading
  21968. }
  21969. if (n < 0) {
  21970. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21971. handle.get_read_error() == Error::Read)
  21972. << "Actual error: " << to_string(handle.get_read_error());
  21973. }
  21974. svr.stop();
  21975. t.join();
  21976. }
  21977. #endif
  21978. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21979. using namespace httplib;
  21980. // Create a test file
  21981. const char *fname = "etag_testfile.txt";
  21982. const char *content = "etag-content";
  21983. {
  21984. std::ofstream ofs(fname);
  21985. ofs << content;
  21986. ASSERT_TRUE(ofs.good());
  21987. }
  21988. Server svr;
  21989. svr.set_mount_point("/static", ".");
  21990. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21991. svr.wait_until_ready();
  21992. Client cli(HOST, PORT);
  21993. // First request: should get 200 with ETag header
  21994. auto res1 = cli.Get("/static/etag_testfile.txt");
  21995. ASSERT_TRUE(res1);
  21996. ASSERT_EQ(200, res1->status);
  21997. ASSERT_TRUE(res1->has_header("ETag"));
  21998. std::string etag = res1->get_header_value("ETag");
  21999. EXPECT_FALSE(etag.empty());
  22000. // Verify ETag format: W/"hex-hex"
  22001. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22002. EXPECT_EQ('W', etag[0]);
  22003. EXPECT_EQ('/', etag[1]);
  22004. EXPECT_EQ('"', etag[2]);
  22005. EXPECT_EQ('"', etag.back());
  22006. // Exact match: expect 304 Not Modified
  22007. Headers h2 = {{"If-None-Match", etag}};
  22008. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22009. ASSERT_TRUE(res2);
  22010. EXPECT_EQ(304, res2->status);
  22011. // Wildcard match: expect 304 Not Modified
  22012. Headers h3 = {{"If-None-Match", "*"}};
  22013. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22014. ASSERT_TRUE(res3);
  22015. EXPECT_EQ(304, res3->status);
  22016. // Non-matching ETag: expect 200
  22017. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22018. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22019. ASSERT_TRUE(res4);
  22020. EXPECT_EQ(200, res4->status);
  22021. // Multiple ETags with one matching: expect 304
  22022. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22023. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22024. ASSERT_TRUE(res5);
  22025. EXPECT_EQ(304, res5->status);
  22026. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22027. // that equivalent to the single comma-separated list above, so the match on
  22028. // the second line must still be found.
  22029. Headers h6;
  22030. h6.emplace("If-None-Match", "W/\"other\"");
  22031. h6.emplace("If-None-Match", etag);
  22032. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22033. ASSERT_TRUE(res6);
  22034. EXPECT_EQ(304, res6->status);
  22035. svr.stop();
  22036. t.join();
  22037. std::remove(fname);
  22038. }
  22039. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22040. using namespace httplib;
  22041. Server svr;
  22042. svr.set_mount_point("/static", ".");
  22043. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22044. svr.wait_until_ready();
  22045. Client cli(HOST, PORT);
  22046. // Send If-None-Match: * to a non-existent file
  22047. Headers h = {{"If-None-Match", "*"}};
  22048. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22050. EXPECT_EQ(404, res->status);
  22051. svr.stop();
  22052. t.join();
  22053. }
  22054. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22055. using namespace httplib;
  22056. // Create a test file
  22057. const char *fname = "etag_boundary_testfile.txt";
  22058. const char *content = "boundary-test";
  22059. {
  22060. std::ofstream ofs(fname);
  22061. ofs << content;
  22062. ASSERT_TRUE(ofs.good());
  22063. }
  22064. Server svr;
  22065. svr.set_mount_point("/static", ".");
  22066. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22067. svr.wait_until_ready();
  22068. Client cli(HOST, PORT);
  22069. // Get the actual ETag
  22070. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22071. ASSERT_TRUE(res1);
  22072. ASSERT_EQ(200, res1->status);
  22073. ASSERT_TRUE(res1->has_header("ETag"));
  22074. std::string etag = res1->get_header_value("ETag");
  22075. // Test 1: Very long ETag value (longer than actual ETag)
  22076. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22077. Headers h1 = {{"If-None-Match", "W/"
  22078. "\"very-long-etag-value-that-is-much-longer-"
  22079. "than-the-actual-etag-value\""}};
  22080. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22081. ASSERT_TRUE(res2);
  22082. EXPECT_EQ(200, res2->status); // Should not match
  22083. // Test 2: Long string followed by wildcard
  22084. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22085. // string)
  22086. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22087. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22088. ASSERT_TRUE(res3);
  22089. EXPECT_EQ(304, res3->status); // Should match on "*"
  22090. // Test 3: Wildcard followed by long string
  22091. // Should match on "*" immediately and return 304
  22092. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22093. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22094. ASSERT_TRUE(res4);
  22095. EXPECT_EQ(304, res4->status); // Should match on "*"
  22096. // Test 4: Multiple long non-matching values
  22097. // Should NOT match and return 200 (test that all comparisons are safe)
  22098. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22099. "W/\"second-long-non-matching-value\", "
  22100. "W/\"third-long-non-matching-value\""}};
  22101. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22102. ASSERT_TRUE(res5);
  22103. EXPECT_EQ(200, res5->status); // Should not match
  22104. // Test 5: Single character that is not "*" (edge case)
  22105. Headers h5 = {{"If-None-Match", "X"}};
  22106. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22107. ASSERT_TRUE(res6);
  22108. EXPECT_EQ(200, res6->status); // Should not match
  22109. svr.stop();
  22110. t.join();
  22111. std::remove(fname);
  22112. }
  22113. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22114. using namespace httplib;
  22115. // Create a test file
  22116. const char *fname = "ims_testfile.txt";
  22117. const char *content = "if-modified-since-test";
  22118. {
  22119. std::ofstream ofs(fname);
  22120. ofs << content;
  22121. ASSERT_TRUE(ofs.good());
  22122. }
  22123. Server svr;
  22124. svr.set_mount_point("/static", ".");
  22125. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22126. svr.wait_until_ready();
  22127. Client cli(HOST, PORT);
  22128. // First request: should get 200 with Last-Modified header
  22129. auto res1 = cli.Get("/static/ims_testfile.txt");
  22130. ASSERT_TRUE(res1);
  22131. ASSERT_EQ(200, res1->status);
  22132. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22133. std::string last_modified = res1->get_header_value("Last-Modified");
  22134. EXPECT_FALSE(last_modified.empty());
  22135. // If-Modified-Since with same time: expect 304
  22136. Headers h2 = {{"If-Modified-Since", last_modified}};
  22137. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22138. ASSERT_TRUE(res2);
  22139. EXPECT_EQ(304, res2->status);
  22140. // If-Modified-Since with future time: expect 304
  22141. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22142. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22143. ASSERT_TRUE(res3);
  22144. EXPECT_EQ(304, res3->status);
  22145. // If-Modified-Since with past time: expect 200
  22146. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22147. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22148. ASSERT_TRUE(res4);
  22149. EXPECT_EQ(200, res4->status);
  22150. // If-None-Match takes precedence over If-Modified-Since
  22151. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22152. ASSERT_TRUE(res1->has_header("ETag"));
  22153. std::string etag = res1->get_header_value("ETag");
  22154. Headers h5 = {{"If-None-Match", etag},
  22155. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22156. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22157. ASSERT_TRUE(res5);
  22158. EXPECT_EQ(304, res5->status);
  22159. svr.stop();
  22160. t.join();
  22161. std::remove(fname);
  22162. }
  22163. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22164. using namespace httplib;
  22165. Server svr;
  22166. // Endpoint that returns compressible content
  22167. svr.Get("/compressible", [](const Request &, Response &res) {
  22168. // Return a large enough body to trigger compression
  22169. std::string body(1000, 'a');
  22170. res.set_content(body, "text/plain");
  22171. });
  22172. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22173. svr.wait_until_ready();
  22174. Client cli(HOST, PORT);
  22175. // Request with gzip support: should get Vary header when compressed
  22176. cli.set_compress(true);
  22177. auto res1 = cli.Get("/compressible");
  22178. ASSERT_TRUE(res1);
  22179. EXPECT_EQ(200, res1->status);
  22180. // If Content-Encoding is set, Vary should also be set
  22181. if (res1->has_header("Content-Encoding")) {
  22182. EXPECT_TRUE(res1->has_header("Vary"));
  22183. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22184. }
  22185. // Request without Accept-Encoding header: should not have compression
  22186. Headers h_no_compress;
  22187. auto res2 = cli.Get("/compressible", h_no_compress);
  22188. ASSERT_TRUE(res2);
  22189. EXPECT_EQ(200, res2->status);
  22190. // Verify Vary header is present when compression is applied
  22191. // (the exact behavior depends on server configuration)
  22192. svr.stop();
  22193. t.join();
  22194. }
  22195. TEST(ETagTest, IfRangeWithETag) {
  22196. using namespace httplib;
  22197. // Create a test file with known content
  22198. const char *fname = "if_range_testfile.txt";
  22199. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22200. {
  22201. std::ofstream ofs(fname);
  22202. ofs << content;
  22203. ASSERT_TRUE(ofs.good());
  22204. }
  22205. Server svr;
  22206. svr.set_mount_point("/static", ".");
  22207. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22208. svr.wait_until_ready();
  22209. Client cli(HOST, PORT);
  22210. // First request: get ETag
  22211. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22212. ASSERT_TRUE(res1);
  22213. ASSERT_EQ(200, res1->status);
  22214. ASSERT_TRUE(res1->has_header("ETag"));
  22215. std::string etag = res1->get_header_value("ETag");
  22216. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22217. // Since our server generates weak ETags (W/"..."), If-Range with our
  22218. // ETag should NOT result in partial content - it should return full content.
  22219. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22220. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22221. ASSERT_TRUE(res2);
  22222. // Weak ETag in If-Range -> full content (200), not partial (206)
  22223. EXPECT_EQ(200, res2->status);
  22224. EXPECT_EQ(content, res2->body);
  22225. EXPECT_FALSE(res2->has_header("Content-Range"));
  22226. // Range request with non-matching If-Range (ETag): should get 200 (full
  22227. // content)
  22228. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22229. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22230. ASSERT_TRUE(res3);
  22231. EXPECT_EQ(200, res3->status);
  22232. EXPECT_EQ(content, res3->body);
  22233. EXPECT_FALSE(res3->has_header("Content-Range"));
  22234. // Range request with strong ETag (hypothetical - our server doesn't generate
  22235. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22236. // should return full content)
  22237. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22238. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22239. ASSERT_TRUE(res4);
  22240. EXPECT_EQ(200, res4->status);
  22241. EXPECT_EQ(content, res4->body);
  22242. EXPECT_FALSE(res4->has_header("Content-Range"));
  22243. svr.stop();
  22244. t.join();
  22245. std::remove(fname);
  22246. }
  22247. TEST(ETagTest, IfRangeWithDate) {
  22248. using namespace httplib;
  22249. // Create a test file
  22250. const char *fname = "if_range_date_testfile.txt";
  22251. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22252. {
  22253. std::ofstream ofs(fname);
  22254. ofs << content;
  22255. ASSERT_TRUE(ofs.good());
  22256. }
  22257. Server svr;
  22258. svr.set_mount_point("/static", ".");
  22259. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22260. svr.wait_until_ready();
  22261. Client cli(HOST, PORT);
  22262. // First request: get Last-Modified
  22263. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22264. ASSERT_TRUE(res1);
  22265. ASSERT_EQ(200, res1->status);
  22266. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22267. std::string last_modified = res1->get_header_value("Last-Modified");
  22268. // Range request with matching If-Range (date): should get 206
  22269. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22270. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22271. ASSERT_TRUE(res2);
  22272. EXPECT_EQ(206, res2->status);
  22273. EXPECT_EQ("FGHIJ", res2->body);
  22274. // Range request with old If-Range date: should get 200 (full content)
  22275. Headers h3 = {{"Range", "bytes=5-9"},
  22276. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22277. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22278. ASSERT_TRUE(res3);
  22279. EXPECT_EQ(200, res3->status);
  22280. EXPECT_EQ(content, res3->body);
  22281. // Range request with future If-Range date: should get 206
  22282. Headers h4 = {{"Range", "bytes=0-4"},
  22283. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22284. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22285. ASSERT_TRUE(res4);
  22286. EXPECT_EQ(206, res4->status);
  22287. EXPECT_EQ("ABCDE", res4->body);
  22288. svr.stop();
  22289. t.join();
  22290. std::remove(fname);
  22291. }
  22292. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22293. using namespace httplib;
  22294. const char *fname = "etag_malformed.txt";
  22295. const char *content = "malformed-etag";
  22296. {
  22297. std::ofstream ofs(fname);
  22298. ofs << content;
  22299. ASSERT_TRUE(ofs.good());
  22300. }
  22301. Server svr;
  22302. svr.set_mount_point("/static", ".");
  22303. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22304. svr.wait_until_ready();
  22305. Client cli(HOST, PORT);
  22306. // baseline: should get 200 and an ETag
  22307. auto res1 = cli.Get("/static/etag_malformed.txt");
  22308. ASSERT_TRUE(res1);
  22309. ASSERT_EQ(200, res1->status);
  22310. ASSERT_TRUE(res1->has_header("ETag"));
  22311. // Malformed ETag value (missing quotes) should be treated as non-matching
  22312. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22313. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22314. ASSERT_TRUE(res_bad);
  22315. EXPECT_EQ(200, res_bad->status);
  22316. // Whitespace-only header value should be considered invalid / non-matching
  22317. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22318. "Host: localhost\r\n"
  22319. "If-None-Match: \r\n"
  22320. "Connection: close\r\n"
  22321. "\r\n";
  22322. std::string out;
  22323. ASSERT_TRUE(send_request(5, raw_req, &out));
  22324. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22325. svr.stop();
  22326. t.join();
  22327. std::remove(fname);
  22328. }
  22329. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22330. using namespace httplib;
  22331. const char *fname = "ims_invalid_format.txt";
  22332. const char *content = "ims-bad-format";
  22333. {
  22334. std::ofstream ofs(fname);
  22335. ofs << content;
  22336. ASSERT_TRUE(ofs.good());
  22337. }
  22338. Server svr;
  22339. svr.set_mount_point("/static", ".");
  22340. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22341. svr.wait_until_ready();
  22342. Client cli(HOST, PORT);
  22343. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22344. ASSERT_TRUE(res1);
  22345. ASSERT_EQ(200, res1->status);
  22346. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22347. // If-Modified-Since with invalid format should not result in 304
  22348. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22349. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22350. ASSERT_TRUE(res_bad);
  22351. EXPECT_EQ(200, res_bad->status);
  22352. // If-Range with invalid date format should be treated as mismatch -> full
  22353. // content (200)
  22354. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22355. {"If-Range", "invalid-date"}};
  22356. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22357. ASSERT_TRUE(res_ifrange);
  22358. EXPECT_EQ(200, res_ifrange->status);
  22359. svr.stop();
  22360. t.join();
  22361. std::remove(fname);
  22362. }
  22363. TEST(ETagTest, IfRangeWithMalformedETag) {
  22364. using namespace httplib;
  22365. const char *fname = "ifrange_malformed.txt";
  22366. const std::string content = "0123456789";
  22367. {
  22368. std::ofstream ofs(fname);
  22369. ofs << content;
  22370. ASSERT_TRUE(ofs.good());
  22371. }
  22372. Server svr;
  22373. svr.set_mount_point("/static", ".");
  22374. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22375. svr.wait_until_ready();
  22376. Client cli(HOST, PORT);
  22377. // First request: get ETag
  22378. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22379. ASSERT_TRUE(res1);
  22380. ASSERT_EQ(200, res1->status);
  22381. ASSERT_TRUE(res1->has_header("ETag"));
  22382. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22383. // full content (200)
  22384. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22385. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22386. ASSERT_TRUE(res2);
  22387. EXPECT_EQ(200, res2->status);
  22388. EXPECT_EQ(content, res2->body);
  22389. svr.stop();
  22390. t.join();
  22391. std::remove(fname);
  22392. }
  22393. TEST(ETagTest, ExtremeLargeDateValues) {
  22394. using namespace httplib;
  22395. const char *fname = "ims_extreme_date.txt";
  22396. const char *content = "ims-extreme-date";
  22397. {
  22398. std::ofstream ofs(fname);
  22399. ofs << content;
  22400. ASSERT_TRUE(ofs.good());
  22401. }
  22402. Server svr;
  22403. svr.set_mount_point("/static", ".");
  22404. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22405. svr.wait_until_ready();
  22406. Client cli(HOST, PORT);
  22407. auto res1 = cli.Get(std::string("/static/") + fname);
  22408. ASSERT_TRUE(res1);
  22409. ASSERT_EQ(200, res1->status);
  22410. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22411. // Extremely large year that may overflow date parsing routines.
  22412. Headers h_large_date = {
  22413. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22414. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22415. ASSERT_TRUE(res_bad);
  22416. // Expect server to treat this as invalid/mismatch and return full content
  22417. EXPECT_EQ(200, res_bad->status);
  22418. // If-Range with extremely large date should be treated as mismatch -> full
  22419. // content (200)
  22420. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22421. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22422. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22423. ASSERT_TRUE(res_ifrange);
  22424. EXPECT_EQ(200, res_ifrange->status);
  22425. svr.stop();
  22426. t.join();
  22427. std::remove(fname);
  22428. }
  22429. TEST(ETagTest, NegativeFileModificationTime) {
  22430. using namespace httplib;
  22431. const char *fname = "ims_negative_mtime.txt";
  22432. const std::string content = "negative-mtime";
  22433. {
  22434. std::ofstream ofs(fname);
  22435. ofs << content;
  22436. ASSERT_TRUE(ofs.good());
  22437. }
  22438. // Try to set file mtime to a negative value. This may fail on some
  22439. // platforms/filesystems; if it fails, the test will still verify server
  22440. // behaves safely by performing a regular conditional request.
  22441. #if defined(__APPLE__) || defined(__linux__)
  22442. bool set_negative = false;
  22443. do {
  22444. struct timeval times[2];
  22445. // access time: now
  22446. times[0].tv_sec = time(nullptr);
  22447. times[0].tv_usec = 0;
  22448. // modification time: negative (e.g., -1)
  22449. times[1].tv_sec = -1;
  22450. times[1].tv_usec = 0;
  22451. if (utimes(fname, times) == 0) { set_negative = true; }
  22452. } while (0);
  22453. #else
  22454. bool set_negative = false;
  22455. #endif
  22456. Server svr;
  22457. svr.set_mount_point("/static", ".");
  22458. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22459. svr.wait_until_ready();
  22460. Client cli(HOST, PORT);
  22461. auto res1 = cli.Get(std::string("/static/") + fname);
  22462. ASSERT_TRUE(res1);
  22463. ASSERT_EQ(200, res1->status);
  22464. bool has_last_modified = res1->has_header("Last-Modified");
  22465. std::string last_modified;
  22466. if (has_last_modified) {
  22467. last_modified = res1->get_header_value("Last-Modified");
  22468. }
  22469. if (set_negative) {
  22470. // If we successfully set a negative mtime, ensure server returns a
  22471. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22472. // with an old date and ensure server handles it without crash.
  22473. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22474. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22475. ASSERT_TRUE(res2);
  22476. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22477. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22478. } else {
  22479. // Could not set negative mtime on this platform; fall back to verifying
  22480. // that normal invalid/malformed dates are treated safely (non-304).
  22481. Headers h_bad_date = {
  22482. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22483. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22484. ASSERT_TRUE(res_bad);
  22485. EXPECT_EQ(200, res_bad->status);
  22486. }
  22487. svr.stop();
  22488. t.join();
  22489. std::remove(fname);
  22490. }
  22491. //==============================================================================
  22492. // Integration Tests with Server
  22493. //==============================================================================
  22494. class SSEIntegrationTest : public ::testing::Test {
  22495. protected:
  22496. void SetUp() override {
  22497. stop_server_.store(false);
  22498. events_.clear();
  22499. server_ = httplib::detail::make_unique<Server>();
  22500. setup_server();
  22501. start_server();
  22502. }
  22503. void TearDown() override {
  22504. stop_server_.store(true);
  22505. event_cv_.notify_all();
  22506. server_->stop();
  22507. if (server_thread_.joinable()) { server_thread_.join(); }
  22508. }
  22509. void setup_server() {
  22510. // Simple SSE endpoint
  22511. server_->Get("/events", [this](const Request &req, Response &res) {
  22512. auto last_id = req.get_header_value("Last-Event-ID");
  22513. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22514. res.set_chunked_content_provider(
  22515. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22516. std::unique_lock<std::mutex> lock(event_mutex_);
  22517. if (event_cv_.wait_for(
  22518. lock, std::chrono::milliseconds(200), [this] {
  22519. return !events_.empty() || stop_server_.load();
  22520. })) {
  22521. if (stop_server_.load()) { return false; }
  22522. if (!events_.empty()) {
  22523. std::string event = events_.front();
  22524. events_.erase(events_.begin());
  22525. sink.write(event.data(), event.size());
  22526. return true;
  22527. }
  22528. }
  22529. return !stop_server_.load();
  22530. });
  22531. });
  22532. // Endpoint that returns error
  22533. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22534. res.status = 500;
  22535. res.set_content("Internal Server Error", "text/plain");
  22536. });
  22537. // Endpoint for custom event types
  22538. server_->Get("/custom-events", [](const Request &, Response &res) {
  22539. res.set_chunked_content_provider(
  22540. "text/event-stream", [](size_t offset, DataSink &sink) {
  22541. if (offset == 0) {
  22542. std::string event = "event: update\ndata: updated\n\n"
  22543. "event: delete\ndata: deleted\n\n";
  22544. sink.write(event.data(), event.size());
  22545. }
  22546. return false; // End stream after sending
  22547. });
  22548. });
  22549. }
  22550. void start_server() {
  22551. port_ = server_->bind_to_any_port(HOST);
  22552. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22553. // Wait for server to start
  22554. while (!server_->is_running()) {
  22555. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22556. }
  22557. }
  22558. int get_port() const { return port_; }
  22559. void send_event(const std::string &event) {
  22560. std::lock_guard<std::mutex> lock(event_mutex_);
  22561. events_.push_back(event);
  22562. event_cv_.notify_all();
  22563. }
  22564. std::unique_ptr<Server> server_;
  22565. std::thread server_thread_;
  22566. std::mutex event_mutex_;
  22567. std::condition_variable event_cv_;
  22568. std::vector<std::string> events_;
  22569. std::atomic<bool> stop_server_{false};
  22570. std::string last_received_event_id_;
  22571. int port_ = 0;
  22572. };
  22573. //==============================================================================
  22574. // SSE Parser Tests
  22575. //==============================================================================
  22576. struct SSEParseResult {
  22577. std::vector<sse::SSEMessage> events;
  22578. std::vector<std::string> ids;
  22579. std::vector<int> retries;
  22580. bool ok = true;
  22581. std::string trace; // Every handler call in order
  22582. };
  22583. static SSEParseResult
  22584. sse_parse(const std::vector<std::string> &chunks,
  22585. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  22586. SSEParseResult r;
  22587. detail::SSEParser parser(
  22588. [&](const sse::SSEMessage &msg) {
  22589. r.events.push_back(msg);
  22590. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  22591. },
  22592. [&](const std::string &id) {
  22593. r.ids.push_back(id);
  22594. r.trace += "id[" + id + "]";
  22595. },
  22596. [&](int retry_ms) {
  22597. r.retries.push_back(retry_ms);
  22598. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  22599. },
  22600. max_event_length);
  22601. for (const auto &chunk : chunks) {
  22602. if (!parser.parse(chunk.data(), chunk.size())) {
  22603. r.ok = false;
  22604. break;
  22605. }
  22606. }
  22607. return r;
  22608. }
  22609. static SSEParseResult sse_parse(const std::string &stream) {
  22610. return sse_parse(std::vector<std::string>{stream});
  22611. }
  22612. TEST(SSEParserTest, SingleLineData) {
  22613. auto r = sse_parse("data: hello\n\n");
  22614. ASSERT_EQ(r.events.size(), 1u);
  22615. EXPECT_EQ(r.events[0].data, "hello");
  22616. EXPECT_EQ(r.events[0].event, "message");
  22617. }
  22618. TEST(SSEParserTest, MultiLineData) {
  22619. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  22620. ASSERT_EQ(r.events.size(), 1u);
  22621. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  22622. }
  22623. TEST(SSEParserTest, CustomEventType) {
  22624. auto r = sse_parse("event: update\ndata: payload\n\n");
  22625. ASSERT_EQ(r.events.size(), 1u);
  22626. EXPECT_EQ(r.events[0].event, "update");
  22627. EXPECT_EQ(r.events[0].data, "payload");
  22628. }
  22629. TEST(SSEParserTest, EventIdHandling) {
  22630. auto r = sse_parse("id: 12345\ndata: test\n\n");
  22631. ASSERT_EQ(r.events.size(), 1u);
  22632. EXPECT_EQ(r.events[0].id, "12345");
  22633. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  22634. }
  22635. TEST(SSEParserTest, EmptyEventId) {
  22636. auto r = sse_parse("id:\ndata: test\n\n");
  22637. ASSERT_EQ(r.events.size(), 1u);
  22638. EXPECT_EQ(r.events[0].id, "");
  22639. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  22640. }
  22641. TEST(SSEParserTest, CommentsIgnored) {
  22642. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  22643. ASSERT_EQ(r.events.size(), 1u);
  22644. EXPECT_EQ(r.events[0].data, "hello");
  22645. EXPECT_EQ(r.events[0].event, "message");
  22646. }
  22647. TEST(SSEParserTest, ColonInValue) {
  22648. auto r = sse_parse("data: hello:world:test\n\n");
  22649. ASSERT_EQ(r.events.size(), 1u);
  22650. EXPECT_EQ(r.events[0].data, "hello:world:test");
  22651. }
  22652. TEST(SSEParserTest, FieldNameOnly) {
  22653. // A line without a colon is a field name with an empty value
  22654. auto r = sse_parse("data\n\n");
  22655. ASSERT_EQ(r.events.size(), 1u);
  22656. EXPECT_EQ(r.events[0].data, "");
  22657. }
  22658. TEST(SSEParserTest, TrailingCarriageReturn) {
  22659. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  22660. ASSERT_EQ(r.events.size(), 1u);
  22661. EXPECT_EQ(r.events[0].event, "update");
  22662. EXPECT_EQ(r.events[0].data, "hello");
  22663. }
  22664. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  22665. auto r = sse_parse("data\r\n\r\n");
  22666. ASSERT_EQ(r.events.size(), 1u);
  22667. EXPECT_EQ(r.events[0].data, "");
  22668. }
  22669. TEST(SSEParserTest, CarriageReturnLineEnding) {
  22670. auto r = sse_parse("event: update\rdata: hello\r\r");
  22671. ASSERT_EQ(r.events.size(), 1u);
  22672. EXPECT_EQ(r.events[0].event, "update");
  22673. EXPECT_EQ(r.events[0].data, "hello");
  22674. }
  22675. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  22676. // Chunk boundaries fall inside every \r\n and right before the first one
  22677. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  22678. "\ndata: hello\r", "\n\r", "\n"});
  22679. ASSERT_EQ(r.events.size(), 1u);
  22680. EXPECT_EQ(r.events[0].event, "update");
  22681. EXPECT_EQ(r.events[0].data, "hello");
  22682. }
  22683. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  22684. // Only a BOM at the start of the stream is ignored
  22685. auto r = sse_parse("\xEF\xBB\xBF"
  22686. "data: first\n\n"
  22687. "\xEF\xBB\xBF"
  22688. "data: second\n\n");
  22689. ASSERT_EQ(r.events.size(), 1u);
  22690. EXPECT_EQ(r.events[0].data, "first");
  22691. }
  22692. TEST(SSEParserTest, UnknownFieldsIgnored) {
  22693. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  22694. ASSERT_EQ(r.events.size(), 1u);
  22695. EXPECT_EQ(r.events[0].data, "hello");
  22696. EXPECT_EQ(r.events[0].event, "message");
  22697. }
  22698. TEST(SSEParserTest, SpaceAfterColonOptional) {
  22699. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  22700. ASSERT_EQ(r.events.size(), 2u);
  22701. EXPECT_EQ(r.events[0].data, "hello");
  22702. EXPECT_EQ(r.events[1].data, "hello");
  22703. }
  22704. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  22705. // An event without data is not dispatched, and its type must not leak
  22706. // into the next event
  22707. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  22708. ASSERT_EQ(r.events.size(), 1u);
  22709. EXPECT_EQ(r.events[0].event, "message");
  22710. EXPECT_EQ(r.events[0].data, "hello");
  22711. }
  22712. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  22713. // Also when the empty field replaces an earlier type
  22714. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22715. ASSERT_EQ(r.events.size(), 2u);
  22716. EXPECT_EQ(r.events[0].event, "message");
  22717. EXPECT_EQ(r.events[1].event, "message");
  22718. }
  22719. TEST(SSEParserTest, EventWithoutDataReportsId) {
  22720. auto r = sse_parse("id: 42\n\n");
  22721. EXPECT_TRUE(r.events.empty());
  22722. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  22723. }
  22724. TEST(SSEParserTest, EmptyEventIdClearsId) {
  22725. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  22726. ASSERT_EQ(r.events.size(), 2u);
  22727. EXPECT_EQ(r.events[0].id, "1");
  22728. EXPECT_EQ(r.events[1].id, "");
  22729. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  22730. }
  22731. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  22732. // Ids that cannot be carried in a Last-Event-ID header
  22733. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  22734. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  22735. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  22736. }
  22737. TEST(SSEParserTest, RetryDigitsOnly) {
  22738. auto r = sse_parse("retry: 1000\n");
  22739. EXPECT_EQ(r.retries, std::vector<int>{1000});
  22740. // A value that is not all ASCII digits, or does not fit, is ignored
  22741. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  22742. EXPECT_TRUE(r.retries.empty());
  22743. }
  22744. TEST(SSEParserTest, CompleteEventParsing) {
  22745. auto r = sse_parse("event: notification\nid: evt-42\n"
  22746. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22747. ASSERT_EQ(r.events.size(), 1u);
  22748. EXPECT_EQ(r.events[0].event, "notification");
  22749. EXPECT_EQ(r.events[0].id, "evt-42");
  22750. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  22751. EXPECT_EQ(r.retries, std::vector<int>{1000});
  22752. }
  22753. TEST(SSEParserTest, IncompleteEventNotReported) {
  22754. // An event still waiting for its blank line when the stream ends is
  22755. // discarded per the SSE spec
  22756. auto r = sse_parse("id: 1\ndata: x\n");
  22757. EXPECT_TRUE(r.events.empty());
  22758. EXPECT_TRUE(r.ids.empty());
  22759. }
  22760. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  22761. const std::vector<std::string> streams = {
  22762. "\xEF\xBB\xBF"
  22763. "data: bom\r\n\r\n",
  22764. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  22765. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  22766. };
  22767. for (const auto &stream : streams) {
  22768. auto expected = sse_parse(stream).trace;
  22769. ASSERT_FALSE(expected.empty());
  22770. for (size_t i = 0; i <= stream.size(); i++) {
  22771. auto r = sse_parse(
  22772. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  22773. EXPECT_EQ(r.trace, expected) << "split at " << i;
  22774. }
  22775. std::vector<std::string> bytes;
  22776. for (auto c : stream) {
  22777. bytes.emplace_back(1, c);
  22778. }
  22779. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  22780. }
  22781. }
  22782. TEST(SSEParserTest, MaxEventLength) {
  22783. // A line still waiting for its end
  22784. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  22785. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  22786. // Data accumulated over the lines of one event
  22787. EXPECT_TRUE(
  22788. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  22789. EXPECT_FALSE(
  22790. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  22791. // 0 means no limit
  22792. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  22793. // Events completed in the same chunk are still reported
  22794. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  22795. EXPECT_FALSE(r.ok);
  22796. ASSERT_EQ(r.events.size(), 1u);
  22797. EXPECT_EQ(r.events[0].data, "a");
  22798. }
  22799. TEST(SSEMessageTest, Clear) {
  22800. sse::SSEMessage msg;
  22801. msg.event = "custom";
  22802. msg.data = "some data";
  22803. msg.id = "123";
  22804. msg.clear();
  22805. EXPECT_EQ(msg.event, "message");
  22806. EXPECT_EQ(msg.data, "");
  22807. EXPECT_EQ(msg.id, "");
  22808. }
  22809. //==============================================================================
  22810. // SSE Integration Tests
  22811. //==============================================================================
  22812. // Test: Successful connection and on_open callback
  22813. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22814. // Add a simple endpoint that sends one event and closes
  22815. server_->Get("/simple-event", [](const Request &, Response &res) {
  22816. res.set_chunked_content_provider(
  22817. "text/event-stream", [](size_t offset, DataSink &sink) {
  22818. if (offset == 0) {
  22819. std::string event = "data: hello\n\n";
  22820. sink.write(event.data(), event.size());
  22821. }
  22822. return false; // Close stream after sending
  22823. });
  22824. });
  22825. Client client("localhost", get_port());
  22826. sse::SSEClient sse(client, "/simple-event");
  22827. std::atomic<bool> open_called{false};
  22828. std::atomic<bool> message_received{false};
  22829. sse.on_open([&open_called]() { open_called.store(true); });
  22830. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22831. if (msg.data == "hello") { message_received.store(true); }
  22832. });
  22833. sse.set_reconnect_interval(100);
  22834. sse.set_max_reconnect_attempts(1);
  22835. // Start async
  22836. sse.start_async();
  22837. // Wait for message to be processed
  22838. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22839. sse.stop();
  22840. EXPECT_TRUE(open_called.load());
  22841. EXPECT_TRUE(message_received.load());
  22842. }
  22843. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22844. // A data line that never ends.
  22845. server_->Get("/endless-line", [](const Request &, Response &res) {
  22846. res.set_chunked_content_provider(
  22847. "text/event-stream", [](size_t offset, DataSink &sink) {
  22848. if (offset == 0) { sink.write("data: ", 6); }
  22849. std::string chunk(64 * 1024, 'A');
  22850. return sink.write(chunk.data(), chunk.size());
  22851. });
  22852. });
  22853. Client client("localhost", get_port());
  22854. sse::SSEClient sse(client, "/endless-line");
  22855. std::atomic<bool> too_long{false};
  22856. sse.on_error([&](Error err) {
  22857. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22858. });
  22859. sse.set_max_reconnect_attempts(1);
  22860. sse.start_async();
  22861. for (int i = 0; i < 500 && !too_long; i++) {
  22862. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22863. }
  22864. sse.stop();
  22865. EXPECT_TRUE(too_long);
  22866. }
  22867. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22868. // Far more in all than the client's payload limit below.
  22869. server_->Get("/many-events", [](const Request &, Response &res) {
  22870. res.set_chunked_content_provider(
  22871. "text/event-stream", [](size_t offset, DataSink &sink) {
  22872. if (offset == 0) {
  22873. std::string events;
  22874. for (int i = 0; i < 1000; i++) {
  22875. events += "data: message\n\n";
  22876. }
  22877. sink.write(events.data(), events.size());
  22878. }
  22879. return false;
  22880. });
  22881. });
  22882. Client client("localhost", get_port());
  22883. client.set_payload_max_length(1024);
  22884. sse::SSEClient sse(client, "/many-events");
  22885. std::atomic<int> messages{0};
  22886. std::atomic<bool> too_large{false};
  22887. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22888. sse.on_error([&](Error err) {
  22889. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22890. });
  22891. sse.set_max_reconnect_attempts(1);
  22892. sse.start_async();
  22893. for (int i = 0; i < 500 && messages < 1000; i++) {
  22894. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22895. }
  22896. sse.stop();
  22897. EXPECT_GE(messages.load(), 1000);
  22898. EXPECT_FALSE(too_large);
  22899. }
  22900. // Test: on_message callback
  22901. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22902. // Endpoint that sends multiple events then closes
  22903. server_->Get("/multi-event", [](const Request &, Response &res) {
  22904. res.set_chunked_content_provider(
  22905. "text/event-stream", [](size_t offset, DataSink &sink) {
  22906. if (offset == 0) {
  22907. std::string events = "data: message1\n\ndata: message2\n\n";
  22908. sink.write(events.data(), events.size());
  22909. }
  22910. return false;
  22911. });
  22912. });
  22913. Client client("localhost", get_port());
  22914. sse::SSEClient sse(client, "/multi-event");
  22915. std::vector<std::string> received_messages;
  22916. std::mutex messages_mutex;
  22917. sse.on_message([&](const sse::SSEMessage &msg) {
  22918. std::lock_guard<std::mutex> lock(messages_mutex);
  22919. received_messages.push_back(msg.data);
  22920. });
  22921. sse.set_reconnect_interval(100);
  22922. sse.set_max_reconnect_attempts(1);
  22923. sse.start_async();
  22924. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22925. sse.stop();
  22926. std::lock_guard<std::mutex> lock(messages_mutex);
  22927. EXPECT_GE(received_messages.size(), 2u);
  22928. if (received_messages.size() >= 2) {
  22929. EXPECT_EQ(received_messages[0], "message1");
  22930. EXPECT_EQ(received_messages[1], "message2");
  22931. }
  22932. }
  22933. // Test: on_event for specific types
  22934. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22935. Client client("localhost", get_port());
  22936. sse::SSEClient sse(client, "/custom-events");
  22937. std::atomic<bool> update_received{false};
  22938. std::atomic<bool> delete_received{false};
  22939. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22940. if (msg.data == "updated") { update_received.store(true); }
  22941. });
  22942. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22943. if (msg.data == "deleted") { delete_received.store(true); }
  22944. });
  22945. sse.set_max_reconnect_attempts(1);
  22946. sse.start_async();
  22947. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22948. sse.stop();
  22949. EXPECT_TRUE(update_received.load());
  22950. EXPECT_TRUE(delete_received.load());
  22951. }
  22952. // Test: on_error callback on connection failure
  22953. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22954. // Connect to a non-existent port
  22955. Client client("localhost", 59999);
  22956. sse::SSEClient sse(client, "/events");
  22957. std::atomic<bool> error_called{false};
  22958. Error received_error = Error::Success;
  22959. sse.on_error([&](Error err) {
  22960. error_called.store(true);
  22961. received_error = err;
  22962. });
  22963. sse.set_reconnect_interval(50);
  22964. sse.set_max_reconnect_attempts(1);
  22965. sse.start_async();
  22966. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22967. sse.stop();
  22968. EXPECT_TRUE(error_called.load());
  22969. EXPECT_NE(received_error, Error::Success);
  22970. }
  22971. // Test: Last-Event-ID header sent on reconnect
  22972. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22973. // Endpoint that sends event with ID
  22974. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22975. res.set_chunked_content_provider(
  22976. "text/event-stream", [](size_t offset, DataSink &sink) {
  22977. if (offset == 0) {
  22978. std::string event = "id: evt-123\ndata: test\n\n";
  22979. sink.write(event.data(), event.size());
  22980. }
  22981. return false;
  22982. });
  22983. });
  22984. Client client("localhost", get_port());
  22985. sse::SSEClient sse(client, "/event-with-id");
  22986. std::atomic<bool> id_received{false};
  22987. sse.on_message([&](const sse::SSEMessage &msg) {
  22988. if (!msg.id.empty()) { id_received.store(true); }
  22989. });
  22990. sse.set_reconnect_interval(100);
  22991. sse.set_max_reconnect_attempts(1);
  22992. sse.start_async();
  22993. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22994. sse.stop();
  22995. EXPECT_TRUE(id_received.load());
  22996. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22997. }
  22998. // Test: last_event_id() read from another thread while start_async() runs
  22999. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23000. // Ids of every length up to 200, so the stored id keeps changing size
  23001. server_->Get("/many-ids", [](const Request &, Response &res) {
  23002. res.set_chunked_content_provider(
  23003. "text/event-stream", [](size_t offset, DataSink &sink) {
  23004. if (offset == 0) {
  23005. std::string events;
  23006. for (size_t i = 0; i < 2000; i++) {
  23007. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23008. events += "data: x\n\n";
  23009. }
  23010. events += "id: end\ndata: x\n\n";
  23011. sink.write(events.data(), events.size());
  23012. }
  23013. return false;
  23014. });
  23015. });
  23016. Client client("localhost", get_port());
  23017. sse::SSEClient sse(client, "/many-ids");
  23018. // Wait out the rest of the test rather than replay the stream
  23019. sse.set_reconnect_interval(10000);
  23020. sse.set_max_reconnect_attempts(1);
  23021. sse.start_async();
  23022. auto well_formed = true;
  23023. std::string id;
  23024. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23025. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23026. id = sse.last_event_id();
  23027. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23028. well_formed = false;
  23029. }
  23030. }
  23031. sse.stop();
  23032. EXPECT_TRUE(well_formed);
  23033. EXPECT_EQ(sse.last_event_id(), "end");
  23034. }
  23035. // Test: Manual stop
  23036. TEST_F(SSEIntegrationTest, ManualStop) {
  23037. // Endpoint that sends one event and stays open briefly. The server outlives
  23038. // this test body, so the provider uses the fixture's flag, not a local.
  23039. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23040. res.set_chunked_content_provider(
  23041. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23042. if (offset == 0) {
  23043. std::string event = "data: connected\n\n";
  23044. sink.write(event.data(), event.size());
  23045. }
  23046. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23047. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23048. }
  23049. return false;
  23050. });
  23051. });
  23052. Client client("localhost", get_port());
  23053. sse::SSEClient sse(client, "/stay-open");
  23054. std::atomic<bool> connected{false};
  23055. sse.on_open([&connected]() { connected.store(true); });
  23056. sse.set_reconnect_interval(100);
  23057. sse.set_max_reconnect_attempts(1);
  23058. sse.start_async();
  23059. // Wait for connection to establish
  23060. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23061. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23062. }
  23063. EXPECT_TRUE(connected.load());
  23064. EXPECT_TRUE(sse.is_connected());
  23065. // Signal handler to stop
  23066. stop_server_.store(true);
  23067. // Stop SSE client
  23068. sse.stop();
  23069. EXPECT_FALSE(sse.is_connected());
  23070. }
  23071. // Sends one event, then nothing until stop is set
  23072. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23073. return [&stop](const Request &, Response &res) {
  23074. res.set_chunked_content_provider(
  23075. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23076. if (offset == 0) {
  23077. std::string event = "data: hello\n\n";
  23078. sink.write(event.data(), event.size());
  23079. }
  23080. while (!stop.load()) {
  23081. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23082. }
  23083. return false;
  23084. });
  23085. };
  23086. }
  23087. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23088. static void check_stop_interrupts_blocked_read(Client &client) {
  23089. client.set_read_timeout(30, 0);
  23090. for (auto by_destructor : {false, true}) {
  23091. std::atomic<bool> received{false};
  23092. std::chrono::steady_clock::time_point start;
  23093. {
  23094. sse::SSEClient sse(client, "/idle-stream");
  23095. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23096. sse.start_async();
  23097. for (int i = 0; i < 500 && !received.load(); ++i) {
  23098. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23099. }
  23100. ASSERT_TRUE(received.load());
  23101. // Let the client block in the next read
  23102. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23103. start = std::chrono::steady_clock::now();
  23104. if (!by_destructor) { sse.stop(); }
  23105. }
  23106. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23107. std::chrono::seconds(2));
  23108. }
  23109. }
  23110. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23111. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23112. Client client("localhost", get_port());
  23113. check_stop_interrupts_blocked_read(client);
  23114. }
  23115. #ifdef CPPHTTPLIB_SSL_ENABLED
  23116. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23118. std::atomic<bool> done{false};
  23119. svr.Get("/idle-stream", idle_event_stream(done));
  23120. auto port = svr.bind_to_any_port(HOST);
  23121. std::thread t([&] { svr.listen_after_bind(); });
  23122. auto se = detail::scope_exit([&] {
  23123. done.store(true);
  23124. svr.stop();
  23125. t.join();
  23126. });
  23127. svr.wait_until_ready();
  23128. Client client("https://localhost:" + std::to_string(port));
  23129. client.enable_server_certificate_verification(false);
  23130. check_stop_interrupts_blocked_read(client);
  23131. }
  23132. #endif
  23133. // Test: SSEClient with custom headers
  23134. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23135. // Setup a server endpoint that checks for custom header
  23136. std::atomic<bool> header_received{false};
  23137. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23138. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23139. header_received.store(true);
  23140. }
  23141. res.set_chunked_content_provider("text/event-stream",
  23142. [](size_t, DataSink &) { return false; });
  23143. });
  23144. Client client("localhost", get_port());
  23145. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23146. sse::SSEClient sse(client, "/header-check", headers);
  23147. sse.set_max_reconnect_attempts(1);
  23148. sse.start_async();
  23149. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23150. sse.stop();
  23151. EXPECT_TRUE(header_received.load());
  23152. }
  23153. // Test: Reconnect interval configuration
  23154. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23155. Client client("localhost", get_port());
  23156. sse::SSEClient sse(client, "/events");
  23157. auto &result = sse.set_reconnect_interval(500);
  23158. // Builder pattern should return reference to self
  23159. EXPECT_EQ(&result, &sse);
  23160. }
  23161. // Test: Max reconnect attempts
  23162. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23163. // Connect to non-existent port to force reconnects
  23164. Client client("localhost", 59998);
  23165. sse::SSEClient sse(client, "/events");
  23166. std::atomic<int> error_count{0};
  23167. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23168. sse.set_reconnect_interval(50);
  23169. sse.set_max_reconnect_attempts(2);
  23170. auto start = std::chrono::steady_clock::now();
  23171. sse.start(); // Blocking call
  23172. auto end = std::chrono::steady_clock::now();
  23173. // Should have stopped after 2 failed attempts
  23174. EXPECT_GE(error_count.load(), 2);
  23175. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23176. auto duration =
  23177. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23178. #ifdef _WIN32
  23179. // Windows is much slower for socket connection failures
  23180. EXPECT_LT(duration.count(), 7000);
  23181. #else
  23182. EXPECT_LT(duration.count(), 1000);
  23183. #endif
  23184. }
  23185. // Test: Multi-line data in integration
  23186. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23187. // Endpoint with multi-line data
  23188. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23189. res.set_chunked_content_provider(
  23190. "text/event-stream", [](size_t offset, DataSink &sink) {
  23191. if (offset == 0) {
  23192. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23193. sink.write(event.data(), event.size());
  23194. }
  23195. return false;
  23196. });
  23197. });
  23198. Client client("localhost", get_port());
  23199. sse::SSEClient sse(client, "/multiline-data");
  23200. std::string received_data;
  23201. std::mutex data_mutex;
  23202. sse.on_message([&](const sse::SSEMessage &msg) {
  23203. std::lock_guard<std::mutex> lock(data_mutex);
  23204. received_data = msg.data;
  23205. });
  23206. sse.set_reconnect_interval(100);
  23207. sse.set_max_reconnect_attempts(1);
  23208. sse.start_async();
  23209. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23210. sse.stop();
  23211. std::lock_guard<std::mutex> lock(data_mutex);
  23212. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23213. }
  23214. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23215. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23216. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23217. DataSink &sink) {
  23218. if (offset == 0) {
  23219. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23220. sink.write(events.data(), events.size());
  23221. }
  23222. return false;
  23223. });
  23224. });
  23225. Client client("localhost", get_port());
  23226. sse::SSEClient sse(client, "/empty-data-lines");
  23227. std::mutex mutex;
  23228. std::condition_variable cv;
  23229. std::vector<std::string> received;
  23230. sse.on_message([&](const sse::SSEMessage &msg) {
  23231. std::lock_guard<std::mutex> lock(mutex);
  23232. received.push_back(msg.data);
  23233. cv.notify_all();
  23234. });
  23235. sse.set_max_reconnect_attempts(1);
  23236. sse.start_async();
  23237. {
  23238. std::unique_lock<std::mutex> lock(mutex);
  23239. cv.wait_for(lock, std::chrono::seconds(2),
  23240. [&] { return received.size() >= 3; });
  23241. }
  23242. sse.stop();
  23243. ASSERT_GE(received.size(), 3u);
  23244. EXPECT_EQ(received[0], "");
  23245. EXPECT_EQ(received[1], "\nhello");
  23246. EXPECT_EQ(received[2], "");
  23247. }
  23248. // Test: Auto-reconnect after server disconnection
  23249. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23250. std::atomic<int> connection_count{0};
  23251. std::atomic<int> message_count{0};
  23252. // Endpoint that sends one event and closes, forcing reconnect
  23253. server_->Get("/reconnect-test",
  23254. [&connection_count](const Request &, Response &res) {
  23255. connection_count.fetch_add(1);
  23256. res.set_chunked_content_provider(
  23257. "text/event-stream", [](size_t offset, DataSink &sink) {
  23258. if (offset == 0) {
  23259. std::string event = "data: hello\n\n";
  23260. sink.write(event.data(), event.size());
  23261. }
  23262. return false; // Close connection after sending
  23263. });
  23264. });
  23265. Client client("localhost", get_port());
  23266. sse::SSEClient sse(client, "/reconnect-test");
  23267. sse.on_message([&message_count](const sse::SSEMessage &) {
  23268. message_count.fetch_add(1);
  23269. });
  23270. sse.set_reconnect_interval(100);
  23271. sse.set_max_reconnect_attempts(3);
  23272. sse.start_async();
  23273. // Wait long enough for multiple reconnects
  23274. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23275. sse.stop();
  23276. // Should have connected multiple times (initial + reconnects)
  23277. EXPECT_GE(connection_count.load(), 2);
  23278. // Should have received messages from multiple connections
  23279. EXPECT_GE(message_count.load(), 2);
  23280. }
  23281. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23282. std::atomic<int> connection_count{0};
  23283. // Neither Content-Length nor chunked: the close ends the stream
  23284. server_->Get("/close-delimited",
  23285. [&connection_count](const Request &, Response &res) {
  23286. connection_count.fetch_add(1);
  23287. res.set_content_provider(
  23288. "text/event-stream", [](size_t offset, DataSink &sink) {
  23289. if (offset == 0) {
  23290. std::string event = "data: hello\n\n";
  23291. sink.write(event.data(), event.size());
  23292. } else {
  23293. sink.done();
  23294. }
  23295. return true;
  23296. });
  23297. });
  23298. Client client("localhost", get_port());
  23299. sse::SSEClient sse(client, "/close-delimited");
  23300. std::atomic<int> error_count{0};
  23301. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23302. sse.set_reconnect_interval(100);
  23303. sse.start_async();
  23304. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23305. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23306. }
  23307. sse.stop();
  23308. // Reconnects as after any end of the stream, but reports no error
  23309. EXPECT_GE(connection_count.load(), 2);
  23310. EXPECT_EQ(0, error_count.load());
  23311. }
  23312. // Test: A retry field of all ASCII digits sets the reconnection time
  23313. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23314. std::mutex mutex;
  23315. std::condition_variable cv;
  23316. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23317. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23318. {
  23319. std::lock_guard<std::mutex> lock(mutex);
  23320. connected_at.push_back(std::chrono::steady_clock::now());
  23321. cv.notify_all();
  23322. }
  23323. res.set_chunked_content_provider(
  23324. "text/event-stream", [](size_t offset, DataSink &sink) {
  23325. if (offset == 0) {
  23326. std::string event = "retry: 0\ndata: hello\n\n";
  23327. sink.write(event.data(), event.size());
  23328. }
  23329. return false;
  23330. });
  23331. });
  23332. Client client("localhost", get_port());
  23333. sse::SSEClient sse(client, "/zero-retry");
  23334. sse.set_reconnect_interval(10000);
  23335. sse.start_async();
  23336. {
  23337. std::unique_lock<std::mutex> lock(mutex);
  23338. cv.wait_for(lock, std::chrono::seconds(5),
  23339. [&] { return connected_at.size() >= 2; });
  23340. }
  23341. sse.stop();
  23342. // The server-supplied interval is applied, but never below 100ms, so
  23343. // "retry: 0" does not cause a busy reconnect loop
  23344. std::lock_guard<std::mutex> lock(mutex);
  23345. ASSERT_GE(connected_at.size(), 2u);
  23346. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23347. connected_at[1] - connected_at[0])
  23348. .count();
  23349. EXPECT_GE(interval_ms, 100);
  23350. }
  23351. // Test: Last-Event-ID sent on reconnect
  23352. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23353. std::atomic<int> connection_count{0};
  23354. std::vector<std::string> received_last_event_ids;
  23355. std::mutex id_mutex;
  23356. // Endpoint that checks Last-Event-ID header and sends event with ID
  23357. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23358. int conn = connection_count.fetch_add(1);
  23359. // Capture the Last-Event-ID header from each connection
  23360. {
  23361. std::lock_guard<std::mutex> lock(id_mutex);
  23362. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23363. }
  23364. res.set_chunked_content_provider(
  23365. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23366. if (offset == 0) {
  23367. std::string event =
  23368. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23369. sink.write(event.data(), event.size());
  23370. }
  23371. return false;
  23372. });
  23373. });
  23374. Client client("localhost", get_port());
  23375. sse::SSEClient sse(client, "/reconnect-with-id");
  23376. sse.set_reconnect_interval(100);
  23377. sse.set_max_reconnect_attempts(3);
  23378. sse.start_async();
  23379. // Wait for at least 2 connections
  23380. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23381. sse.stop();
  23382. // Verify behavior
  23383. std::lock_guard<std::mutex> lock(id_mutex);
  23384. EXPECT_GE(received_last_event_ids.size(), 2u);
  23385. // First connection should have no Last-Event-ID
  23386. if (!received_last_event_ids.empty()) {
  23387. EXPECT_EQ(received_last_event_ids[0], "");
  23388. }
  23389. // Second connection should have Last-Event-ID from first connection
  23390. if (received_last_event_ids.size() >= 2) {
  23391. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23392. }
  23393. }
  23394. // Test: set_headers updates headers used on reconnect
  23395. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23396. std::vector<std::string> received_tokens;
  23397. std::mutex token_mutex;
  23398. // Endpoint that captures Authorization header
  23399. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23400. {
  23401. std::lock_guard<std::mutex> lock(token_mutex);
  23402. received_tokens.push_back(req.get_header_value("Authorization"));
  23403. }
  23404. res.set_chunked_content_provider(
  23405. "text/event-stream", [](size_t offset, DataSink &sink) {
  23406. if (offset == 0) {
  23407. std::string event = "data: hello\n\n";
  23408. sink.write(event.data(), event.size());
  23409. }
  23410. return false; // Close connection to trigger reconnect
  23411. });
  23412. });
  23413. Client client("localhost", get_port());
  23414. Headers headers = {{"Authorization", "Bearer old-token"}};
  23415. sse::SSEClient sse(client, "/auth-check", headers);
  23416. // Update headers on each successful connection
  23417. sse.on_open(
  23418. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23419. sse.set_reconnect_interval(100);
  23420. sse.set_max_reconnect_attempts(3);
  23421. sse.start_async();
  23422. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23423. sse.stop();
  23424. std::lock_guard<std::mutex> lock(token_mutex);
  23425. ASSERT_GE(received_tokens.size(), 2u);
  23426. // First connection uses original header
  23427. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23428. // Second connection uses updated header from set_headers
  23429. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23430. }
  23431. // Test: 401 allows reconnection (so on_error can refresh headers)
  23432. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23433. std::atomic<int> connection_count{0};
  23434. // Endpoint: returns 401 on first attempt, 200 on second
  23435. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23436. int conn = connection_count.fetch_add(1);
  23437. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23438. res.status = StatusCode::Unauthorized_401;
  23439. res.set_content("Unauthorized", "text/plain");
  23440. return;
  23441. }
  23442. res.set_chunked_content_provider(
  23443. "text/event-stream", [](size_t offset, DataSink &sink) {
  23444. if (offset == 0) {
  23445. std::string event = "data: authenticated\n\n";
  23446. sink.write(event.data(), event.size());
  23447. }
  23448. return false;
  23449. });
  23450. });
  23451. Client client("localhost", get_port());
  23452. Headers headers = {{"Authorization", "Bearer expired"}};
  23453. sse::SSEClient sse(client, "/auth-retry", headers);
  23454. std::atomic<bool> message_received{false};
  23455. // Refresh token on error
  23456. sse.on_error(
  23457. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23458. sse.on_message([&](const sse::SSEMessage &msg) {
  23459. if (msg.data == "authenticated") { message_received.store(true); }
  23460. });
  23461. sse.set_reconnect_interval(100);
  23462. sse.set_max_reconnect_attempts(3);
  23463. sse.start_async();
  23464. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23465. sse.stop();
  23466. // Should have reconnected after 401 and succeeded with new token
  23467. EXPECT_GE(connection_count.load(), 2);
  23468. EXPECT_TRUE(message_received.load());
  23469. }
  23470. TEST(Issue2318Test, EmptyHostString) {
  23471. {
  23472. httplib::Client cli_empty("", PORT);
  23473. auto res = cli_empty.Get("/");
  23474. ASSERT_FALSE(res);
  23475. EXPECT_EQ(httplib::Error::Connection, res.error());
  23476. }
  23477. {
  23478. httplib::Client cli(" ", PORT);
  23479. auto res = cli.Get("/");
  23480. ASSERT_FALSE(res);
  23481. EXPECT_EQ(httplib::Error::Connection, res.error());
  23482. }
  23483. }
  23484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23485. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23486. Server svr;
  23487. // Set a small payload limit (1KB)
  23488. svr.set_payload_max_length(1024);
  23489. svr.Post("/test", [&](const Request &req, Response &res) {
  23490. res.set_content("Body size: " + std::to_string(req.body.size()),
  23491. "text/plain");
  23492. });
  23493. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23494. auto se = detail::scope_exit([&] {
  23495. svr.stop();
  23496. listen_thread.join();
  23497. });
  23498. svr.wait_until_ready();
  23499. // Create data that compresses well but exceeds limit when decompressed
  23500. // 8KB of repeated null bytes compresses to a very small size
  23501. std::string original_data(8 * 1024, '\0');
  23502. // Compress the data using gzip
  23503. std::string compressed_data;
  23504. detail::gzip_compressor compressor;
  23505. compressor.compress(original_data.data(), original_data.size(), true,
  23506. [&](const char *data, size_t size) {
  23507. compressed_data.append(data, size);
  23508. return true;
  23509. });
  23510. // Verify compression worked (compressed should be much smaller)
  23511. ASSERT_LT(compressed_data.size(), original_data.size());
  23512. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23513. // Send compressed data with Content-Encoding: gzip
  23514. Client cli(HOST, PORT);
  23515. Headers headers = {{"Content-Encoding", "gzip"}};
  23516. auto res =
  23517. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23518. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23520. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23521. }
  23522. #endif
  23523. // ============================================================================
  23524. // OpenSSL-Specific Tests
  23525. // ============================================================================
  23526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23527. X509 *readCertificate(const std::string &strFileName) {
  23528. std::ifstream inStream(strFileName);
  23529. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23530. std::istreambuf_iterator<char>());
  23531. if (strCertPEM.empty()) return (nullptr);
  23532. BIO *pbCert = BIO_new(BIO_s_mem());
  23533. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23534. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23535. BIO_free(pbCert);
  23536. return (pCert);
  23537. }
  23538. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23539. std::ifstream inStream(strFileName);
  23540. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23541. std::istreambuf_iterator<char>());
  23542. if (strPrivateKeyPEM.empty()) return (nullptr);
  23543. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23544. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23545. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23546. BIO_free(pbPrivKey);
  23547. return (pPrivateKey);
  23548. }
  23549. TEST(BindServerTest, UpdateCerts) {
  23550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23551. int port = svr.bind_to_any_port("0.0.0.0");
  23552. ASSERT_TRUE(svr.is_valid());
  23553. ASSERT_TRUE(port > 0);
  23554. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23555. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23556. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23557. ASSERT_TRUE(cert != nullptr);
  23558. ASSERT_TRUE(ca_cert != nullptr);
  23559. ASSERT_TRUE(key != nullptr);
  23560. X509_STORE *cert_store = X509_STORE_new();
  23561. X509_STORE_add_cert(cert_store, ca_cert);
  23562. // svr.update_certs(cert, key, cert_store); // deprecated
  23563. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23564. CLIENT_CA_CERT_FILE);
  23565. ASSERT_TRUE(svr.is_valid());
  23566. svr.stop();
  23567. X509_STORE_free(cert_store);
  23568. X509_free(cert);
  23569. X509_free(ca_cert);
  23570. EVP_PKEY_free(key);
  23571. }
  23572. // Test that update_certs() updates client CA list correctly
  23573. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23574. // Start with file-based constructor
  23575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23576. ASSERT_TRUE(svr.is_valid());
  23577. // Initially no client CA list should be set
  23578. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23579. ASSERT_TRUE(ssl_ctx != nullptr);
  23580. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23581. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23582. // Now update with client CA (PEM string)
  23583. std::string cert_pem, key_pem, ca_pem;
  23584. read_file(SERVER_CERT_FILE, cert_pem);
  23585. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23586. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23587. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23588. ASSERT_TRUE(svr.is_valid());
  23589. // Now client CA list should be set
  23590. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23591. ASSERT_TRUE(ca_list_after != nullptr);
  23592. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23593. }
  23594. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23595. // Test that the file-path SSLServer constructor properly sets the client CA
  23596. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23598. ASSERT_TRUE(svr.is_valid());
  23599. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23600. ASSERT_TRUE(ssl_ctx != nullptr);
  23601. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23602. ASSERT_TRUE(ca_list != nullptr);
  23603. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23604. }
  23605. #endif
  23606. // ============================================================================
  23607. // MbedTLS-Specific Tests
  23608. // ============================================================================
  23609. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23610. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23611. using namespace httplib::tls;
  23612. // Track if callback was invoked
  23613. bool callback_invoked = false;
  23614. // The callback receives void* ctx which is actually MbedTlsContext*
  23615. // We can access the mbedtls_ssl_config via the context
  23616. auto setup_callback = [&callback_invoked](void *ctx) {
  23617. callback_invoked = true;
  23618. // Cast to MbedTlsContext* to access the ssl config
  23619. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23620. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23621. // Use static variables to hold certificate data (simplified for test)
  23622. static mbedtls_x509_crt own_cert;
  23623. static mbedtls_pk_context own_key;
  23624. static mbedtls_x509_crt ca_chain;
  23625. static bool initialized = false;
  23626. if (!initialized) {
  23627. mbedtls_x509_crt_init(&own_cert);
  23628. mbedtls_pk_init(&own_key);
  23629. mbedtls_x509_crt_init(&ca_chain);
  23630. // Load server certificate
  23631. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23632. return false;
  23633. }
  23634. // Load server private key.
  23635. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23636. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23637. #if MBEDTLS_VERSION_MAJOR == 3
  23638. ,
  23639. mbedtls_ctr_drbg_random, nullptr
  23640. #endif
  23641. ) != 0) {
  23642. return false;
  23643. }
  23644. // Load CA chain for client verification
  23645. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23646. return false;
  23647. }
  23648. initialized = true;
  23649. }
  23650. // Configure the SSL config
  23651. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23652. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23653. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23654. // Set minimum TLS version using mbedTLS native API
  23655. #if MBEDTLS_VERSION_MAJOR >= 3
  23656. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23657. #else
  23658. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23659. MBEDTLS_SSL_MINOR_VERSION_3);
  23660. #endif
  23661. return true;
  23662. };
  23663. SSLServer svr(setup_callback);
  23664. ASSERT_TRUE(svr.is_valid());
  23665. ASSERT_TRUE(callback_invoked);
  23666. svr.Get("/test", [&](const Request &req, Response &res) {
  23667. res.set_content("test", "text/plain");
  23668. auto cert = req.peer_cert();
  23669. ASSERT_TRUE(static_cast<bool>(cert));
  23670. auto common_name = cert.subject_cn();
  23671. EXPECT_EQ("Common Name", common_name);
  23672. });
  23673. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23674. auto se = detail::scope_exit([&] {
  23675. svr.stop();
  23676. t.join();
  23677. ASSERT_FALSE(svr.is_running());
  23678. });
  23679. svr.wait_until_ready();
  23680. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23681. cli.enable_server_certificate_verification(false);
  23682. cli.set_connection_timeout(30);
  23683. auto res = cli.Get("/test");
  23684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23685. ASSERT_EQ(StatusCode::OK_200, res->status);
  23686. }
  23687. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23688. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23689. // keep-alive SSL session, which reads through that config in
  23690. // mbedtls_ssl_close_notify.
  23691. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23693. ASSERT_TRUE(svr.is_valid());
  23694. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23695. res.set_content("test", "text/plain");
  23696. });
  23697. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23698. auto se = detail::scope_exit([&] {
  23699. svr.stop();
  23700. t.join();
  23701. ASSERT_FALSE(svr.is_running());
  23702. });
  23703. svr.wait_until_ready();
  23704. {
  23705. SSLClient cli(HOST, PORT);
  23706. cli.enable_server_certificate_verification(false);
  23707. cli.set_keep_alive(true);
  23708. auto res = cli.Get("/test");
  23709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23710. ASSERT_EQ(StatusCode::OK_200, res->status);
  23711. // cli is destructed here with the keep-alive SSL session still open.
  23712. }
  23713. }
  23714. #endif
  23715. // WebSocket Tests
  23716. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23717. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23718. // defining the meaning of these bits has been negotiated.
  23719. auto make_frame = [](uint8_t first_byte) {
  23720. std::string frame;
  23721. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23722. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23723. frame += "Hello";
  23724. return frame;
  23725. };
  23726. // RSV1 set (0x40)
  23727. {
  23728. detail::BufferStream strm;
  23729. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23730. ws::Opcode opcode;
  23731. std::string payload;
  23732. bool fin;
  23733. EXPECT_EQ(
  23734. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23735. ws::impl::FrameRead::Fail);
  23736. }
  23737. // RSV2 set (0x20)
  23738. {
  23739. detail::BufferStream strm;
  23740. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23741. ws::Opcode opcode;
  23742. std::string payload;
  23743. bool fin;
  23744. EXPECT_EQ(
  23745. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23746. ws::impl::FrameRead::Fail);
  23747. }
  23748. // RSV3 set (0x10)
  23749. {
  23750. detail::BufferStream strm;
  23751. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23752. ws::Opcode opcode;
  23753. std::string payload;
  23754. bool fin;
  23755. EXPECT_EQ(
  23756. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23757. ws::impl::FrameRead::Fail);
  23758. }
  23759. // No RSV bits set - should succeed
  23760. {
  23761. detail::BufferStream strm;
  23762. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23763. ws::Opcode opcode;
  23764. std::string payload;
  23765. bool fin;
  23766. EXPECT_EQ(
  23767. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23768. ws::impl::FrameRead::Ok);
  23769. EXPECT_EQ(ws::Opcode::Text, opcode);
  23770. EXPECT_EQ("Hello", payload);
  23771. EXPECT_TRUE(fin);
  23772. }
  23773. }
  23774. TEST(WebSocketTest, ControlFrameValidation) {
  23775. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23776. // payload length <= 125.
  23777. // Ping with FIN=0 - must be rejected
  23778. {
  23779. detail::BufferStream strm;
  23780. std::string frame;
  23781. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23782. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23783. strm.write(frame.data(), frame.size());
  23784. ws::Opcode opcode;
  23785. std::string payload;
  23786. bool fin;
  23787. EXPECT_EQ(
  23788. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23789. ws::impl::FrameRead::Fail);
  23790. }
  23791. // Close with FIN=0 - must be rejected
  23792. {
  23793. detail::BufferStream strm;
  23794. std::string frame;
  23795. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23796. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23797. strm.write(frame.data(), frame.size());
  23798. ws::Opcode opcode;
  23799. std::string payload;
  23800. bool fin;
  23801. EXPECT_EQ(
  23802. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23803. ws::impl::FrameRead::Fail);
  23804. }
  23805. // Ping with payload_len=126 (extended length) - must be rejected
  23806. {
  23807. detail::BufferStream strm;
  23808. std::string frame;
  23809. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23810. frame += static_cast<char>(126); // payload_len=126 (>125)
  23811. frame += static_cast<char>(0x00); // extended length high byte
  23812. frame += static_cast<char>(126); // extended length low byte
  23813. frame += std::string(126, 'x');
  23814. strm.write(frame.data(), frame.size());
  23815. ws::Opcode opcode;
  23816. std::string payload;
  23817. bool fin;
  23818. EXPECT_EQ(
  23819. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23820. ws::impl::FrameRead::Fail);
  23821. }
  23822. // Ping with FIN=1 and payload_len=125 - should succeed
  23823. {
  23824. detail::BufferStream strm;
  23825. std::string frame;
  23826. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23827. frame += static_cast<char>(125); // payload_len=125
  23828. frame += std::string(125, 'x');
  23829. strm.write(frame.data(), frame.size());
  23830. ws::Opcode opcode;
  23831. std::string payload;
  23832. bool fin;
  23833. EXPECT_EQ(
  23834. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23835. ws::impl::FrameRead::Ok);
  23836. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23837. EXPECT_EQ(125u, payload.size());
  23838. EXPECT_TRUE(fin);
  23839. }
  23840. }
  23841. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23842. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23843. // length MUST be 0.
  23844. // MSB set - must be rejected
  23845. {
  23846. detail::BufferStream strm;
  23847. std::string frame;
  23848. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23849. frame += static_cast<char>(127); // 64-bit extended length
  23850. frame += static_cast<char>(0x80); // MSB set (invalid)
  23851. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23852. strm.write(frame.data(), frame.size());
  23853. ws::Opcode opcode;
  23854. std::string payload;
  23855. bool fin;
  23856. EXPECT_EQ(
  23857. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23858. ws::impl::FrameRead::Fail);
  23859. }
  23860. // MSB clear - should pass length parsing (will be rejected by max_len,
  23861. // but that's a different check; use a small length to verify)
  23862. {
  23863. detail::BufferStream strm;
  23864. std::string frame;
  23865. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23866. frame += static_cast<char>(127); // 64-bit extended length
  23867. frame += std::string(7, '\0'); // high bytes = 0
  23868. frame += static_cast<char>(0x03); // length = 3
  23869. frame += "abc";
  23870. strm.write(frame.data(), frame.size());
  23871. ws::Opcode opcode;
  23872. std::string payload;
  23873. bool fin;
  23874. EXPECT_EQ(
  23875. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23876. ws::impl::FrameRead::Ok);
  23877. EXPECT_EQ(ws::Opcode::Text, opcode);
  23878. EXPECT_EQ("abc", payload);
  23879. }
  23880. }
  23881. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23882. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23883. // Valid UTF-8
  23884. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23885. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23886. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23887. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23888. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23889. // Invalid UTF-8
  23890. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23891. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23892. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23893. EXPECT_FALSE(
  23894. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23895. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23896. }
  23897. TEST(WebSocketTest, ConnectAndDisconnect) {
  23898. Server svr;
  23899. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23900. std::string msg;
  23901. while (ws.read(msg)) {}
  23902. });
  23903. auto port = svr.bind_to_any_port(HOST);
  23904. std::thread t([&]() { svr.listen_after_bind(); });
  23905. svr.wait_until_ready();
  23906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23907. auto res = client.connect();
  23908. ASSERT_TRUE(res);
  23909. EXPECT_EQ(Error::Success, res.error());
  23910. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23911. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23912. EXPECT_TRUE(client.is_open());
  23913. client.close();
  23914. EXPECT_FALSE(client.is_open());
  23915. svr.stop();
  23916. t.join();
  23917. }
  23918. TEST(WebSocketTest, ValidURL) {
  23919. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23920. EXPECT_TRUE(ws1.is_valid());
  23921. ws::WebSocketClient ws2("ws://example.com/path");
  23922. EXPECT_TRUE(ws2.is_valid());
  23923. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23924. EXPECT_TRUE(ws3.is_valid());
  23925. #ifdef CPPHTTPLIB_SSL_ENABLED
  23926. ws::WebSocketClient wss1("wss://example.com/path");
  23927. EXPECT_TRUE(wss1.is_valid());
  23928. ws::WebSocketClient wss2("wss://example.com:443/path");
  23929. EXPECT_TRUE(wss2.is_valid());
  23930. #endif
  23931. }
  23932. TEST(WebSocketTest, InvalidURL) {
  23933. // No scheme
  23934. ws::WebSocketClient ws1("localhost:8080/path");
  23935. EXPECT_FALSE(ws1.is_valid());
  23936. // No path
  23937. ws::WebSocketClient ws2("ws://localhost:8080");
  23938. EXPECT_FALSE(ws2.is_valid());
  23939. // Empty string
  23940. ws::WebSocketClient ws3("");
  23941. EXPECT_FALSE(ws3.is_valid());
  23942. // Missing host
  23943. ws::WebSocketClient ws4("ws://:8080/path");
  23944. EXPECT_FALSE(ws4.is_valid());
  23945. // Port number overflow — should not crash
  23946. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23947. EXPECT_FALSE(ws5.is_valid());
  23948. // Port out of range
  23949. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23950. EXPECT_FALSE(ws6.is_valid());
  23951. }
  23952. TEST(WebSocketTest, UnsupportedScheme) {
  23953. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23954. ws::WebSocketClient ws1("http://localhost:8080/path");
  23955. EXPECT_FALSE(ws1.is_valid());
  23956. ws::WebSocketClient ws2("https://localhost:8080/path");
  23957. EXPECT_FALSE(ws2.is_valid());
  23958. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23959. EXPECT_FALSE(ws3.is_valid());
  23960. #else
  23961. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23962. std::invalid_argument);
  23963. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23964. std::invalid_argument);
  23965. #endif
  23966. }
  23967. TEST(WebSocketTest, ConnectWhenInvalid) {
  23968. ws::WebSocketClient ws("not a valid url");
  23969. EXPECT_FALSE(ws.is_valid());
  23970. auto res = ws.connect();
  23971. EXPECT_FALSE(res);
  23972. EXPECT_EQ(Error::Connection, res.error());
  23973. EXPECT_EQ(-1, res.status());
  23974. }
  23975. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23976. // Grab a port that is free, then close it again so nothing listens there
  23977. Server svr;
  23978. auto port = svr.bind_to_any_port(HOST);
  23979. svr.stop();
  23980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23981. auto res = client.connect();
  23982. ASSERT_FALSE(res);
  23983. EXPECT_EQ(Error::Connection, res.error());
  23984. EXPECT_EQ(-1, res.status());
  23985. }
  23986. TEST(WebSocketTest, DefaultPort) {
  23987. ws::WebSocketClient ws1("ws://example.com/path");
  23988. EXPECT_TRUE(ws1.is_valid());
  23989. // ws:// defaults to port 80 (verified by successful parse)
  23990. #ifdef CPPHTTPLIB_SSL_ENABLED
  23991. ws::WebSocketClient ws2("wss://example.com/path");
  23992. EXPECT_TRUE(ws2.is_valid());
  23993. // wss:// defaults to port 443 (verified by successful parse)
  23994. #endif
  23995. }
  23996. TEST(WebSocketTest, IPv6LiteralAddress) {
  23997. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23998. EXPECT_TRUE(ws1.is_valid());
  23999. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24000. EXPECT_TRUE(ws2.is_valid());
  24001. }
  24002. TEST(WebSocketTest, ComplexPath) {
  24003. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24004. EXPECT_TRUE(ws1.is_valid());
  24005. ws::WebSocketClient ws2("ws://localhost:8080/");
  24006. EXPECT_TRUE(ws2.is_valid());
  24007. }
  24008. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24009. Server svr;
  24010. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24011. std::string msg;
  24012. while (ws.read(msg)) {}
  24013. });
  24014. auto port = svr.bind_to_any_port(HOST);
  24015. std::thread t([&]() { svr.listen_after_bind(); });
  24016. svr.wait_until_ready();
  24017. auto another_host = "example.com";
  24018. auto wrong_ip = "192.0.2.1";
  24019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24020. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24021. ASSERT_TRUE(client.connect());
  24022. EXPECT_TRUE(client.is_open());
  24023. client.close();
  24024. svr.stop();
  24025. t.join();
  24026. }
  24027. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24028. Server svr;
  24029. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24030. std::string msg;
  24031. while (ws.read(msg)) {}
  24032. });
  24033. auto port = svr.bind_to_any_port(HOST);
  24034. std::thread t([&]() { svr.listen_after_bind(); });
  24035. svr.wait_until_ready();
  24036. auto wrong_ip = "192.0.2.1";
  24037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24038. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24039. client.set_connection_timeout(1);
  24040. client.set_read_timeout(1);
  24041. client.set_write_timeout(1);
  24042. EXPECT_FALSE(client.connect());
  24043. EXPECT_FALSE(client.is_open());
  24044. svr.stop();
  24045. t.join();
  24046. }
  24047. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24048. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24049. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24050. // (RFC 6761) is only a map key and the Host header value.
  24051. auto host = "target.invalid";
  24052. Server svr;
  24053. std::string received_host;
  24054. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24055. received_host = req.get_header_value("Host");
  24056. std::string msg;
  24057. while (ws.read(msg)) {}
  24058. });
  24059. auto port = svr.bind_to_any_port(HOST);
  24060. std::thread t([&]() { svr.listen_after_bind(); });
  24061. // ASSERT_* below returns from the test body, which would leave t joinable
  24062. // and make ~thread call std::terminate.
  24063. auto se = detail::scope_exit([&] {
  24064. svr.stop();
  24065. if (t.joinable()) { t.join(); }
  24066. });
  24067. svr.wait_until_ready();
  24068. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24069. std::to_string(port) + "/ws");
  24070. client.set_direct_hostname_addr_map({{host, HOST}});
  24071. ASSERT_TRUE(client.connect());
  24072. EXPECT_TRUE(client.is_open());
  24073. client.close();
  24074. svr.stop();
  24075. t.join();
  24076. // The mapping only redirects the connection; the identity stays host_.
  24077. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24078. }
  24079. class WebSocketIntegrationTest : public ::testing::Test {
  24080. protected:
  24081. void SetUp() override {
  24082. server_ = httplib::detail::make_unique<Server>();
  24083. setup_server();
  24084. start_server();
  24085. }
  24086. void TearDown() override {
  24087. server_->stop();
  24088. if (server_thread_.joinable()) { server_thread_.join(); }
  24089. }
  24090. void setup_server() {
  24091. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24092. std::string msg;
  24093. ws::ReadResult ret;
  24094. while ((ret = ws.read(msg))) {
  24095. if (ret == ws::Binary) {
  24096. ws.send(msg.data(), msg.size());
  24097. } else {
  24098. ws.send(msg);
  24099. }
  24100. }
  24101. });
  24102. server_->WebSocket("/ws-echo-string",
  24103. [](const Request &, ws::WebSocket &ws) {
  24104. std::string msg;
  24105. while (ws.read(msg)) {
  24106. ws.send("echo: " + msg);
  24107. }
  24108. });
  24109. server_->WebSocket(
  24110. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24111. // Echo back request metadata
  24112. ws.send("path:" + req.path);
  24113. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24114. std::string msg;
  24115. while (ws.read(msg)) {}
  24116. });
  24117. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24118. std::string msg;
  24119. ws.read(msg); // wait for a message
  24120. ws.close();
  24121. });
  24122. server_->WebSocket("/ws-close-status",
  24123. [](const Request &, ws::WebSocket &ws) {
  24124. std::string msg;
  24125. ws.read(msg); // wait for a message
  24126. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24127. });
  24128. server_->WebSocket(
  24129. "/ws-subprotocol",
  24130. [](const Request &, ws::WebSocket &ws) {
  24131. std::string msg;
  24132. while (ws.read(msg)) {
  24133. ws.send(msg);
  24134. }
  24135. },
  24136. [](const std::vector<std::string> &protocols) -> std::string {
  24137. for (const auto &p : protocols) {
  24138. if (p == "graphql-ws") { return p; }
  24139. }
  24140. return "";
  24141. });
  24142. server_->WebSocket(
  24143. "/ws-subprotocol-unoffered",
  24144. [](const Request &, ws::WebSocket &ws) {
  24145. std::string msg;
  24146. while (ws.read(msg)) {
  24147. ws.send(msg);
  24148. }
  24149. },
  24150. [](const std::vector<std::string> &) -> std::string {
  24151. return "admin";
  24152. });
  24153. }
  24154. void start_server() {
  24155. port_ = server_->bind_to_any_port(HOST);
  24156. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24157. server_->wait_until_ready();
  24158. }
  24159. std::unique_ptr<Server> server_;
  24160. std::thread server_thread_;
  24161. int port_ = 0;
  24162. };
  24163. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24164. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24165. "/ws-echo");
  24166. ASSERT_TRUE(client.connect());
  24167. ASSERT_TRUE(client.is_open());
  24168. ASSERT_TRUE(client.send("Hello WebSocket"));
  24169. std::string msg;
  24170. EXPECT_EQ(ws::Text, client.read(msg));
  24171. EXPECT_EQ("Hello WebSocket", msg);
  24172. client.close();
  24173. }
  24174. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24175. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24176. "/ws-echo");
  24177. ASSERT_TRUE(client.connect());
  24178. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24179. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24180. std::string msg;
  24181. EXPECT_EQ(ws::Binary, client.read(msg));
  24182. EXPECT_EQ(binary_data, msg);
  24183. client.close();
  24184. }
  24185. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24187. "/ws-echo");
  24188. ASSERT_TRUE(client.connect());
  24189. for (int i = 0; i < 10; i++) {
  24190. auto text = "message " + std::to_string(i);
  24191. ASSERT_TRUE(client.send(text));
  24192. std::string msg;
  24193. ASSERT_TRUE(client.read(msg));
  24194. EXPECT_EQ(text, msg);
  24195. }
  24196. client.close();
  24197. }
  24198. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24199. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24200. "/ws-close");
  24201. ASSERT_TRUE(client.connect());
  24202. // Send a message to trigger the server to close
  24203. ASSERT_TRUE(client.send("trigger close"));
  24204. // The server will close, so read should return false
  24205. std::string msg;
  24206. EXPECT_FALSE(client.read(msg));
  24207. EXPECT_FALSE(client.is_open());
  24208. }
  24209. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24211. "/ws-echo");
  24212. ASSERT_TRUE(client.connect());
  24213. // 128KB message
  24214. std::string large_data(128 * 1024, 'X');
  24215. ASSERT_TRUE(client.send(large_data));
  24216. std::string msg;
  24217. ASSERT_TRUE(client.read(msg));
  24218. EXPECT_EQ(large_data, msg);
  24219. client.close();
  24220. }
  24221. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24222. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24223. "/ws-echo");
  24224. ASSERT_TRUE(client.connect());
  24225. const int num_threads = 4;
  24226. std::vector<std::thread> threads;
  24227. std::atomic<int> send_count{0};
  24228. for (int t = 0; t < num_threads; t++) {
  24229. threads.emplace_back([&client, &send_count, t]() {
  24230. for (int i = 0; i < 5; i++) {
  24231. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24232. if (client.send(text)) { send_count++; }
  24233. }
  24234. });
  24235. }
  24236. for (auto &th : threads) {
  24237. th.join();
  24238. }
  24239. int received = 0;
  24240. std::string msg;
  24241. while (received < send_count.load()) {
  24242. if (!client.read(msg)) { break; }
  24243. received++;
  24244. }
  24245. EXPECT_EQ(send_count.load(), received);
  24246. client.close();
  24247. }
  24248. TEST_F(WebSocketIntegrationTest, ReadString) {
  24249. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24250. "/ws-echo-string");
  24251. ASSERT_TRUE(client.connect());
  24252. ASSERT_TRUE(client.send("hello"));
  24253. std::string msg;
  24254. ASSERT_TRUE(client.read(msg));
  24255. EXPECT_EQ("echo: hello", msg);
  24256. ASSERT_TRUE(client.send("world"));
  24257. ASSERT_TRUE(client.read(msg));
  24258. EXPECT_EQ("echo: world", msg);
  24259. client.close();
  24260. }
  24261. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24262. Headers headers = {{"X-Test-Header", "test-value"}};
  24263. ws::WebSocketClient client(
  24264. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24265. ASSERT_TRUE(client.connect());
  24266. std::string msg;
  24267. ASSERT_TRUE(client.read(msg));
  24268. EXPECT_EQ("path:/ws-request-info", msg);
  24269. ASSERT_TRUE(client.read(msg));
  24270. EXPECT_EQ("header:test-value", msg);
  24271. client.close();
  24272. }
  24273. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24274. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24275. "/ws-echo");
  24276. client.set_read_timeout(1, 0); // 1 second
  24277. ASSERT_TRUE(client.connect());
  24278. // Don't send anything — server echo handler waits for a message, so read()
  24279. // should time out. The connection survives it: nothing was consumed.
  24280. std::string msg;
  24281. EXPECT_EQ(client.read(msg), ws::Timeout);
  24282. EXPECT_TRUE(client.is_open());
  24283. // And it is still usable afterwards.
  24284. EXPECT_TRUE(client.send("after timeout"));
  24285. EXPECT_EQ(client.read(msg), ws::Text);
  24286. EXPECT_EQ(msg, "after timeout");
  24287. }
  24288. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24289. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24290. "/ws-echo");
  24291. client.set_read_timeout(1, 0);
  24292. ASSERT_TRUE(client.connect());
  24293. ASSERT_TRUE(client.send("first"));
  24294. std::string msg;
  24295. ASSERT_EQ(client.read(msg), ws::Text);
  24296. ASSERT_EQ(msg, "first");
  24297. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24298. // not be used with a read timeout: it would reprocess the previous message.
  24299. EXPECT_EQ(client.read(msg), ws::Timeout);
  24300. EXPECT_EQ(msg, "first");
  24301. }
  24302. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24303. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24304. "/ws-echo");
  24305. ASSERT_TRUE(client.connect());
  24306. // Setting it once the connection is open reaches the live stream, not just
  24307. // the seed for the next connect().
  24308. client.set_read_timeout(1, 0);
  24309. std::string msg;
  24310. EXPECT_EQ(client.read(msg), ws::Timeout);
  24311. EXPECT_TRUE(client.is_open());
  24312. }
  24313. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24314. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24315. "/ws-echo");
  24316. client.set_read_timeout(5, 0);
  24317. ASSERT_TRUE(client.connect());
  24318. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24319. // The server should reject it and close the connection.
  24320. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24321. client.send(oversized);
  24322. // The server's read() should have failed due to payload limit,
  24323. // so our read() should return false (connection closed).
  24324. std::string msg;
  24325. EXPECT_FALSE(client.read(msg));
  24326. }
  24327. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24328. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24329. "/ws-echo");
  24330. client.set_read_timeout(10, 0);
  24331. ASSERT_TRUE(client.connect());
  24332. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24333. // This should succeed.
  24334. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24335. ASSERT_TRUE(client.send(at_limit));
  24336. std::string msg;
  24337. ASSERT_TRUE(client.read(msg));
  24338. EXPECT_EQ(at_limit.size(), msg.size());
  24339. client.close();
  24340. }
  24341. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24342. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24343. "/nonexistent");
  24344. auto res = client.connect();
  24345. EXPECT_FALSE(res);
  24346. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24347. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24348. EXPECT_FALSE(client.is_open());
  24349. }
  24350. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24352. "/ws-echo");
  24353. ASSERT_TRUE(client.connect());
  24354. ASSERT_TRUE(client.send(""));
  24355. std::string msg;
  24356. EXPECT_EQ(ws::Text, client.read(msg));
  24357. EXPECT_EQ("", msg);
  24358. client.close();
  24359. }
  24360. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24362. "/ws-echo");
  24363. // First connection
  24364. ASSERT_TRUE(client.connect());
  24365. ASSERT_TRUE(client.send("first"));
  24366. std::string msg;
  24367. ASSERT_TRUE(client.read(msg));
  24368. EXPECT_EQ("first", msg);
  24369. client.close();
  24370. EXPECT_FALSE(client.is_open());
  24371. // Reconnect using the same client object
  24372. ASSERT_TRUE(client.connect());
  24373. ASSERT_TRUE(client.is_open());
  24374. ASSERT_TRUE(client.send("second"));
  24375. ASSERT_TRUE(client.read(msg));
  24376. EXPECT_EQ("second", msg);
  24377. client.close();
  24378. }
  24379. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24380. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24381. "/ws-close-status");
  24382. ASSERT_TRUE(client.connect());
  24383. // Trigger the server to close with GoingAway status
  24384. ASSERT_TRUE(client.send("trigger"));
  24385. // read() should return false after receiving the close frame
  24386. std::string msg;
  24387. EXPECT_FALSE(client.read(msg));
  24388. EXPECT_FALSE(client.is_open());
  24389. }
  24390. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24391. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24392. "/ws-echo");
  24393. ASSERT_TRUE(client.connect());
  24394. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24395. EXPECT_FALSE(client.is_open());
  24396. }
  24397. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24398. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24399. ws::WebSocketClient client(
  24400. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24401. ASSERT_TRUE(client.connect());
  24402. // Server should have selected graphql-ws
  24403. EXPECT_EQ("graphql-ws", client.subprotocol());
  24404. client.close();
  24405. }
  24406. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24407. Headers headers;
  24408. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24409. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24410. ws::WebSocketClient client(
  24411. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24412. ASSERT_TRUE(client.connect());
  24413. // The offer on the second field line counts too, so graphql-ws is selected
  24414. EXPECT_EQ("graphql-ws", client.subprotocol());
  24415. client.close();
  24416. }
  24417. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24418. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24419. ws::WebSocketClient client(
  24420. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24421. ASSERT_TRUE(client.connect());
  24422. // Server should not have selected any subprotocol
  24423. EXPECT_TRUE(client.subprotocol().empty());
  24424. client.close();
  24425. }
  24426. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24427. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24428. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24429. "/ws-subprotocol-unoffered",
  24430. headers);
  24431. ASSERT_TRUE(client.connect());
  24432. EXPECT_TRUE(client.subprotocol().empty());
  24433. client.close();
  24434. }
  24435. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24436. // Connect without requesting any subprotocol
  24437. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24438. "/ws-subprotocol");
  24439. ASSERT_TRUE(client.connect());
  24440. EXPECT_TRUE(client.subprotocol().empty());
  24441. client.close();
  24442. }
  24443. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24444. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24445. "/ws-echo");
  24446. client.set_tcp_nodelay(true);
  24447. client.set_connection_timeout(3, 0);
  24448. bool socket_options_called = false;
  24449. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24450. ASSERT_TRUE(client.connect());
  24451. ASSERT_TRUE(client.is_open());
  24452. EXPECT_TRUE(socket_options_called);
  24453. ASSERT_TRUE(client.send("hello"));
  24454. std::string msg;
  24455. auto result = client.read(msg);
  24456. EXPECT_EQ(result, ws::ReadResult::Text);
  24457. EXPECT_EQ(msg, "hello");
  24458. client.close();
  24459. }
  24460. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24461. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24462. "/ws-echo");
  24463. client.set_connection_timeout(std::chrono::seconds(3));
  24464. client.set_write_timeout(std::chrono::seconds(3));
  24465. // A sub-second remainder exercises the seconds/microseconds split.
  24466. client.set_read_timeout(std::chrono::milliseconds(1500));
  24467. ASSERT_TRUE(client.connect());
  24468. auto start = std::chrono::steady_clock::now();
  24469. std::string msg;
  24470. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24471. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24472. std::chrono::steady_clock::now() - start)
  24473. .count();
  24474. // Above 1s so that dropping the microseconds half of the split fails here.
  24475. // Ignoring the setter altogether would not reach this line at all: a client
  24476. // waits forever by default.
  24477. EXPECT_GE(elapsed, 1400);
  24478. EXPECT_LT(elapsed, 30000);
  24479. }
  24480. #ifndef _WIN32
  24481. // A send() that times out after part of the data went out returns the count
  24482. // written so far. Every byte of the frame must still be sent, or the peer reads
  24483. // the next frame's header and payload as the rest of this one.
  24484. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24485. signal(SIGPIPE, SIG_IGN);
  24486. const std::string large(4 * 1024 * 1024, 'A');
  24487. std::atomic<bool> large_sent{false};
  24488. std::atomic<bool> small_sent{false};
  24489. Server svr;
  24490. svr.set_write_timeout(0, 500000);
  24491. svr.set_socket_options([](socket_t sock) {
  24492. int size = 8192;
  24493. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24494. reinterpret_cast<const char *>(&size), sizeof(size));
  24495. });
  24496. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24497. large_sent = ws.send(large.data(), large.size());
  24498. small_sent = ws.send("after");
  24499. std::string msg;
  24500. while (ws.read(msg)) {}
  24501. });
  24502. auto port = svr.bind_to_any_port(HOST);
  24503. std::thread t([&]() { svr.listen_after_bind(); });
  24504. auto se = detail::scope_exit([&] {
  24505. svr.stop();
  24506. t.join();
  24507. });
  24508. svr.wait_until_ready();
  24509. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24510. std::to_string(port) + "/ws");
  24511. client.set_read_timeout(5);
  24512. client.set_socket_options([](socket_t sock) {
  24513. int size = 8192;
  24514. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24515. reinterpret_cast<const char *>(&size), sizeof(size));
  24516. });
  24517. ASSERT_TRUE(client.connect());
  24518. // Outlast the server's write timeout, then drain.
  24519. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24520. std::string msg;
  24521. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24522. EXPECT_TRUE(msg == large);
  24523. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24524. EXPECT_EQ("after", msg);
  24525. EXPECT_TRUE(large_sent);
  24526. EXPECT_TRUE(small_sent);
  24527. client.close();
  24528. }
  24529. #endif
  24530. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24531. Server svr;
  24532. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24533. if (!req.has_header("Authorization")) {
  24534. res.status = StatusCode::Unauthorized_401;
  24535. res.set_content("Unauthorized", "text/plain");
  24536. return Server::HandlerResponse::Handled;
  24537. }
  24538. return Server::HandlerResponse::Unhandled;
  24539. });
  24540. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24541. std::string msg;
  24542. while (ws.read(msg)) {
  24543. ws.send(msg);
  24544. }
  24545. });
  24546. auto port = svr.bind_to_any_port("localhost");
  24547. std::thread t([&]() { svr.listen_after_bind(); });
  24548. svr.wait_until_ready();
  24549. // Without Authorization header - should be rejected before upgrade
  24550. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24551. EXPECT_FALSE(client1.connect());
  24552. // The rejection is framed like any other HTTP response
  24553. {
  24554. Client cli("localhost", port);
  24555. Headers headers = {{"Upgrade", "websocket"},
  24556. {"Connection", "Upgrade"},
  24557. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24558. {"Sec-WebSocket-Version", "13"}};
  24559. auto res = cli.Get("/ws", headers);
  24560. ASSERT_TRUE(res);
  24561. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24562. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24563. EXPECT_EQ("Unauthorized", res->body);
  24564. }
  24565. // With Authorization header - should succeed
  24566. Headers headers = {{"Authorization", "Bearer token123"}};
  24567. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24568. headers);
  24569. ASSERT_TRUE(client2.connect());
  24570. ASSERT_TRUE(client2.send("hello"));
  24571. std::string msg;
  24572. ASSERT_TRUE(client2.read(msg));
  24573. EXPECT_EQ("hello", msg);
  24574. client2.close();
  24575. svr.stop();
  24576. t.join();
  24577. }
  24578. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24579. Server svr;
  24580. std::atomic<int> pre_routing_calls{0};
  24581. std::atomic<int> pre_request_calls{0};
  24582. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24583. pre_routing_calls++;
  24584. if (req.path == "/handled") {
  24585. res.set_content("handled", "text/plain");
  24586. return Server::HandlerResponse::Handled;
  24587. }
  24588. return Server::HandlerResponse::Unhandled;
  24589. });
  24590. svr.set_pre_request_handler([&](const Request &, Response &) {
  24591. pre_request_calls++;
  24592. return Server::HandlerResponse::Unhandled;
  24593. });
  24594. svr.Get("/http", [](const Request &, Response &res) {
  24595. res.set_content("http", "text/plain");
  24596. });
  24597. svr.WebSocket("/ws",
  24598. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  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. Headers upgrade = {{"Upgrade", "websocket"},
  24607. {"Connection", "Upgrade"},
  24608. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24609. {"Sec-WebSocket-Version", "13"}};
  24610. auto get = [&](const char *path) {
  24611. pre_routing_calls = 0;
  24612. return Client("localhost", port).Get(path, upgrade);
  24613. };
  24614. // No WebSocket route, but an HTTP one
  24615. auto res = get("/http");
  24616. ASSERT_TRUE(res);
  24617. EXPECT_EQ(StatusCode::OK_200, res->status);
  24618. EXPECT_EQ("http", res->body);
  24619. EXPECT_EQ(1, pre_routing_calls);
  24620. EXPECT_EQ(1, pre_request_calls);
  24621. // No route at all
  24622. res = get("/none");
  24623. ASSERT_TRUE(res);
  24624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24625. EXPECT_EQ(1, pre_routing_calls);
  24626. // Answered by the pre-routing handler
  24627. res = get("/handled");
  24628. ASSERT_TRUE(res);
  24629. EXPECT_EQ(StatusCode::OK_200, res->status);
  24630. EXPECT_EQ("handled", res->body);
  24631. EXPECT_EQ(1, pre_routing_calls);
  24632. // A WebSocket route
  24633. pre_routing_calls = 0;
  24634. pre_request_calls = 0;
  24635. {
  24636. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24637. "/ws");
  24638. ASSERT_TRUE(client.connect());
  24639. std::string msg;
  24640. ASSERT_TRUE(client.read(msg));
  24641. EXPECT_EQ("ws", msg);
  24642. client.close();
  24643. }
  24644. EXPECT_EQ(1, pre_routing_calls);
  24645. EXPECT_EQ(1, pre_request_calls);
  24646. }
  24647. // An upgrade request answered by a hook leaves its body unread, so that body
  24648. // must not be served as the next request on the connection.
  24649. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24650. Server svr;
  24651. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24652. if (req.path == "/pre-routing") {
  24653. res.set_content("pre-routing", "text/plain");
  24654. return Server::HandlerResponse::Handled;
  24655. }
  24656. return Server::HandlerResponse::Unhandled;
  24657. });
  24658. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24659. if (req.matched_route == "/pre-request") {
  24660. res.set_content("pre-request", "text/plain");
  24661. return Server::HandlerResponse::Handled;
  24662. }
  24663. return Server::HandlerResponse::Unhandled;
  24664. });
  24665. svr.Get("/smuggled", [](const Request &, Response &res) {
  24666. res.set_content("smuggled", "text/plain");
  24667. });
  24668. svr.WebSocket("/pre-request",
  24669. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24670. auto port = svr.bind_to_any_port(HOST);
  24671. std::thread t([&]() { svr.listen_after_bind(); });
  24672. auto se = detail::scope_exit([&] {
  24673. svr.stop();
  24674. t.join();
  24675. });
  24676. svr.wait_until_ready();
  24677. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24678. for (auto path : {"/pre-routing", "/pre-request"}) {
  24679. std::string req = std::string("GET ") + path +
  24680. " HTTP/1.1\r\n"
  24681. "Host: localhost\r\n"
  24682. "Upgrade: websocket\r\n"
  24683. "Connection: Upgrade\r\n"
  24684. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24685. "Sec-WebSocket-Version: 13\r\n"
  24686. "Content-Length: " +
  24687. std::to_string(body.size()) + "\r\n\r\n" + body;
  24688. std::string res;
  24689. ASSERT_TRUE(send_request(5, req, &res, port));
  24690. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24691. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24692. // Only one response, and the body was not served as a request
  24693. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24694. }
  24695. }
  24696. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24697. Server svr;
  24698. std::atomic<int> pre_request_calls{0};
  24699. std::atomic<bool> route_matched{false};
  24700. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24701. pre_request_calls++;
  24702. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24703. if (req.get_header_value("Authorization") != "Bearer token123") {
  24704. res.status = StatusCode::Unauthorized_401;
  24705. res.set_content("Unauthorized", "text/plain");
  24706. return Server::HandlerResponse::Handled;
  24707. }
  24708. return Server::HandlerResponse::Unhandled;
  24709. });
  24710. std::atomic<bool> handler_called{false};
  24711. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24712. handler_called = true;
  24713. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24714. });
  24715. auto port = svr.bind_to_any_port("localhost");
  24716. std::thread t([&]() { svr.listen_after_bind(); });
  24717. svr.wait_until_ready();
  24718. // Without Authorization header - should be rejected before upgrade
  24719. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24720. "/ws/1");
  24721. EXPECT_FALSE(client1.connect());
  24722. EXPECT_FALSE(handler_called);
  24723. EXPECT_EQ(1, pre_request_calls);
  24724. EXPECT_TRUE(route_matched);
  24725. // The rejection is an ordinary HTTP response, not a protocol switch
  24726. {
  24727. Client cli("localhost", port);
  24728. Headers headers = {{"Upgrade", "websocket"},
  24729. {"Connection", "Upgrade"},
  24730. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24731. {"Sec-WebSocket-Version", "13"}};
  24732. auto res = cli.Get("/ws/1", headers);
  24733. ASSERT_TRUE(res);
  24734. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24735. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24736. EXPECT_EQ("Unauthorized", res->body);
  24737. }
  24738. EXPECT_FALSE(handler_called);
  24739. // With Authorization header - should succeed
  24740. Headers headers = {{"Authorization", "Bearer token123"}};
  24741. ws::WebSocketClient client2(
  24742. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24743. ASSERT_TRUE(client2.connect());
  24744. std::string msg;
  24745. ASSERT_TRUE(client2.read(msg));
  24746. EXPECT_EQ("/ws/:id 2", msg);
  24747. EXPECT_TRUE(handler_called);
  24748. client2.close();
  24749. svr.stop();
  24750. t.join();
  24751. }
  24752. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24753. static Headers websocket_upgrade_headers() {
  24754. return {{"Upgrade", "websocket"},
  24755. {"Connection", "Upgrade"},
  24756. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24757. {"Sec-WebSocket-Version", "13"},
  24758. {"Sec-WebSocket-Protocol", "chat"}};
  24759. }
  24760. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24761. Server svr;
  24762. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24763. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24764. return Server::HandlerResponse::Unhandled;
  24765. });
  24766. svr.set_pre_request_handler([](const Request &req, Response &) {
  24767. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24768. return Server::HandlerResponse::Unhandled;
  24769. });
  24770. svr.set_exception_handler(
  24771. [](const Request &, Response &res, std::exception_ptr ep) {
  24772. try {
  24773. std::rethrow_exception(ep);
  24774. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24775. });
  24776. auto handler = [](const Request &, ws::WebSocket &) {};
  24777. svr.WebSocket("/pre-routing", handler);
  24778. svr.WebSocket("/pre-request", handler);
  24779. svr.WebSocket("/sub-protocol", handler,
  24780. [](const std::vector<std::string> &) -> std::string {
  24781. throw std::runtime_error("/sub-protocol");
  24782. });
  24783. auto port = svr.bind_to_any_port(HOST);
  24784. ASSERT_GT(port, 0);
  24785. thread t = thread([&] { svr.listen_after_bind(); });
  24786. auto se = detail::scope_exit([&] {
  24787. svr.stop();
  24788. t.join();
  24789. ASSERT_FALSE(svr.is_running());
  24790. });
  24791. svr.wait_until_ready();
  24792. Client cli(HOST, port);
  24793. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24794. auto res = cli.Get(path, websocket_upgrade_headers());
  24795. if (!res) {
  24796. ADD_FAILURE() << path << ": " << to_string(res.error());
  24797. continue;
  24798. }
  24799. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24800. EXPECT_EQ(path, res->body);
  24801. }
  24802. }
  24803. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24804. Server svr;
  24805. svr.set_pre_routing_handler(
  24806. [](const Request &, Response &) -> Server::HandlerResponse {
  24807. throw std::runtime_error("pre-routing");
  24808. });
  24809. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24810. auto port = svr.bind_to_any_port(HOST);
  24811. ASSERT_GT(port, 0);
  24812. thread t = thread([&] { svr.listen_after_bind(); });
  24813. auto se = detail::scope_exit([&] {
  24814. svr.stop();
  24815. t.join();
  24816. ASSERT_FALSE(svr.is_running());
  24817. });
  24818. svr.wait_until_ready();
  24819. Client cli(HOST, port);
  24820. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24821. ASSERT_TRUE(res) << to_string(res.error());
  24822. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24823. }
  24824. #endif
  24825. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24826. Server svr;
  24827. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24828. // A read timeout is how a handler gets control back. Without it, a handler
  24829. // parked in read() can never write on the connection it is reading.
  24830. ws.set_read_timeout(std::chrono::milliseconds(100));
  24831. std::string msg;
  24832. while (ws.is_open()) {
  24833. auto r = ws.read(msg);
  24834. if (r == httplib::ws::Timeout) {
  24835. ws.send("tick");
  24836. continue;
  24837. }
  24838. if (r == httplib::ws::Fail) { break; }
  24839. ws.send(msg);
  24840. }
  24841. });
  24842. auto port = svr.bind_to_any_port("localhost");
  24843. std::thread t([&]() { svr.listen_after_bind(); });
  24844. svr.wait_until_ready();
  24845. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24846. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24847. ASSERT_TRUE(client.connect());
  24848. // The client sends nothing, so anything it receives came out of the
  24849. // handler's timeout path.
  24850. std::string msg;
  24851. ASSERT_EQ(client.read(msg), ws::Text);
  24852. EXPECT_EQ("tick", msg);
  24853. client.close();
  24854. svr.stop();
  24855. t.join();
  24856. }
  24857. // Stream::read may return fewer bytes than asked for. This is that contract at
  24858. // its worst -- one byte per call -- which is what a frame header straddling a
  24859. // read buffer's boundary looks like to the frame parser.
  24860. class WsByteAtATimeStream : public Stream {
  24861. public:
  24862. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24863. bool is_readable() const override { return true; }
  24864. bool wait_readable() const override { return true; }
  24865. bool wait_writable() const override { return true; }
  24866. ssize_t read(char *ptr, size_t size) override {
  24867. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24868. *ptr = data_[pos_++];
  24869. return 1;
  24870. }
  24871. ssize_t write(const char *, size_t size) override {
  24872. return static_cast<ssize_t>(size);
  24873. }
  24874. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24875. ip = "127.0.0.1";
  24876. port = 0;
  24877. }
  24878. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24879. ip = "127.0.0.1";
  24880. port = 0;
  24881. }
  24882. socket_t socket() const override { return INVALID_SOCKET; }
  24883. time_t duration() const override { return 0; }
  24884. private:
  24885. std::string data_;
  24886. size_t pos_ = 0;
  24887. };
  24888. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24889. // The payload uses the 16-bit extended length, so the header, the length
  24890. // and the mask key are all multi-byte fields here. Each used to be read
  24891. // with a single read() call, which fails as soon as one is split. The
  24892. // payload is also a little over one read chunk, so it is read in two.
  24893. std::string body;
  24894. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24895. body += static_cast<char>(i % 251);
  24896. }
  24897. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24898. std::string frame;
  24899. frame += static_cast<char>(0x81); // FIN + Text
  24900. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24901. frame += static_cast<char>(body.size() >> 8);
  24902. frame += static_cast<char>(body.size() & 0xff);
  24903. for (size_t i = 0; i < 4; i++) {
  24904. frame += static_cast<char>(mask[i]);
  24905. }
  24906. for (size_t i = 0; i < body.size(); i++) {
  24907. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24908. }
  24909. WsByteAtATimeStream strm(frame);
  24910. ws::Opcode opcode;
  24911. std::string payload;
  24912. bool fin = false;
  24913. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24914. /*expect_masked=*/true, body.size()),
  24915. ws::impl::FrameRead::Ok);
  24916. EXPECT_TRUE(fin);
  24917. EXPECT_EQ(opcode, ws::Opcode::Text);
  24918. EXPECT_EQ(payload, body);
  24919. }
  24920. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24921. std::string body(2000, 'x');
  24922. std::string frame;
  24923. frame += static_cast<char>(0x82); // FIN + Binary
  24924. frame += static_cast<char>(126); // 16-bit length follows
  24925. frame += static_cast<char>(body.size() >> 8);
  24926. frame += static_cast<char>(body.size() & 0xff);
  24927. frame += body;
  24928. detail::BufferStream strm;
  24929. strm.write(frame.data(), frame.size());
  24930. ws::Opcode opcode;
  24931. std::string payload;
  24932. bool fin;
  24933. EXPECT_EQ(
  24934. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24935. ws::impl::FrameRead::Ok);
  24936. EXPECT_EQ(body, payload);
  24937. }
  24938. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24939. // The header announces the largest payload allowed, and only 3 bytes of it
  24940. // ever arrive.
  24941. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24942. std::string frame;
  24943. frame += static_cast<char>(0x82); // FIN + Binary
  24944. frame += static_cast<char>(127); // 64-bit length follows
  24945. for (int shift = 56; shift >= 0; shift -= 8) {
  24946. frame += static_cast<char>((len >> shift) & 0xff);
  24947. }
  24948. frame += "abc";
  24949. detail::BufferStream strm;
  24950. strm.write(frame.data(), frame.size());
  24951. ws::Opcode opcode;
  24952. std::string payload;
  24953. bool fin;
  24954. EXPECT_EQ(
  24955. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24956. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24957. ws::impl::FrameRead::Fail);
  24958. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24959. }
  24960. TEST(WebSocketTest, QueryStringInHandshake) {
  24961. Server svr;
  24962. std::mutex mtx;
  24963. std::string received_target;
  24964. std::string received_token;
  24965. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24966. {
  24967. std::lock_guard<std::mutex> lock(mtx);
  24968. received_target = req.target;
  24969. if (req.has_param("token")) {
  24970. received_token = req.get_param_value("token");
  24971. }
  24972. }
  24973. std::string msg;
  24974. while (ws.read(msg)) {
  24975. ws.send(msg);
  24976. }
  24977. });
  24978. auto port = svr.bind_to_any_port("localhost");
  24979. std::thread t([&]() { svr.listen_after_bind(); });
  24980. svr.wait_until_ready();
  24981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24982. "/ws?token=ABC&session=123");
  24983. ASSERT_TRUE(client.connect());
  24984. // Round-trip ensures the handler has run and captured the request.
  24985. ASSERT_TRUE(client.send("hello"));
  24986. std::string msg;
  24987. ASSERT_TRUE(client.read(msg));
  24988. EXPECT_EQ("hello", msg);
  24989. client.close();
  24990. {
  24991. std::lock_guard<std::mutex> lock(mtx);
  24992. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24993. EXPECT_EQ("ABC", received_token);
  24994. }
  24995. svr.stop();
  24996. t.join();
  24997. }
  24998. // Run a handshake against a throwaway server and hand the request the server
  24999. // received back to the caller, so tests can assert on the headers the client
  25000. // actually put on the wire.
  25001. static void capture_websocket_handshake_request(
  25002. const Headers &client_headers,
  25003. std::function<void(const Request &, int port)> verify) {
  25004. Server svr;
  25005. std::mutex mtx;
  25006. Request received;
  25007. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25008. {
  25009. std::lock_guard<std::mutex> lock(mtx);
  25010. received = req;
  25011. }
  25012. std::string msg;
  25013. while (ws.read(msg)) {
  25014. ws.send(msg);
  25015. }
  25016. });
  25017. auto port = svr.bind_to_any_port("localhost");
  25018. std::thread t([&]() { svr.listen_after_bind(); });
  25019. auto se = detail::scope_exit([&] {
  25020. svr.stop();
  25021. t.join();
  25022. });
  25023. svr.wait_until_ready();
  25024. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25025. client_headers);
  25026. ASSERT_TRUE(client.connect());
  25027. ASSERT_TRUE(client.send("hello"));
  25028. std::string msg;
  25029. ASSERT_TRUE(client.read(msg));
  25030. client.close();
  25031. {
  25032. std::lock_guard<std::mutex> lock(mtx);
  25033. verify(received, port);
  25034. }
  25035. }
  25036. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25037. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25038. // Non-default port must be present in the Host header. Default ports
  25039. // (80/443) are omitted; that logic is covered by
  25040. // MakeHostAndPortStringTest.
  25041. EXPECT_EQ("localhost:" + std::to_string(port),
  25042. req.get_header_value("Host"));
  25043. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25044. req.get_header_value("User-Agent"));
  25045. EXPECT_FALSE(req.has_header("Accept"));
  25046. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25047. EXPECT_FALSE(req.has_header("Content-Length"));
  25048. });
  25049. }
  25050. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25051. capture_websocket_handshake_request(
  25052. {{"Host", "example.com"},
  25053. {"User-Agent", "custom-agent"},
  25054. {"X-Custom", "value"}},
  25055. [](const Request &req, int) {
  25056. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25057. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25058. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25059. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25060. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25061. });
  25062. }
  25063. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25064. capture_websocket_handshake_request(
  25065. {{"Upgrade", "bogus"},
  25066. {"Connection", "close"},
  25067. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25068. {"Sec-WebSocket-Version", "8"}},
  25069. [](const Request &req, int) {
  25070. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25071. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25072. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25073. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25074. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25075. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25076. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25077. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25078. req.get_header_value("Sec-WebSocket-Key"));
  25079. });
  25080. }
  25081. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25082. // A header the client refuses to send must abort the handshake before any
  25083. // part of it reaches the wire; a lone request line would otherwise sit in
  25084. // the peer's buffer as a truncated request.
  25085. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25086. ASSERT_NE(INVALID_SOCKET, srv);
  25087. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25088. sockaddr_in addr{};
  25089. addr.sin_family = AF_INET;
  25090. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25091. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25092. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25093. ASSERT_EQ(0, ::listen(srv, 1));
  25094. sockaddr_in bound{};
  25095. socklen_t bound_len = sizeof(bound);
  25096. ASSERT_EQ(
  25097. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25098. auto port = ntohs(bound.sin_port);
  25099. ssize_t received = -1;
  25100. std::thread t([&] {
  25101. // Bound every blocking call so a regression fails the test with a bad
  25102. // value instead of hanging the suite.
  25103. fd_set rfds;
  25104. FD_ZERO(&rfds);
  25105. FD_SET(srv, &rfds);
  25106. timeval tv{5, 0};
  25107. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25108. 0) {
  25109. return;
  25110. }
  25111. sockaddr_in cli_addr{};
  25112. socklen_t cli_len = sizeof(cli_addr);
  25113. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25114. if (cli == INVALID_SOCKET) { return; }
  25115. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25116. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25117. char buf[4096];
  25118. received = ::recv(cli, buf, sizeof(buf), 0);
  25119. });
  25120. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25121. // connect() has already shut the socket down by the time it returns false,
  25122. // so the peer sees EOF without waiting for the client to be destroyed.
  25123. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25124. {{"X-Bad", "a\r\nInjected: 1"}});
  25125. EXPECT_FALSE(client.connect());
  25126. t.join();
  25127. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25128. EXPECT_EQ(0, received);
  25129. }
  25130. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25131. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25132. // contains "upgrade" as a substring is a different token and must not
  25133. // start a WebSocket handshake.
  25134. auto make_request = [](const std::vector<std::string> &connection_values) {
  25135. Request req;
  25136. req.method = "GET";
  25137. req.headers.emplace("Upgrade", "websocket");
  25138. for (const auto &value : connection_values) {
  25139. req.headers.emplace("Connection", value);
  25140. }
  25141. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25142. req.headers.emplace("Sec-WebSocket-Version", "13");
  25143. return req;
  25144. };
  25145. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25146. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25147. EXPECT_TRUE(
  25148. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25149. EXPECT_TRUE(
  25150. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25151. EXPECT_TRUE(
  25152. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25153. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25154. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25155. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25156. EXPECT_FALSE(
  25157. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25158. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25159. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25160. }
  25161. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25162. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25163. // asks recipients to match each protocol-name case-insensitively, and RFC
  25164. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25165. // client naming websocket alongside another protocol, or on a second field
  25166. // line, is offering websocket; a value that merely contains "websocket" as a
  25167. // substring is a different protocol name and is not.
  25168. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25169. Request req;
  25170. req.method = "GET";
  25171. for (const auto &value : upgrade_values) {
  25172. req.headers.emplace("Upgrade", value);
  25173. }
  25174. req.headers.emplace("Connection", "Upgrade");
  25175. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25176. req.headers.emplace("Sec-WebSocket-Version", "13");
  25177. return req;
  25178. };
  25179. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25180. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25181. EXPECT_TRUE(
  25182. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25183. EXPECT_TRUE(
  25184. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25185. EXPECT_TRUE(
  25186. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25187. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25188. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25189. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25190. EXPECT_FALSE(
  25191. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25192. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25193. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25194. }
  25195. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25196. Server svr;
  25197. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25198. auto port = svr.bind_to_any_port("localhost");
  25199. std::thread t([&]() { svr.listen_after_bind(); });
  25200. auto se = detail::scope_exit([&] {
  25201. svr.stop();
  25202. t.join();
  25203. });
  25204. svr.wait_until_ready();
  25205. Headers headers = {{"Upgrade", "websocket"},
  25206. {"Connection", "notupgrade"},
  25207. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25208. {"Sec-WebSocket-Version", "13"}};
  25209. Client cli("localhost", port);
  25210. auto res = cli.Get("/ws", headers);
  25211. // The route exists only as a WebSocket route, so a request that fails the
  25212. // handshake check falls through to ordinary routing.
  25213. ASSERT_TRUE(res);
  25214. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25215. }
  25216. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25217. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25218. // Connection value is the only thing left for the client to reject.
  25219. Server svr;
  25220. svr.Get("/ws", [](const Request &req, Response &res) {
  25221. res.status = StatusCode::SwitchingProtocol_101;
  25222. res.set_header("Upgrade", "websocket");
  25223. res.set_header("Connection", "notupgrade");
  25224. res.set_header("Sec-WebSocket-Accept",
  25225. detail::websocket_accept_key(
  25226. req.get_header_value("Sec-WebSocket-Key")));
  25227. });
  25228. auto port = svr.bind_to_any_port("localhost");
  25229. std::thread t([&]() { svr.listen_after_bind(); });
  25230. auto se = detail::scope_exit([&] {
  25231. svr.stop();
  25232. t.join();
  25233. });
  25234. svr.wait_until_ready();
  25235. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25236. auto res = client.connect();
  25237. EXPECT_FALSE(res);
  25238. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25239. EXPECT_FALSE(client.is_open());
  25240. }
  25241. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25242. Server svr;
  25243. svr.Get("/ws", [](const Request &req, Response &res) {
  25244. res.status = StatusCode::SwitchingProtocol_101;
  25245. res.set_header("Upgrade", "websocket");
  25246. res.set_header("Connection", "Upgrade");
  25247. res.set_header("Sec-WebSocket-Accept",
  25248. detail::websocket_accept_key(
  25249. req.get_header_value("Sec-WebSocket-Key")));
  25250. res.set_header("Sec-WebSocket-Protocol", "admin");
  25251. });
  25252. auto port = svr.bind_to_any_port("localhost");
  25253. std::thread t([&]() { svr.listen_after_bind(); });
  25254. auto se = detail::scope_exit([&] {
  25255. svr.stop();
  25256. t.join();
  25257. });
  25258. svr.wait_until_ready();
  25259. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25260. // Server selects a subprotocol the client never offered
  25261. {
  25262. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25263. ws::WebSocketClient client(url, headers);
  25264. auto res = client.connect();
  25265. EXPECT_FALSE(res);
  25266. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25267. EXPECT_FALSE(client.is_open());
  25268. EXPECT_TRUE(client.subprotocol().empty());
  25269. }
  25270. // Client offered none but the server named one anyway
  25271. {
  25272. ws::WebSocketClient client(url);
  25273. auto res = client.connect();
  25274. EXPECT_FALSE(res);
  25275. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25276. EXPECT_FALSE(client.is_open());
  25277. EXPECT_TRUE(client.subprotocol().empty());
  25278. }
  25279. }
  25280. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25281. // The socket path doubles as the URL host, so it must not contain '/'.
  25282. const char *shard = getenv("GTEST_SHARD_INDEX");
  25283. const std::string sock_path =
  25284. shard ? std::string("httplib-ws-") + shard + ".sock"
  25285. : std::string("httplib-ws.sock");
  25286. std::remove(sock_path.c_str());
  25287. Server svr;
  25288. std::mutex mtx;
  25289. std::string received_host;
  25290. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25291. {
  25292. std::lock_guard<std::mutex> lock(mtx);
  25293. received_host = req.get_header_value("Host");
  25294. }
  25295. std::string msg;
  25296. while (ws.read(msg)) {
  25297. ws.send(msg);
  25298. }
  25299. });
  25300. svr.set_address_family(AF_UNIX);
  25301. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25302. auto se = detail::scope_exit([&] {
  25303. svr.stop();
  25304. t.join();
  25305. std::remove(sock_path.c_str());
  25306. });
  25307. svr.wait_until_ready();
  25308. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25309. client.set_address_family(AF_UNIX);
  25310. ASSERT_TRUE(client.connect());
  25311. ASSERT_TRUE(client.send("hello"));
  25312. std::string msg;
  25313. ASSERT_TRUE(client.read(msg));
  25314. client.close();
  25315. {
  25316. std::lock_guard<std::mutex> lock(mtx);
  25317. // There is no host:port for a Unix socket, so the same "localhost"
  25318. // placeholder the HTTP client uses is expected.
  25319. EXPECT_EQ("localhost", received_host);
  25320. }
  25321. }
  25322. // Two threads must never parse WebSocket frames from the same stream.
  25323. // close() used to read the peer's Close reply with its own frame read, so it
  25324. // raced a reader thread that was in the middle of a payload: the payload loop
  25325. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25326. // so bytes taken by close() were replaced with bytes from further along the
  25327. // stream. The message kept its length and silently changed content.
  25328. //
  25329. // The raw peer below sends a frame header plus part of the payload, waits for
  25330. // the handler to call close(), and only then sends the rest. Whichever thread
  25331. // would win the race for those bytes, the message must arrive intact, because
  25332. // close() must not touch the stream while read() owns it.
  25333. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25334. #ifndef _WIN32
  25335. signal(SIGPIPE, SIG_IGN);
  25336. #endif
  25337. const size_t payload_len = 120; // fits the 7-bit length field
  25338. const size_t prefix_len = 8;
  25339. const int attempts = 8;
  25340. std::string expected(payload_len, '\0');
  25341. for (size_t i = 0; i < payload_len; i++) {
  25342. expected[i] = static_cast<char>('a' + i % 26);
  25343. }
  25344. std::atomic<bool> peer_stalled{false};
  25345. std::atomic<bool> handler_done{false};
  25346. std::mutex received_mutex;
  25347. std::vector<std::string> received;
  25348. // Bound every wait, so a regression fails the test instead of hanging the
  25349. // suite.
  25350. auto wait_for = [](const std::atomic<bool> &flag) {
  25351. for (int i = 0; i < 500 && !flag; i++) {
  25352. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25353. }
  25354. };
  25355. Server svr;
  25356. svr.set_websocket_ping_interval(0);
  25357. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25358. std::thread reader([&]() {
  25359. std::string msg;
  25360. while (ws.read(msg)) {
  25361. std::lock_guard<std::mutex> guard(received_mutex);
  25362. received.push_back(msg);
  25363. }
  25364. });
  25365. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25366. // inside read_websocket_frame() when close() runs.
  25367. wait_for(peer_stalled);
  25368. ws.close();
  25369. reader.join();
  25370. handler_done = true;
  25371. });
  25372. auto port = svr.bind_to_any_port("127.0.0.1");
  25373. std::thread t([&]() { svr.listen_after_bind(); });
  25374. auto se = detail::scope_exit([&] {
  25375. svr.stop();
  25376. t.join();
  25377. });
  25378. svr.wait_until_ready();
  25379. auto send_bytes = [](socket_t s, const std::string &data) {
  25380. #ifdef _WIN32
  25381. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25382. #else
  25383. auto n = ::send(s, data.data(), data.size(), 0);
  25384. #endif
  25385. return n == static_cast<decltype(n)>(data.size());
  25386. };
  25387. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25388. // Every length used here fits the 7-bit length field.
  25389. auto masked_header = [](uint8_t first_byte, size_t len) {
  25390. std::string h;
  25391. h += static_cast<char>(first_byte);
  25392. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25393. h.append(4, '\0'); // mask key
  25394. return h;
  25395. };
  25396. for (int attempt = 0; attempt < attempts; attempt++) {
  25397. peer_stalled = false;
  25398. handler_done = false;
  25399. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25400. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25401. auto se_sock = detail::scope_exit([&] {
  25402. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25403. });
  25404. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25405. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25406. sockaddr_in addr{};
  25407. addr.sin_family = AF_INET;
  25408. addr.sin_port = htons(static_cast<uint16_t>(port));
  25409. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25410. ASSERT_EQ(
  25411. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25412. << "attempt " << attempt;
  25413. ASSERT_TRUE(send_bytes(sock,
  25414. "GET /ws HTTP/1.1\r\n"
  25415. "Host: 127.0.0.1\r\n"
  25416. "Upgrade: websocket\r\n"
  25417. "Connection: Upgrade\r\n"
  25418. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25419. "Sec-WebSocket-Version: 13\r\n"
  25420. "\r\n"))
  25421. << "attempt " << attempt;
  25422. std::string response;
  25423. while (response.find("\r\n\r\n") == std::string::npos) {
  25424. char buf[512];
  25425. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25426. if (n <= 0) { break; }
  25427. response.append(buf, static_cast<size_t>(n));
  25428. }
  25429. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25430. << "attempt " << attempt;
  25431. // Send the header of a Binary message but only the first prefix_len bytes
  25432. // of its payload, leaving the reader thread stalled inside the payload.
  25433. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25434. expected.substr(0, prefix_len)))
  25435. << "attempt " << attempt;
  25436. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25437. peer_stalled = true;
  25438. // Let close() send its Close frame and park in its own read before the
  25439. // rest of the payload arrives, so both threads are waiting for it.
  25440. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25441. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25442. close_frame += static_cast<char>(0x03); // status 1000
  25443. close_frame += static_cast<char>(0xE8);
  25444. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25445. << "attempt " << attempt;
  25446. // Closing the peer releases the reader thread even on the buggy path,
  25447. // where it waits for bytes another thread already consumed.
  25448. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25449. detail::close_socket(sock);
  25450. sock = INVALID_SOCKET;
  25451. wait_for(handler_done);
  25452. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25453. }
  25454. std::lock_guard<std::mutex> guard(received_mutex);
  25455. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25456. << "a message in flight when close() ran was dropped";
  25457. for (size_t i = 0; i < received.size(); i++) {
  25458. EXPECT_EQ(expected, received[i]) << "message " << i;
  25459. }
  25460. }
  25461. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25462. // returning the socket, or INVALID_SOCKET.
  25463. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25464. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25465. if (sock == INVALID_SOCKET) { return sock; }
  25466. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25467. sockaddr_in addr{};
  25468. addr.sin_family = AF_INET;
  25469. addr.sin_port = htons(static_cast<uint16_t>(port));
  25470. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25471. std::string req = "GET " + path +
  25472. " HTTP/1.1\r\n"
  25473. "Host: 127.0.0.1\r\n"
  25474. "Upgrade: websocket\r\n"
  25475. "Connection: Upgrade\r\n"
  25476. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25477. "Sec-WebSocket-Version: 13\r\n"
  25478. "\r\n";
  25479. std::string res;
  25480. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25481. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25482. static_cast<ssize_t>(req.size())) {
  25483. char c;
  25484. while (res.find("\r\n\r\n") == std::string::npos &&
  25485. ::recv(sock, &c, 1, 0) == 1) {
  25486. res += c;
  25487. }
  25488. }
  25489. if (res.find(" 101 ") == std::string::npos) {
  25490. detail::close_socket(sock);
  25491. return INVALID_SOCKET;
  25492. }
  25493. return sock;
  25494. }
  25495. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25496. // The payload must fit the 7-bit length field.
  25497. static std::string masked_frame(uint8_t first_byte,
  25498. const std::string &payload) {
  25499. std::string f;
  25500. f += static_cast<char>(first_byte);
  25501. f += static_cast<char>(0x80 | payload.size());
  25502. f.append(4, '\0');
  25503. return f + payload;
  25504. }
  25505. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25506. std::atomic<bool> done{false};
  25507. std::string received;
  25508. Server svr;
  25509. svr.set_websocket_ping_interval(0);
  25510. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25511. std::string msg;
  25512. if (ws.read(msg) == ws::Binary) { received = msg; }
  25513. done = true;
  25514. });
  25515. auto port = svr.bind_to_any_port("127.0.0.1");
  25516. std::thread t([&]() { svr.listen_after_bind(); });
  25517. auto se = detail::scope_exit([&] {
  25518. svr.stop();
  25519. t.join();
  25520. });
  25521. svr.wait_until_ready();
  25522. auto sock = connect_raw_websocket(port, "/ws");
  25523. ASSERT_NE(INVALID_SOCKET, sock);
  25524. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25525. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25526. masked_frame(0x89, "p") + // FIN + Ping
  25527. masked_frame(0x80, "lo"); // FIN + Continuation
  25528. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25529. for (int i = 0; i < 500 && !done; i++) {
  25530. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25531. }
  25532. ASSERT_TRUE(done);
  25533. EXPECT_EQ("Hello", received);
  25534. // The Ping between the fragments is answered with a Pong.
  25535. char pong[3];
  25536. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25537. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25538. }
  25539. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25540. Server svr;
  25541. svr.set_websocket_ping_interval(-1);
  25542. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25543. std::string msg;
  25544. while (ws.read(msg)) {}
  25545. });
  25546. auto port = svr.bind_to_any_port("127.0.0.1");
  25547. std::thread t([&]() { svr.listen_after_bind(); });
  25548. auto se = detail::scope_exit([&] {
  25549. svr.stop();
  25550. t.join();
  25551. });
  25552. svr.wait_until_ready();
  25553. auto sock = connect_raw_websocket(port, "/ws");
  25554. ASSERT_NE(INVALID_SOCKET, sock);
  25555. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25556. // Nothing comes while the client stays quiet.
  25557. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25558. char c;
  25559. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25560. }
  25561. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25562. // and that has to end a read() already waiting on the peer, on every platform.
  25563. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25564. // The peer sends no pings, and its handler never calls read(), which is
  25565. // where pongs are written.
  25566. std::mutex mutex;
  25567. std::condition_variable cv;
  25568. auto release = false;
  25569. svr.set_websocket_ping_interval(0);
  25570. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25571. std::unique_lock<std::mutex> lock(mutex);
  25572. cv.wait(lock, [&] { return release; });
  25573. });
  25574. auto port = svr.bind_to_any_port(HOST);
  25575. std::thread t([&]() { svr.listen_after_bind(); });
  25576. auto se = detail::scope_exit([&] {
  25577. {
  25578. std::lock_guard<std::mutex> lock(mutex);
  25579. release = true;
  25580. }
  25581. cv.notify_all();
  25582. svr.stop();
  25583. t.join();
  25584. });
  25585. svr.wait_until_ready();
  25586. ws::WebSocketClient client(std::string(scheme) +
  25587. "://localhost:" + std::to_string(port) + "/ws");
  25588. #ifdef CPPHTTPLIB_SSL_ENABLED
  25589. client.enable_server_certificate_verification(false);
  25590. #endif
  25591. // A ping a second, given up on after two go unanswered: about 3s
  25592. client.set_websocket_ping_interval(1);
  25593. client.set_websocket_max_missed_pongs(2);
  25594. // Well past that, so that a read the timeout ends instead stands out
  25595. client.set_read_timeout(10);
  25596. ASSERT_TRUE(client.connect());
  25597. auto start = std::chrono::steady_clock::now();
  25598. std::string msg;
  25599. EXPECT_EQ(ws::Fail, client.read(msg));
  25600. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25601. std::chrono::steady_clock::now() - start)
  25602. .count(),
  25603. 6000);
  25604. EXPECT_FALSE(client.is_open());
  25605. }
  25606. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25607. Server svr;
  25608. check_pong_timeout_ends_read(svr, "ws");
  25609. }
  25610. #ifdef CPPHTTPLIB_SSL_ENABLED
  25611. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25612. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25613. ASSERT_TRUE(svr.is_valid());
  25614. check_pong_timeout_ends_read(svr, "wss");
  25615. }
  25616. #endif
  25617. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25618. Server svr;
  25619. svr.set_websocket_ping_interval(0);
  25620. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25621. std::string msg;
  25622. while (ws.read(msg)) {}
  25623. });
  25624. auto port = svr.bind_to_any_port("127.0.0.1");
  25625. std::thread t([&]() { svr.listen_after_bind(); });
  25626. auto se = detail::scope_exit([&] {
  25627. svr.stop();
  25628. t.join();
  25629. });
  25630. svr.wait_until_ready();
  25631. // Each Close payload and the reply it should get: an echo when valid, 1002
  25632. // otherwise.
  25633. std::vector<std::pair<std::string, std::string>> cases = {
  25634. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25635. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25636. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25637. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25638. };
  25639. // Also between the fragments of a message.
  25640. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25641. for (const auto &c : cases) {
  25642. auto sock = connect_raw_websocket(port, "/ws");
  25643. ASSERT_NE(INVALID_SOCKET, sock);
  25644. auto frames = prefix + masked_frame(0x88, c.first);
  25645. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25646. std::string reply;
  25647. char buf[256];
  25648. while (reply.size() < 2 + c.second.size()) {
  25649. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25650. if (n <= 0) { break; }
  25651. reply.append(buf, static_cast<size_t>(n));
  25652. }
  25653. detail::close_socket(sock);
  25654. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25655. c.second,
  25656. reply);
  25657. }
  25658. }
  25659. }
  25660. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25661. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25662. protected:
  25663. void SetUp() override {
  25664. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25665. SERVER_PRIVATE_KEY_FILE);
  25666. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25667. std::string msg;
  25668. ws::ReadResult ret;
  25669. while ((ret = ws.read(msg))) {
  25670. if (ret == ws::Binary) {
  25671. ws.send(msg.data(), msg.size());
  25672. } else {
  25673. ws.send(msg);
  25674. }
  25675. }
  25676. });
  25677. port_ = server_->bind_to_any_port(HOST);
  25678. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25679. server_->wait_until_ready();
  25680. }
  25681. void TearDown() override {
  25682. server_->stop();
  25683. if (server_thread_.joinable()) { server_thread_.join(); }
  25684. }
  25685. std::unique_ptr<SSLServer> server_;
  25686. std::thread server_thread_;
  25687. int port_ = 0;
  25688. };
  25689. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25690. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25691. {
  25692. ws::WebSocketClient client(url);
  25693. client.enable_server_certificate_verification(false);
  25694. auto calls = 0;
  25695. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25696. calls++;
  25697. return false;
  25698. });
  25699. EXPECT_FALSE(client.connect());
  25700. EXPECT_GT(calls, 0);
  25701. }
  25702. {
  25703. ws::WebSocketClient client(url);
  25704. client.enable_server_certificate_verification(false);
  25705. client.set_session_verifier([](tls::session_t) {
  25706. return SSLVerifierResponse::CertificateRejected;
  25707. });
  25708. EXPECT_FALSE(client.connect());
  25709. }
  25710. {
  25711. ws::WebSocketClient client(url);
  25712. client.enable_server_certificate_verification(false);
  25713. client.set_session_verifier([](tls::session_t) {
  25714. return SSLVerifierResponse::CertificateAccepted;
  25715. });
  25716. EXPECT_TRUE(client.connect());
  25717. }
  25718. }
  25719. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25720. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25721. "/ws-echo");
  25722. client.enable_server_certificate_verification(false);
  25723. ASSERT_TRUE(client.connect());
  25724. ASSERT_TRUE(client.is_open());
  25725. ASSERT_TRUE(client.send("Hello WSS"));
  25726. std::string msg;
  25727. EXPECT_EQ(ws::Text, client.read(msg));
  25728. EXPECT_EQ("Hello WSS", msg);
  25729. client.close();
  25730. }
  25731. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25732. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25733. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25734. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25735. // client (without calling close() first) is the only path that runs
  25736. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25737. // bug exactly.
  25738. //
  25739. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25740. // when linked against an instrumented libssl; run under Valgrind to catch it
  25741. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25742. // suite (the freed session otherwise stalls on the close handshake) — this test
  25743. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25744. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25745. {
  25746. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25747. "/ws-echo");
  25748. client.enable_server_certificate_verification(false);
  25749. client.set_read_timeout(2, 0);
  25750. client.set_write_timeout(2, 0);
  25751. ASSERT_TRUE(client.connect());
  25752. ASSERT_TRUE(client.is_open());
  25753. ASSERT_TRUE(client.send("still open"));
  25754. // Intentionally do NOT call client.close(): leaving scope runs
  25755. // shutdown_and_close() with the WebSocket still open, which must send the
  25756. // close frame while the TLS session is still alive.
  25757. }
  25758. }
  25759. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25760. // shutdown_and_close() at the start of connect(), reproducing the same
  25761. // use-after-free within the test body rather than at scope exit. The second
  25762. // connect must succeed and echo, proving the close handshake ran over a live
  25763. // session. See the note above about memory-tool requirements.
  25764. TEST_F(WebSocketSSLIntegrationTest,
  25765. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25766. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25767. "/ws-echo");
  25768. client.enable_server_certificate_verification(false);
  25769. client.set_read_timeout(2, 0);
  25770. client.set_write_timeout(2, 0);
  25771. ASSERT_TRUE(client.connect());
  25772. ASSERT_TRUE(client.is_open());
  25773. ASSERT_TRUE(client.send("still open"));
  25774. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25775. // the still-open connection, which must not touch a freed TLS session.
  25776. ASSERT_TRUE(client.connect());
  25777. ASSERT_TRUE(client.is_open());
  25778. ASSERT_TRUE(client.send("after reconnect"));
  25779. std::string msg;
  25780. EXPECT_EQ(ws::Text, client.read(msg));
  25781. EXPECT_EQ("after reconnect", msg);
  25782. client.close();
  25783. }
  25784. #endif
  25785. #ifdef CPPHTTPLIB_SSL_ENABLED
  25786. class WebSocketSSLCATest : public ::testing::Test {
  25787. protected:
  25788. void SetUp() override {
  25789. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25790. SERVER_PRIVATE_KEY_FILE);
  25791. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25792. std::string msg;
  25793. while (ws.read(msg)) {
  25794. ws.send(msg);
  25795. }
  25796. });
  25797. port_ = server_->bind_to_any_port("127.0.0.1");
  25798. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25799. server_->wait_until_ready();
  25800. }
  25801. void TearDown() override {
  25802. server_->stop();
  25803. if (server_thread_.joinable()) { server_thread_.join(); }
  25804. }
  25805. std::string url() const {
  25806. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25807. }
  25808. std::unique_ptr<SSLServer> server_;
  25809. std::thread server_thread_;
  25810. int port_ = 0;
  25811. };
  25812. // A custom CA loaded as PEM verifies the server with full certificate
  25813. // verification enabled
  25814. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25815. ws::WebSocketClient client(url());
  25816. std::string cert;
  25817. read_file(SERVER_CERT2_FILE, cert);
  25818. client.load_ca_cert_store(cert.c_str(), cert.size());
  25819. ASSERT_TRUE(client.connect());
  25820. ASSERT_TRUE(client.send("hello"));
  25821. std::string msg;
  25822. EXPECT_EQ(ws::Text, client.read(msg));
  25823. EXPECT_EQ("hello", msg);
  25824. client.close();
  25825. }
  25826. // A custom CA that does not cover the server must fail verification (the
  25827. // custom CA is exclusive; system certs are not loaded alongside it)
  25828. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25829. ws::WebSocketClient client(url());
  25830. std::string cert;
  25831. read_file(CLIENT_CA_CERT_FILE, cert);
  25832. client.load_ca_cert_store(cert.c_str(), cert.size());
  25833. auto res = client.connect();
  25834. ASSERT_FALSE(res);
  25835. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25836. EXPECT_EQ(-1, res.status());
  25837. EXPECT_NE(0u, res.ssl_backend_error());
  25838. }
  25839. // The same CA as a file path rather than PEM in memory
  25840. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25841. ws::WebSocketClient client(url());
  25842. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25843. ASSERT_TRUE(client.connect());
  25844. ASSERT_TRUE(client.send("hello"));
  25845. std::string msg;
  25846. EXPECT_EQ(ws::Text, client.read(msg));
  25847. EXPECT_EQ("hello", msg);
  25848. client.close();
  25849. }
  25850. // ...and a CA file that does not cover the server still fails, so it is the
  25851. // path above that decides the outcome
  25852. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25853. ws::WebSocketClient client(url());
  25854. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25855. ASSERT_FALSE(client.connect());
  25856. }
  25857. // Regression test: reconnecting with a native custom CA store used to reuse
  25858. // a store handle the previous TLS context had already freed (use-after-free
  25859. // under the OpenSSL backend). The context now lives as long as the client.
  25860. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25861. ws::WebSocketClient client(url());
  25862. std::string cert;
  25863. read_file(SERVER_CERT2_FILE, cert);
  25864. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25865. ASSERT_TRUE(client.connect());
  25866. client.close();
  25867. ASSERT_TRUE(client.connect());
  25868. ASSERT_TRUE(client.send("again"));
  25869. std::string msg;
  25870. EXPECT_EQ(ws::Text, client.read(msg));
  25871. EXPECT_EQ("again", msg);
  25872. client.close();
  25873. }
  25874. // Regression test: a certificate with a trusted chain but no identity match
  25875. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25876. // verification entirely for IP hosts, so this connection succeeded there.
  25877. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25878. // chain verification while the identity check must still fail.
  25879. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25881. ASSERT_TRUE(svr.is_valid());
  25882. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25883. std::string msg;
  25884. while (ws.read(msg)) {
  25885. ws.send(msg);
  25886. }
  25887. });
  25888. auto port = svr.bind_to_any_port("127.0.0.1");
  25889. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25890. auto se = detail::scope_exit([&] {
  25891. svr.stop();
  25892. t.join();
  25893. });
  25894. svr.wait_until_ready();
  25895. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25896. "/echo");
  25897. std::string cert;
  25898. read_file(SERVER_CERT_FILE, cert);
  25899. client.load_ca_cert_store(cert.c_str(), cert.size());
  25900. ASSERT_FALSE(client.connect());
  25901. }
  25902. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25903. // SNI, so nothing binds the host name to the TLS session. These bind the
  25904. // server to "localhost" instead, the only shape that exercises the SNI and
  25905. // hostname-verification path with certificate verification left enabled.
  25906. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25907. protected:
  25908. void Start(const char *cert_file) {
  25909. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25910. SERVER_PRIVATE_KEY_FILE);
  25911. ASSERT_TRUE(server_->is_valid());
  25912. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25913. std::string msg;
  25914. while (ws.read(msg)) {
  25915. ws.send(msg);
  25916. }
  25917. });
  25918. port_ = server_->bind_to_any_port("localhost");
  25919. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25920. server_->wait_until_ready();
  25921. }
  25922. void TearDown() override {
  25923. if (server_) { server_->stop(); }
  25924. if (server_thread_.joinable()) { server_thread_.join(); }
  25925. }
  25926. std::string url() const {
  25927. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25928. }
  25929. std::unique_ptr<SSLServer> server_;
  25930. std::thread server_thread_;
  25931. int port_ = 0;
  25932. };
  25933. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25934. // out and the connection is usable
  25935. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25936. Start(SERVER_CERT2_FILE);
  25937. ws::WebSocketClient client(url());
  25938. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25939. ASSERT_TRUE(client.connect());
  25940. ASSERT_TRUE(client.send("hello"));
  25941. std::string msg;
  25942. EXPECT_EQ(ws::Text, client.read(msg));
  25943. EXPECT_EQ("hello", msg);
  25944. client.close();
  25945. }
  25946. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25947. // while the identity check must still reject "localhost"
  25948. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25949. Start(SERVER_CERT_FILE);
  25950. ws::WebSocketClient client(url());
  25951. client.set_ca_cert_path(SERVER_CERT_FILE);
  25952. auto res = client.connect();
  25953. ASSERT_FALSE(res);
  25954. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25955. EXPECT_EQ(-1, res.status());
  25956. }
  25957. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25958. // disabled: the chain is still checked, only the identity check is skipped
  25959. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25960. Start(SERVER_CERT_FILE);
  25961. ws::WebSocketClient client(url());
  25962. client.set_ca_cert_path(SERVER_CERT_FILE);
  25963. client.enable_server_hostname_verification(false);
  25964. ASSERT_TRUE(client.connect());
  25965. ASSERT_TRUE(client.send("hello"));
  25966. std::string msg;
  25967. EXPECT_EQ(ws::Text, client.read(msg));
  25968. EXPECT_EQ("hello", msg);
  25969. client.close();
  25970. }
  25971. // A CA that did not sign the server certificate fails the chain, even though
  25972. // the name would match
  25973. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25974. Start(SERVER_CERT2_FILE);
  25975. ws::WebSocketClient client(url());
  25976. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25977. ASSERT_FALSE(client.connect());
  25978. }
  25979. // With verification disabled, neither the chain nor the name is checked
  25980. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25981. Start(SERVER_CERT_FILE);
  25982. ws::WebSocketClient client(url());
  25983. client.enable_server_certificate_verification(false);
  25984. ASSERT_TRUE(client.connect());
  25985. ASSERT_TRUE(client.send("hello"));
  25986. std::string msg;
  25987. EXPECT_EQ(ws::Text, client.read(msg));
  25988. EXPECT_EQ("hello", msg);
  25989. client.close();
  25990. }
  25991. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25992. protected:
  25993. void SetUp() override {
  25994. server_ = httplib::detail::make_unique<SSLServer>(
  25995. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25996. ASSERT_TRUE(server_->is_valid());
  25997. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25998. std::string msg;
  25999. while (ws.read(msg)) {
  26000. ws.send(msg);
  26001. }
  26002. });
  26003. port_ = server_->bind_to_any_port("localhost");
  26004. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26005. server_->wait_until_ready();
  26006. }
  26007. void TearDown() override {
  26008. server_->stop();
  26009. if (server_thread_.joinable()) { server_thread_.join(); }
  26010. }
  26011. std::string url() const {
  26012. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26013. }
  26014. void ConnectWithClientCert(const std::string &client_cert_file,
  26015. const std::string &client_private_key_file,
  26016. const char *private_key_password) {
  26017. std::string cert_pem, key_pem;
  26018. read_file(client_cert_file, cert_pem);
  26019. read_file(client_private_key_file, key_pem);
  26020. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26021. key_pem.c_str(), key_pem.size(),
  26022. private_key_password};
  26023. ConnectWithPem(pem);
  26024. }
  26025. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26026. ws::WebSocketClient client(url(), pem);
  26027. ASSERT_TRUE(client.is_valid());
  26028. client.enable_server_certificate_verification(false);
  26029. ASSERT_TRUE(client.connect());
  26030. ASSERT_TRUE(client.send("hello"));
  26031. std::string msg;
  26032. EXPECT_EQ(ws::Text, client.read(msg));
  26033. EXPECT_EQ("hello", msg);
  26034. client.close();
  26035. }
  26036. std::unique_ptr<SSLServer> server_;
  26037. std::thread server_thread_;
  26038. int port_ = 0;
  26039. };
  26040. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26041. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26042. }
  26043. // Control for the tests above: the fixture's server really does require a
  26044. // client certificate, so it is the PEM the constructor installed that decides
  26045. // the outcome.
  26046. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26047. ws::WebSocketClient client(url());
  26048. ASSERT_TRUE(client.is_valid());
  26049. client.enable_server_certificate_verification(false);
  26050. EXPECT_FALSE(client.connect());
  26051. }
  26052. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26053. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26054. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26055. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26056. }
  26057. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26058. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26059. std::string cert_pem, key_pem;
  26060. read_file(CLIENT_CERT_FILE, cert_pem);
  26061. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26062. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26063. std::vector<char> key(key_pem.begin(), key_pem.end());
  26064. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26065. key.size(), nullptr};
  26066. ConnectWithPem(pem);
  26067. }
  26068. #endif
  26069. #if !defined(_WIN32)
  26070. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26071. auto secret_dir = std::string("./symlink_test_secret");
  26072. auto served_dir = std::string("./symlink_test_served");
  26073. auto secret_file = secret_dir + "/secret.txt";
  26074. auto symlink_path = served_dir + "/escape";
  26075. // Setup: create directories and files
  26076. mkdir(secret_dir.c_str(), 0755);
  26077. mkdir(served_dir.c_str(), 0755);
  26078. {
  26079. std::ofstream ofs(secret_file);
  26080. ofs << "SECRET_DATA";
  26081. }
  26082. // Create symlink using absolute path so it resolves correctly
  26083. #ifdef PATH_MAX
  26084. char abs_secret[PATH_MAX];
  26085. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26086. #else
  26087. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26088. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26089. ASSERT_NE(nullptr, abs_secret);
  26090. #endif
  26091. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26092. auto se = detail::scope_exit([&] {
  26093. unlink(symlink_path.c_str());
  26094. unlink(secret_file.c_str());
  26095. rmdir(served_dir.c_str());
  26096. rmdir(secret_dir.c_str());
  26097. });
  26098. Server svr;
  26099. svr.set_mount_point("/", served_dir);
  26100. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26101. auto se2 = detail::scope_exit([&] {
  26102. svr.stop();
  26103. listen_thread.join();
  26104. });
  26105. svr.wait_until_ready();
  26106. Client cli("localhost", PORT);
  26107. // Symlink pointing outside base dir should be blocked
  26108. auto res = cli.Get("/escape/secret.txt");
  26109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26110. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26111. }
  26112. #else
  26113. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26114. auto secret_dir = std::string("junction_test_secret");
  26115. auto served_dir = std::string("junction_test_served");
  26116. auto secret_file = secret_dir + "\\secret.txt";
  26117. auto junction_path = served_dir + "\\escape";
  26118. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26119. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26120. {
  26121. std::ofstream ofs(secret_file);
  26122. ofs << "SECRET_DATA";
  26123. }
  26124. // A junction needs no privilege to create, unlike a symlink
  26125. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26126. ASSERT_EQ(0, std::system(cmd.c_str()));
  26127. auto se = detail::scope_exit([&] {
  26128. ::RemoveDirectoryA(junction_path.c_str());
  26129. std::remove(secret_file.c_str());
  26130. ::RemoveDirectoryA(served_dir.c_str());
  26131. ::RemoveDirectoryA(secret_dir.c_str());
  26132. });
  26133. Server svr;
  26134. svr.set_mount_point("/", served_dir);
  26135. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26136. auto se2 = detail::scope_exit([&] {
  26137. svr.stop();
  26138. listen_thread.join();
  26139. });
  26140. svr.wait_until_ready();
  26141. Client cli("localhost", PORT);
  26142. // Junction pointing outside base dir should be blocked
  26143. auto res = cli.Get("/escape/secret.txt");
  26144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26145. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26146. }
  26147. #endif
  26148. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26149. // "GET /smuggled" request), reads the first response, and only then sends the
  26150. // embedded request as the body. Returns how many times /smuggled ran.
  26151. //
  26152. // The body is sent AFTER receiving the first response (as in the original
  26153. // PoC) so that the stream_line_reader cannot buffer it together with the
  26154. // headers of the first request.
  26155. static int count_smuggled_requests(const std::string &outer_head,
  26156. std::string &first_response) {
  26157. Server svr;
  26158. svr.set_mount_point("/", "./www");
  26159. std::atomic<int> smuggled_count(0);
  26160. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26161. smuggled_count++;
  26162. res.set_content("oops", "text/plain");
  26163. });
  26164. svr.Post("/post", [&](const Request &req, Response &res) {
  26165. res.set_content(req.body, "text/plain");
  26166. });
  26167. auto port = svr.bind_to_any_port("localhost");
  26168. thread t = thread([&] { svr.listen_after_bind(); });
  26169. auto se = detail::scope_exit([&] {
  26170. svr.stop();
  26171. t.join();
  26172. });
  26173. svr.wait_until_ready();
  26174. auto error = Error::Success;
  26175. auto sock = detail::create_client_socket(
  26176. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26177. /*connection_timeout_sec=*/2, 0,
  26178. /*read_timeout_sec=*/2, 0,
  26179. /*write_timeout_sec=*/2, 0, std::string(), error);
  26180. EXPECT_NE(INVALID_SOCKET, sock);
  26181. if (sock == INVALID_SOCKET) { return -1; }
  26182. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26183. // The "smuggled" request will be sent as the body of the outer request
  26184. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26185. "Host: localhost\r\n"
  26186. "Connection: close\r\n"
  26187. "\r\n";
  26188. auto head = outer_head;
  26189. auto len = std::to_string(smuggled.size());
  26190. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26191. pos = head.find("{len}", pos + len.size())) {
  26192. head.replace(pos, 5, len);
  26193. }
  26194. // Step 1: Send only the outer request headers (no body yet)
  26195. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26196. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26197. // Step 2: Read the first response
  26198. char buf[4096];
  26199. for (;;) {
  26200. auto n = recv(sock, buf, sizeof(buf), 0);
  26201. if (n <= 0) break;
  26202. first_response.append(buf, static_cast<size_t>(n));
  26203. // Stop once we have a complete response (headers + body)
  26204. auto hdr_end = first_response.find("\r\n\r\n");
  26205. if (hdr_end != std::string::npos) {
  26206. // Check for Content-Length to know when the body is complete
  26207. auto cl_pos = first_response.find("Content-Length:");
  26208. if (cl_pos != std::string::npos) {
  26209. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26210. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26211. auto cl = std::stoul(
  26212. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26213. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26214. } else {
  26215. break; // No Content-Length, assume headers-only response
  26216. }
  26217. }
  26218. }
  26219. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26220. // vulnerable server the keep-alive loop reads this as a second request. The
  26221. // server may already have closed the connection, so the result is ignored.
  26222. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26223. // Half-close so that a server which drained the body sees EOF and closes,
  26224. // instead of the read below waiting for the read timeout.
  26225. #ifdef _WIN32
  26226. ::shutdown(sock, SD_SEND);
  26227. #else
  26228. ::shutdown(sock, SHUT_WR);
  26229. #endif
  26230. // Step 4: Read until the server closes the connection
  26231. for (;;) {
  26232. auto n = recv(sock, buf, sizeof(buf), 0);
  26233. if (n <= 0) break;
  26234. }
  26235. return smuggled_count.load();
  26236. }
  26237. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26238. // A GET request with Content-Length to a static file handler must have its
  26239. // body drained before the keep-alive connection is reused. Otherwise the
  26240. // unread body bytes are interpreted as the next HTTP request.
  26241. std::string first_response;
  26242. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26243. "Host: localhost\r\n"
  26244. "Content-Length: {len}\r\n"
  26245. "\r\n",
  26246. first_response));
  26247. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26248. }
  26249. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26250. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26251. // be answered with 400 and the connection closed. Treating it as "no body"
  26252. // leaves the body to be parsed as the next request.
  26253. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26254. const char *targets[] = {
  26255. "GET /file", // handler that never reads the body
  26256. "GET /not-found", // no handler matches (404)
  26257. "POST /post", // handler that reads the body
  26258. };
  26259. for (auto target : targets) {
  26260. for (auto value : values) {
  26261. std::string first_response;
  26262. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26263. " HTTP/1.1\r\n"
  26264. "Host: localhost\r\n"
  26265. "Content-Length: " +
  26266. value + "\r\n\r\n",
  26267. first_response))
  26268. << target << " with Content-Length: " << value;
  26269. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  26270. << target << " with Content-Length: " << value;
  26271. }
  26272. }
  26273. }
  26274. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  26275. // A 400 for an unparseable request line leaves the rest of the message
  26276. // unread, so the connection must be closed rather than reused.
  26277. std::string first_response;
  26278. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  26279. "Host: localhost\r\n"
  26280. "Content-Length: {len}\r\n"
  26281. "\r\n",
  26282. first_response));
  26283. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26284. }
  26285. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  26286. // Same as above for a header block that fails to parse.
  26287. std::string first_response;
  26288. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26289. "Host: localhost\r\n"
  26290. "Bad Header\r\n"
  26291. "Content-Length: {len}\r\n"
  26292. "\r\n",
  26293. first_response));
  26294. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26295. }
  26296. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  26297. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  26298. // server must not read another request on that connection, even when the
  26299. // request had no body to drain.
  26300. std::string first_response;
  26301. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  26302. "Host: localhost\r\n"
  26303. "\r\n",
  26304. first_response));
  26305. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26306. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26307. }
  26308. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26309. // A content reader that stops early leaves the stream inside the body.
  26310. // Draining the whole Content-Length from there, or reading the body again,
  26311. // reads into the next request, and whatever follows is parsed as a request
  26312. // of its own.
  26313. Server svr;
  26314. std::atomic<int> smuggled_count(0);
  26315. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26316. svr.Post("/upload", [](const Request &req, Response &res,
  26317. const ContentReader &content_reader) {
  26318. // Stop at the last chunk, so the whole body has been read however it
  26319. // arrives.
  26320. auto length = req.get_header_value_u64("Content-Length");
  26321. size_t total = 0;
  26322. auto consumed = content_reader([&](const char *, size_t n) {
  26323. total += n;
  26324. return total < length;
  26325. });
  26326. EXPECT_FALSE(consumed);
  26327. if (req.has_param("retry")) {
  26328. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26329. }
  26330. // Replace the 400 the aborted read set, which would close the connection.
  26331. res.set_redirect("/done");
  26332. });
  26333. auto port = svr.bind_to_any_port(HOST);
  26334. thread t = thread([&] { svr.listen_after_bind(); });
  26335. auto se = detail::scope_exit([&] {
  26336. svr.stop();
  26337. t.join();
  26338. });
  26339. svr.wait_until_ready();
  26340. // A front end sees the second request as a POST whose body is the GET. The
  26341. // first body is as long as the POST's headers, so draining it again reads
  26342. // exactly those and leaves the GET to be parsed next.
  26343. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26344. "Host: localhost\r\n"
  26345. "\r\n";
  26346. std::string second_head = "POST /post HTTP/1.1\r\n"
  26347. "Host: localhost\r\n"
  26348. "Content-Length: " +
  26349. std::to_string(inner.size()) +
  26350. "\r\n"
  26351. "\r\n";
  26352. for (auto target : {"/upload", "/upload?retry"}) {
  26353. smuggled_count = 0;
  26354. std::string request = "POST " + std::string(target) +
  26355. " HTTP/1.1\r\n"
  26356. "Host: localhost\r\n"
  26357. "Content-Length: " +
  26358. std::to_string(second_head.size()) +
  26359. "\r\n"
  26360. "\r\n" +
  26361. std::string(second_head.size(), 'A') + second_head +
  26362. inner;
  26363. std::string response;
  26364. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26365. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26366. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26367. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26368. EXPECT_EQ(0, smuggled_count.load()) << target;
  26369. }
  26370. }
  26371. // An error response closes the connection anyway, so the body is left unread
  26372. // with a redirect, such as one to a login page.
  26373. static void serve_redirects(Server &svr,
  26374. const std::function<void(int)> &client) {
  26375. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26376. res.set_redirect("/login");
  26377. return Server::HandlerResponse::Handled;
  26378. });
  26379. auto port = svr.bind_to_any_port(HOST);
  26380. ASSERT_GT(port, 0);
  26381. thread t = thread([&] { svr.listen_after_bind(); });
  26382. auto se = detail::scope_exit([&] {
  26383. svr.stop();
  26384. t.join();
  26385. ASSERT_FALSE(svr.is_running());
  26386. });
  26387. svr.wait_until_ready();
  26388. client(port);
  26389. }
  26390. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26391. Server svr;
  26392. serve_redirects(svr, [](int port) {
  26393. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26394. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26395. std::to_string(body.size()) + "\r\n\r\n" + body +
  26396. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26397. std::string resp;
  26398. ASSERT_TRUE(send_request(1, req, &resp, port));
  26399. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26400. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26401. });
  26402. }
  26403. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26404. Server svr;
  26405. svr.set_read_timeout(0, 200000);
  26406. serve_redirects(svr, [](int port) {
  26407. // A byte every 100 ms keeps each read within the read timeout, but not the
  26408. // body as a whole, so the server closes and the bytes sent after that fail.
  26409. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26410. "Content-Length: 10\r\n\r\n"};
  26411. parts.resize(11, "x");
  26412. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26413. });
  26414. }
  26415. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26416. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26417. // must be rejected with 400 Bad Request.
  26418. Server svr;
  26419. svr.Post("/test", [&](const Request &, Response &res) {
  26420. res.set_content("ok", "text/plain");
  26421. });
  26422. thread t = thread([&] { svr.listen(HOST, PORT); });
  26423. auto se = detail::scope_exit([&] {
  26424. svr.stop();
  26425. t.join();
  26426. ASSERT_FALSE(svr.is_running());
  26427. });
  26428. svr.wait_until_ready();
  26429. // Exact "chunked"
  26430. {
  26431. auto req = "POST /test HTTP/1.1\r\n"
  26432. "Host: localhost\r\n"
  26433. "Content-Length: 5\r\n"
  26434. "Transfer-Encoding: chunked\r\n"
  26435. "Connection: close\r\n"
  26436. "\r\n"
  26437. "hello";
  26438. std::string response;
  26439. ASSERT_TRUE(send_request(1, req, &response));
  26440. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26441. response.substr(0, response.find("\r\n")));
  26442. }
  26443. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26444. {
  26445. auto req = "POST /test HTTP/1.1\r\n"
  26446. "Host: localhost\r\n"
  26447. "Content-Length: 5\r\n"
  26448. "Transfer-Encoding: gzip, chunked\r\n"
  26449. "Connection: close\r\n"
  26450. "\r\n"
  26451. "hello";
  26452. std::string response;
  26453. ASSERT_TRUE(send_request(1, req, &response));
  26454. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26455. response.substr(0, response.find("\r\n")));
  26456. }
  26457. }
  26458. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26459. Server svr;
  26460. svr.Post("/test", [&](const Request &, Response &res) {
  26461. res.set_content("ok", "text/plain");
  26462. });
  26463. thread t = thread([&] { svr.listen(HOST, PORT); });
  26464. auto se = detail::scope_exit([&] {
  26465. svr.stop();
  26466. t.join();
  26467. ASSERT_FALSE(svr.is_running());
  26468. });
  26469. svr.wait_until_ready();
  26470. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26471. // length cannot be determined, so the server must answer 400 and close
  26472. // rather than treat the request as bodyless and leave the body in the
  26473. // socket for the next request to pick up.
  26474. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26475. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26476. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26477. std::string response;
  26478. ASSERT_TRUE(send_request(1, req, &response));
  26479. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26480. response.substr(0, response.find("\r\n")))
  26481. << transfer_encoding;
  26482. }
  26483. // RFC 9110 5.3: the codings may also be split across several
  26484. // Transfer-Encoding lines, which combine in the order they were received.
  26485. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26486. // just like the single-line "chunked, gzip" above.
  26487. {
  26488. auto req = "POST /test HTTP/1.1\r\n"
  26489. "Host: localhost\r\n"
  26490. "Transfer-Encoding: chunked\r\n"
  26491. "Transfer-Encoding: gzip\r\n"
  26492. "\r\n"
  26493. "0\r\n\r\n";
  26494. std::string response;
  26495. ASSERT_TRUE(send_request(1, req, &response));
  26496. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26497. response.substr(0, response.find("\r\n")));
  26498. }
  26499. }
  26500. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26501. Server svr;
  26502. svr.Post("/test", [&](const Request &, Response &res) {
  26503. res.set_content("ok", "text/plain");
  26504. });
  26505. auto port = svr.bind_to_any_port(HOST);
  26506. ASSERT_GT(port, 0);
  26507. thread t = thread([&] { svr.listen_after_bind(); });
  26508. auto se = detail::scope_exit([&] {
  26509. svr.stop();
  26510. t.join();
  26511. ASSERT_FALSE(svr.is_running());
  26512. });
  26513. svr.wait_until_ready();
  26514. for (auto transfer_encoding :
  26515. {"Transfer-Encoding: gzip, chunked\r\n",
  26516. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26517. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26518. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26519. transfer_encoding + "\r\n0\r\n\r\n";
  26520. std::string response;
  26521. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26522. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26523. response.substr(0, response.find("\r\n")))
  26524. << transfer_encoding;
  26525. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26526. << transfer_encoding;
  26527. }
  26528. }
  26529. // Regression for issue #2450: a DELETE without Content-Length on a
  26530. // keep-alive connection must not let the post-response drain consume the
  26531. // next request's bytes.
  26532. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26533. Server svr;
  26534. std::atomic<int> delete_count(0);
  26535. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26536. delete_count++;
  26537. res.status = StatusCode::NoContent_204;
  26538. });
  26539. auto port = svr.bind_to_any_port(HOST);
  26540. thread t = thread([&] { svr.listen_after_bind(); });
  26541. auto se = detail::scope_exit([&] {
  26542. svr.stop();
  26543. t.join();
  26544. });
  26545. svr.wait_until_ready();
  26546. auto error = Error::Success;
  26547. auto sock = detail::create_client_socket(
  26548. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26549. /*connection_timeout_sec=*/2, 0,
  26550. /*read_timeout_sec=*/2, 0,
  26551. /*write_timeout_sec=*/2, 0, std::string(), error);
  26552. ASSERT_NE(INVALID_SOCKET, sock);
  26553. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26554. auto send_request_and_read_response = [&](const std::string &req,
  26555. std::string &out) -> bool {
  26556. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26557. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26558. char buf[4096];
  26559. for (;;) {
  26560. auto n = recv(sock, buf, sizeof(buf), 0);
  26561. if (n <= 0) { return !out.empty(); }
  26562. out.append(buf, static_cast<size_t>(n));
  26563. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26564. }
  26565. };
  26566. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26567. "Host: localhost\r\n"
  26568. "\r\n";
  26569. std::string resp1;
  26570. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26571. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26572. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26573. "Host: localhost\r\n"
  26574. "Connection: close\r\n"
  26575. "\r\n";
  26576. std::string resp2;
  26577. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26578. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26579. EXPECT_EQ(2, delete_count.load());
  26580. }
  26581. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26582. Server svr;
  26583. svr.Post("/ingest", [&](const Request &, Response &res,
  26584. const ContentReader &content_reader) {
  26585. auto consumed = content_reader([](const char *, size_t) { return false; });
  26586. EXPECT_FALSE(consumed);
  26587. res.status = StatusCode::Conflict_409;
  26588. res.set_header("Connection", "close");
  26589. });
  26590. auto port = svr.bind_to_any_port(HOST);
  26591. thread t = thread([&] { svr.listen_after_bind(); });
  26592. auto se = detail::scope_exit([&] {
  26593. svr.stop();
  26594. t.join();
  26595. });
  26596. svr.wait_until_ready();
  26597. auto error = Error::Success;
  26598. auto sock = detail::create_client_socket(
  26599. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26600. /*connection_timeout_sec=*/2, 0,
  26601. /*read_timeout_sec=*/1, 0,
  26602. /*write_timeout_sec=*/2, 0, std::string(), error);
  26603. ASSERT_NE(INVALID_SOCKET, sock);
  26604. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26605. std::string request = "POST /ingest HTTP/1.1\r\n"
  26606. "Host: localhost\r\n"
  26607. "Transfer-Encoding: chunked\r\n"
  26608. "\r\n"
  26609. "4\r\n"
  26610. "data\r\n";
  26611. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26612. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26613. std::string response;
  26614. ssize_t received = 0;
  26615. do {
  26616. char buf[4096];
  26617. received = recv(sock, buf, sizeof(buf), 0);
  26618. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26619. } while (received > 0);
  26620. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26621. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26622. EXPECT_EQ(0, received);
  26623. }
  26624. namespace no_proxy_test {
  26625. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26626. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26627. // calling listen().
  26628. class ScopedServer {
  26629. public:
  26630. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26631. ~ScopedServer() {
  26632. svr_.stop();
  26633. if (th_.joinable()) { th_.join(); }
  26634. }
  26635. Server &svr() { return svr_; }
  26636. int port() const { return port_; }
  26637. void listen() {
  26638. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26639. svr_.wait_until_ready();
  26640. }
  26641. private:
  26642. Server svr_;
  26643. std::thread th_;
  26644. int port_ = 0;
  26645. };
  26646. class ProxyAndTargetServers {
  26647. public:
  26648. ProxyAndTargetServers() {
  26649. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26650. proxy_hits_++;
  26651. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26652. res.set_content("via-proxy", "text/plain");
  26653. });
  26654. target_.Get(".*", [this](const Request &req, Response &res) {
  26655. target_hits_++;
  26656. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26657. res.set_content("direct", "text/plain");
  26658. });
  26659. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26660. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26661. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26662. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26663. proxy_mock_.wait_until_ready();
  26664. target_.wait_until_ready();
  26665. }
  26666. ~ProxyAndTargetServers() {
  26667. proxy_mock_.stop();
  26668. target_.stop();
  26669. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26670. if (target_thread_.joinable()) { target_thread_.join(); }
  26671. }
  26672. Server &proxy_mock() { return proxy_mock_; }
  26673. Server &target() { return target_; }
  26674. int proxy_port() const { return proxy_port_; }
  26675. int target_port() const { return target_port_; }
  26676. int proxy_hits() const { return proxy_hits_.load(); }
  26677. int target_hits() const { return target_hits_.load(); }
  26678. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26679. void reset_counters() {
  26680. proxy_hits_ = 0;
  26681. target_hits_ = 0;
  26682. last_had_proxy_authz_ = false;
  26683. }
  26684. private:
  26685. Server proxy_mock_;
  26686. Server target_;
  26687. std::thread proxy_thread_;
  26688. std::thread target_thread_;
  26689. int proxy_port_ = 0;
  26690. int target_port_ = 0;
  26691. std::atomic<int> proxy_hits_{0};
  26692. std::atomic<int> target_hits_{0};
  26693. std::atomic<bool> last_had_proxy_authz_{false};
  26694. };
  26695. inline std::unique_ptr<Client> make_client(const std::string &host,
  26696. ProxyAndTargetServers &s) {
  26697. auto cli = detail::make_unique<Client>(host, s.target_port());
  26698. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26699. cli->set_proxy("127.0.0.1", s.proxy_port());
  26700. return cli;
  26701. }
  26702. } // namespace no_proxy_test
  26703. using no_proxy_test::make_client;
  26704. using no_proxy_test::ProxyAndTargetServers;
  26705. // A stream request carries the credentials a buffered request does
  26706. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26707. no_proxy_test::ScopedServer origin;
  26708. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26709. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26710. });
  26711. origin.listen();
  26712. Client cli("127.0.0.1", origin.port());
  26713. cli.set_basic_auth("user", "pass");
  26714. auto handle = cli.open_stream("GET", "/x");
  26715. ASSERT_TRUE(handle.is_valid());
  26716. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26717. Client bearer("127.0.0.1", origin.port());
  26718. bearer.set_bearer_token_auth("tok");
  26719. auto handle2 = bearer.open_stream("GET", "/x");
  26720. ASSERT_TRUE(handle2.is_valid());
  26721. EXPECT_EQ("Bearer tok", read_all(handle2));
  26722. }
  26723. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26724. // takes its own credentials, as for a buffered request
  26725. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26726. std::string target, authz, proxy_authz;
  26727. no_proxy_test::ScopedServer proxy;
  26728. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26729. target = req.target;
  26730. authz = req.get_header_value("Authorization");
  26731. proxy_authz = req.get_header_value("Proxy-Authorization");
  26732. res.set_content("ok", "text/plain");
  26733. });
  26734. proxy.listen();
  26735. Client cli("origin.example", 8080);
  26736. cli.set_proxy("127.0.0.1", proxy.port());
  26737. cli.set_proxy_basic_auth("puser", "ppass");
  26738. cli.set_basic_auth("user", "pass");
  26739. auto handle = cli.open_stream("GET", "/x");
  26740. ASSERT_TRUE(handle.is_valid());
  26741. EXPECT_EQ("ok", read_all(handle));
  26742. EXPECT_EQ("http://origin.example:8080/x", target);
  26743. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26744. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26745. }
  26746. // In absolute-form the path follows the authority, so a path that does not
  26747. // begin with '/' would make the proxy connect to another host
  26748. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26749. std::vector<std::string> targets;
  26750. no_proxy_test::ScopedServer proxy;
  26751. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26752. targets.push_back(req.target);
  26753. res.set_content("ok", "text/plain");
  26754. });
  26755. proxy.listen();
  26756. Client cli("origin.example", 8080);
  26757. cli.set_proxy("127.0.0.1", proxy.port());
  26758. cli.set_basic_auth("user", "pass");
  26759. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26760. auto res = cli.Get(path);
  26761. EXPECT_FALSE(res) << path;
  26762. auto handle = cli.open_stream("GET", path);
  26763. EXPECT_FALSE(handle.is_valid()) << path;
  26764. }
  26765. EXPECT_TRUE(targets.empty());
  26766. auto res = cli.Get("/x");
  26767. ASSERT_TRUE(res);
  26768. ASSERT_EQ(1u, targets.size());
  26769. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26770. }
  26771. TEST(NoProxyTest, ExactHostnameBypasses) {
  26772. ProxyAndTargetServers s;
  26773. auto cli = make_client("example.com", s);
  26774. cli->set_no_proxy({"example.com"});
  26775. auto res = cli->Get("/");
  26776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26777. EXPECT_EQ(0, s.proxy_hits());
  26778. EXPECT_EQ(1, s.target_hits());
  26779. }
  26780. TEST(NoProxyTest, SubdomainBypasses) {
  26781. ProxyAndTargetServers s;
  26782. auto cli = make_client("foo.example.com", s);
  26783. cli->set_no_proxy({"example.com"});
  26784. auto res = cli->Get("/");
  26785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26786. EXPECT_EQ(0, s.proxy_hits());
  26787. EXPECT_EQ(1, s.target_hits());
  26788. }
  26789. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26790. // Regression guard: "evilexample.com" must not be considered a subdomain
  26791. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26792. // check would let traffic bypass the proxy and leak credentials direct
  26793. // to the attacker host.
  26794. ProxyAndTargetServers s;
  26795. auto cli = make_client("evilexample.com", s);
  26796. cli->set_no_proxy({"example.com"});
  26797. auto res = cli->Get("/");
  26798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26799. EXPECT_GE(s.proxy_hits(), 1);
  26800. EXPECT_EQ(0, s.target_hits());
  26801. }
  26802. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26803. ProxyAndTargetServers s;
  26804. auto cli = make_client("example.com.evil.com", s);
  26805. cli->set_no_proxy({"example.com"});
  26806. auto res = cli->Get("/");
  26807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26808. EXPECT_GE(s.proxy_hits(), 1);
  26809. EXPECT_EQ(0, s.target_hits());
  26810. }
  26811. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26812. ProxyAndTargetServers s;
  26813. auto cli = make_client("example.com", s);
  26814. cli->set_no_proxy({".example.com"});
  26815. auto res = cli->Get("/");
  26816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26817. EXPECT_EQ(0, s.proxy_hits());
  26818. EXPECT_EQ(1, s.target_hits());
  26819. }
  26820. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26821. ProxyAndTargetServers s;
  26822. auto cli = make_client("Example.COM", s);
  26823. cli->set_no_proxy({"EXAMPLE.com"});
  26824. auto res = cli->Get("/");
  26825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26826. EXPECT_EQ(0, s.proxy_hits());
  26827. EXPECT_EQ(1, s.target_hits());
  26828. }
  26829. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26830. ProxyAndTargetServers s;
  26831. auto cli = make_client("example.com.", s);
  26832. cli->set_no_proxy({"example.com"});
  26833. auto res = cli->Get("/");
  26834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26835. EXPECT_EQ(0, s.proxy_hits());
  26836. EXPECT_EQ(1, s.target_hits());
  26837. }
  26838. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26839. // Trailing dots must be normalized on BOTH sides — host and entry.
  26840. // An implementation that only strips the host-side trailing dot would
  26841. // fail to match host "example.com" against entry "example.com." because
  26842. // a literal substring search would compare 11 chars against 12.
  26843. ProxyAndTargetServers s;
  26844. auto cli = make_client("example.com", s);
  26845. cli->set_no_proxy({"example.com."});
  26846. auto res = cli->Get("/");
  26847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26848. EXPECT_EQ(0, s.proxy_hits());
  26849. EXPECT_EQ(1, s.target_hits());
  26850. }
  26851. TEST(NoProxyTest, WildcardBypassesEverything) {
  26852. ProxyAndTargetServers s;
  26853. auto cli = make_client("anything.invalid.test", s);
  26854. cli->set_no_proxy({"*"});
  26855. auto res = cli->Get("/");
  26856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26857. EXPECT_EQ(0, s.proxy_hits());
  26858. EXPECT_EQ(1, s.target_hits());
  26859. }
  26860. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26861. ProxyAndTargetServers s;
  26862. Client cli("127.0.0.1", s.target_port());
  26863. cli.set_proxy("127.0.0.1", s.proxy_port());
  26864. cli.set_no_proxy({"127.0.0.1"});
  26865. auto res = cli.Get("/");
  26866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26867. EXPECT_EQ(0, s.proxy_hits());
  26868. EXPECT_EQ(1, s.target_hits());
  26869. }
  26870. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26871. ProxyAndTargetServers s;
  26872. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26873. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26874. cli.set_proxy("127.0.0.1", s.proxy_port());
  26875. cli.set_no_proxy({"::1"});
  26876. auto res = cli.Get("/");
  26877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26878. EXPECT_EQ(0, s.proxy_hits());
  26879. EXPECT_EQ(1, s.target_hits());
  26880. }
  26881. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26882. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26883. // must still be recognized as IPv6 for CIDR matching. Implementations
  26884. // that detect IPv6 only when the host begins with '[' would parse the
  26885. // host as a hostname and miss the match.
  26886. ProxyAndTargetServers s;
  26887. Client cli("fe80::1", s.target_port());
  26888. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26889. cli.set_proxy("127.0.0.1", s.proxy_port());
  26890. cli.set_no_proxy({"fe80::/10"});
  26891. auto res = cli.Get("/");
  26892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26893. EXPECT_EQ(0, s.proxy_hits());
  26894. EXPECT_EQ(1, s.target_hits());
  26895. }
  26896. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26897. ProxyAndTargetServers s;
  26898. Client cli("::1", s.target_port());
  26899. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26900. cli.set_proxy("127.0.0.1", s.proxy_port());
  26901. cli.set_no_proxy({"[::1]"});
  26902. auto res = cli.Get("/");
  26903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26904. EXPECT_EQ(0, s.proxy_hits());
  26905. EXPECT_EQ(1, s.target_hits());
  26906. }
  26907. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26908. ProxyAndTargetServers s;
  26909. Client cli("fe80::1", s.target_port());
  26910. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26911. cli.set_proxy("127.0.0.1", s.proxy_port());
  26912. cli.set_no_proxy({"[fe80::]/10"});
  26913. auto res = cli.Get("/");
  26914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26915. EXPECT_EQ(0, s.proxy_hits());
  26916. EXPECT_EQ(1, s.target_hits());
  26917. }
  26918. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26919. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26920. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26921. // tricks via address-family conversion.
  26922. ProxyAndTargetServers s;
  26923. Client cli("::ffff:127.0.0.1", s.target_port());
  26924. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26925. cli.set_proxy("127.0.0.1", s.proxy_port());
  26926. cli.set_no_proxy({"127.0.0.1"});
  26927. auto res = cli.Get("/");
  26928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26929. EXPECT_GE(s.proxy_hits(), 1);
  26930. EXPECT_EQ(0, s.target_hits());
  26931. }
  26932. TEST(NoProxyTest, IPv4CidrMatch) {
  26933. ProxyAndTargetServers s;
  26934. Client cli("127.0.0.1", s.target_port());
  26935. cli.set_proxy("127.0.0.1", s.proxy_port());
  26936. cli.set_no_proxy({"127.0.0.0/8"});
  26937. auto res = cli.Get("/");
  26938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26939. EXPECT_EQ(0, s.proxy_hits());
  26940. EXPECT_EQ(1, s.target_hits());
  26941. }
  26942. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26943. ProxyAndTargetServers s;
  26944. Client cli("127.0.0.1", s.target_port());
  26945. cli.set_proxy("127.0.0.1", s.proxy_port());
  26946. cli.set_no_proxy({"10.0.0.0/8"});
  26947. auto res = cli.Get("/");
  26948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26949. EXPECT_GE(s.proxy_hits(), 1);
  26950. EXPECT_EQ(0, s.target_hits());
  26951. }
  26952. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26953. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26954. // IPv4 target matches.
  26955. ProxyAndTargetServers s;
  26956. Client cli("127.0.0.1", s.target_port());
  26957. cli.set_proxy("127.0.0.1", s.proxy_port());
  26958. cli.set_no_proxy({"0.0.0.0/0"});
  26959. auto res = cli.Get("/");
  26960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26961. EXPECT_EQ(0, s.proxy_hits());
  26962. EXPECT_EQ(1, s.target_hits());
  26963. }
  26964. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26965. ProxyAndTargetServers s;
  26966. Client cli("127.0.0.1", s.target_port());
  26967. cli.set_proxy("127.0.0.1", s.proxy_port());
  26968. cli.set_no_proxy({"127.0.0.1"});
  26969. auto res = cli.Get("/");
  26970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26971. EXPECT_EQ(0, s.proxy_hits());
  26972. EXPECT_EQ(1, s.target_hits());
  26973. }
  26974. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26975. ProxyAndTargetServers s;
  26976. Client cli("127.0.0.1", s.target_port());
  26977. cli.set_proxy("127.0.0.1", s.proxy_port());
  26978. cli.set_no_proxy({"127.0.0.0/33"});
  26979. auto res = cli.Get("/");
  26980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26981. EXPECT_GE(s.proxy_hits(), 1);
  26982. EXPECT_EQ(0, s.target_hits());
  26983. }
  26984. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26985. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26986. ProxyAndTargetServers s;
  26987. Client cli("127.0.0.1", s.target_port());
  26988. cli.set_proxy("127.0.0.1", s.proxy_port());
  26989. cli.set_no_proxy({"127.0.0.1/"});
  26990. auto res = cli.Get("/");
  26991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26992. EXPECT_GE(s.proxy_hits(), 1);
  26993. EXPECT_EQ(0, s.target_hits());
  26994. }
  26995. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26996. ProxyAndTargetServers s;
  26997. auto cli = make_client("internal.corp", s);
  26998. cli->set_proxy_basic_auth("u", "p");
  26999. cli->set_no_proxy({"internal.corp"});
  27000. auto res = cli->Get("/");
  27001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27002. EXPECT_EQ(1, s.target_hits());
  27003. EXPECT_EQ(0, s.proxy_hits());
  27004. EXPECT_FALSE(s.last_had_proxy_authz())
  27005. << "Proxy-Authorization must not be sent direct to the target";
  27006. }
  27007. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27008. ProxyAndTargetServers s;
  27009. auto cli = make_client("public.example", s);
  27010. cli->set_proxy_basic_auth("u", "p");
  27011. cli->set_no_proxy({"internal.corp"}); // does not match
  27012. auto res = cli->Get("/");
  27013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27014. EXPECT_GE(s.proxy_hits(), 1);
  27015. EXPECT_TRUE(s.last_had_proxy_authz());
  27016. }
  27017. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27018. std::atomic<int> hits{0};
  27019. std::atomic<int> hits_with_authz{0};
  27020. no_proxy_test::ScopedServer proxy_mock;
  27021. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27022. hits++;
  27023. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27024. if (req.target.find("/redir") != std::string::npos) {
  27025. res.set_redirect("http://other.example/landed");
  27026. } else {
  27027. res.set_content("via-proxy", "text/plain");
  27028. }
  27029. });
  27030. proxy_mock.listen();
  27031. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27032. hits = 0;
  27033. hits_with_authz = 0;
  27034. Client cli("public.example", 80);
  27035. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27036. cli.set_proxy_basic_auth(c.first, c.second);
  27037. cli.set_follow_location(true);
  27038. // The redirect to another host goes through the proxy as well
  27039. auto res = cli.Get("/redir");
  27040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27041. EXPECT_EQ(2, hits.load());
  27042. EXPECT_EQ(2, hits_with_authz.load());
  27043. }
  27044. }
  27045. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27046. ProxyAndTargetServers s;
  27047. auto cli = make_client("anything.test", s);
  27048. auto res = cli->Get("/");
  27049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27050. EXPECT_GE(s.proxy_hits(), 1);
  27051. EXPECT_EQ(0, s.target_hits());
  27052. }
  27053. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27054. ProxyAndTargetServers s;
  27055. auto cli = make_client("example.com", s);
  27056. cli->set_no_proxy({"example.com:8080"});
  27057. auto res = cli->Get("/");
  27058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27059. EXPECT_GE(s.proxy_hits(), 1);
  27060. EXPECT_EQ(0, s.target_hits());
  27061. }
  27062. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27063. ProxyAndTargetServers s;
  27064. auto cli = make_client("anything.test", s);
  27065. cli->set_no_proxy({"", " ", "\t"});
  27066. auto res = cli->Get("/");
  27067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27068. EXPECT_GE(s.proxy_hits(), 1);
  27069. EXPECT_EQ(0, s.target_hits());
  27070. }
  27071. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27072. // An entry with leading/trailing whitespace must still match — env-style
  27073. // values are commonly pasted with stray spaces and an implementation
  27074. // that feeds the raw token directly to inet_pton would fail to match
  27075. // valid CIDRs because of the spaces.
  27076. ProxyAndTargetServers s;
  27077. Client cli("127.0.0.1", s.target_port());
  27078. cli.set_proxy("127.0.0.1", s.proxy_port());
  27079. cli.set_no_proxy({" 127.0.0.0/8 "});
  27080. auto res = cli.Get("/");
  27081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27082. EXPECT_EQ(0, s.proxy_hits());
  27083. EXPECT_EQ(1, s.target_hits());
  27084. }
  27085. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27086. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27087. // go direct and must NOT carry Proxy-Authorization.
  27088. std::atomic<int> proxy_hits{0};
  27089. std::atomic<int> target_hits{0};
  27090. std::atomic<bool> target_saw_authz{false};
  27091. no_proxy_test::ScopedServer proxy_mock, target;
  27092. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27093. proxy_hits++;
  27094. res.status = 302;
  27095. res.set_header("Location", "http://127.0.0.1:" +
  27096. std::to_string(target.port()) + "/landed");
  27097. });
  27098. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27099. target_hits++;
  27100. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27101. res.set_content("direct", "text/plain");
  27102. });
  27103. proxy_mock.listen();
  27104. target.listen();
  27105. Client cli("public.example", target.port());
  27106. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27107. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27108. cli.set_proxy_basic_auth("u", "p");
  27109. cli.set_no_proxy({"127.0.0.1"});
  27110. cli.set_follow_location(true);
  27111. auto res = cli.Get("/redir");
  27112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27113. EXPECT_GE(proxy_hits.load(), 1);
  27114. EXPECT_GE(target_hits.load(), 1);
  27115. EXPECT_FALSE(target_saw_authz.load());
  27116. }
  27117. #ifdef CPPHTTPLIB_SSL_ENABLED
  27118. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27119. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27120. // proxy creds would be sent to the (possibly hostile) origin.
  27121. std::atomic<int> target_hits{0};
  27122. std::atomic<bool> target_saw_proxy_authz{false};
  27123. no_proxy_test::ScopedServer target;
  27124. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27125. target_hits++;
  27126. if (req.has_header("Proxy-Authorization")) {
  27127. target_saw_proxy_authz = true;
  27128. }
  27129. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27130. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27131. "nonce=\"abc\", algorithm=MD5");
  27132. });
  27133. target.listen();
  27134. // The proxy address is set to the target's port: the bypass MUST kick in;
  27135. // if it doesn't, the test still routes "via proxy" to the same server and
  27136. // the Proxy-Authorization assertion below catches the leak.
  27137. Client cli("evil.example", target.port());
  27138. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27139. cli.set_proxy("127.0.0.1", target.port());
  27140. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27141. cli.set_no_proxy({"evil.example"});
  27142. auto res = cli.Get("/x");
  27143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27144. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27145. EXPECT_EQ(1, target_hits.load());
  27146. EXPECT_FALSE(target_saw_proxy_authz.load());
  27147. }
  27148. #endif
  27149. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27150. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27151. std::atomic<int> proxy_hits{0};
  27152. std::atomic<int> bypass_hits{0};
  27153. std::atomic<bool> proxy_saw_c_url{false};
  27154. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27155. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27156. proxy_hits++;
  27157. if (req.path.find("/start") != std::string::npos) {
  27158. res.status = 302;
  27159. res.set_header("Location", "http://127.0.0.1:" +
  27160. std::to_string(bypass_server.port()) +
  27161. "/middle");
  27162. return;
  27163. }
  27164. if (req.path.find("/end") != std::string::npos) {
  27165. proxy_saw_c_url = true;
  27166. res.set_content("c-via-proxy", "text/plain");
  27167. return;
  27168. }
  27169. res.set_content("unexpected", "text/plain");
  27170. });
  27171. // public.example's "advertised" port is arbitrary (the request never lands
  27172. // there — it goes through the proxy), but use a dynamic value to stay
  27173. // friendly with sharded parallel runs.
  27174. int public_port = bypass_server.port();
  27175. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27176. bypass_hits++;
  27177. res.status = 302;
  27178. res.set_header("Location", "http://public.example:" +
  27179. std::to_string(public_port) + "/end");
  27180. });
  27181. proxy_mock.listen();
  27182. bypass_server.listen();
  27183. Client cli("public.example", public_port);
  27184. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27185. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27186. cli.set_no_proxy({"127.0.0.1"});
  27187. cli.set_follow_location(true);
  27188. auto res = cli.Get("/start");
  27189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27190. EXPECT_EQ(StatusCode::OK_200, res->status);
  27191. EXPECT_EQ("c-via-proxy", res->body);
  27192. EXPECT_GE(proxy_hits.load(), 2);
  27193. EXPECT_GE(bypass_hits.load(), 1);
  27194. EXPECT_TRUE(proxy_saw_c_url.load());
  27195. }
  27196. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27197. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27198. // request reconnects to the correct endpoint.
  27199. std::atomic<int> proxy_hits{0};
  27200. std::atomic<int> target_hits{0};
  27201. no_proxy_test::ScopedServer proxy_mock, target;
  27202. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27203. proxy_hits++;
  27204. res.set_content("via-proxy", "text/plain");
  27205. });
  27206. target.svr().Get(".*", [&](const Request &, Response &res) {
  27207. target_hits++;
  27208. res.set_content("direct", "text/plain");
  27209. });
  27210. proxy_mock.listen();
  27211. target.listen();
  27212. Client cli("public.example", target.port());
  27213. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27214. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27215. cli.set_keep_alive(true);
  27216. auto res1 = cli.Get("/a");
  27217. ASSERT_TRUE(res1);
  27218. EXPECT_EQ("via-proxy", res1->body);
  27219. EXPECT_EQ(1, proxy_hits.load());
  27220. EXPECT_EQ(0, target_hits.load());
  27221. cli.set_no_proxy({"public.example"});
  27222. auto res2 = cli.Get("/b");
  27223. ASSERT_TRUE(res2);
  27224. EXPECT_EQ("direct", res2->body);
  27225. EXPECT_EQ(1, proxy_hits.load());
  27226. EXPECT_EQ(1, target_hits.load());
  27227. }
  27228. // Forward declarations (see the base64_encode note).
  27229. namespace httplib {
  27230. namespace detail {
  27231. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27232. int shutdown_socket(socket_t sock) noexcept;
  27233. } // namespace detail
  27234. } // namespace httplib
  27235. namespace proxy_tunnel_test {
  27236. const char *const kTunnelEstablished =
  27237. "HTTP/1.1 200 Connection established\r\n\r\n";
  27238. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27239. using ConnectReply = std::function<std::string(const std::string &head)>;
  27240. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27241. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27242. class ScopedConnectProxy {
  27243. public:
  27244. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27245. : forward_port_(forward_port), reply_(std::move(reply)) {
  27246. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27247. if (listen_sock_ == INVALID_SOCKET) { return; }
  27248. auto a = loopback(0);
  27249. auto addr = reinterpret_cast<sockaddr *>(&a);
  27250. socklen_t alen = sizeof(a);
  27251. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27252. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27253. ::listen(listen_sock_, 4) != 0) {
  27254. return;
  27255. }
  27256. port_ = ntohs(a.sin_port);
  27257. th_ = std::thread([this] { run(); });
  27258. }
  27259. ~ScopedConnectProxy() {
  27260. if (th_.joinable()) {
  27261. stop_ = true;
  27262. auto wake = connect_to(port_);
  27263. th_.join();
  27264. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27265. }
  27266. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27267. }
  27268. int port() const { return port_; }
  27269. int connect_hits() const { return connect_hits_.load(); }
  27270. // Head of the last CONNECT request, as the proxy saw it on the wire.
  27271. std::string connect_request() const {
  27272. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27273. return connect_request_;
  27274. }
  27275. private:
  27276. static sockaddr_in loopback(int port) {
  27277. sockaddr_in a{};
  27278. a.sin_family = AF_INET;
  27279. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  27280. a.sin_port = htons(static_cast<unsigned short>(port));
  27281. return a;
  27282. }
  27283. static socket_t connect_to(int port) {
  27284. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  27285. if (sock == INVALID_SOCKET) { return sock; }
  27286. auto a = loopback(port);
  27287. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  27288. detail::close_socket(sock);
  27289. return INVALID_SOCKET;
  27290. }
  27291. return sock;
  27292. }
  27293. static bool send_all(socket_t sock, const char *data, size_t size) {
  27294. while (size > 0) {
  27295. auto n = detail::send_socket(sock, data, size, 0);
  27296. if (n <= 0) { return false; }
  27297. data += n;
  27298. size -= static_cast<size_t>(n);
  27299. }
  27300. return true;
  27301. }
  27302. void run() {
  27303. for (;;) {
  27304. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27305. if (stop_) {
  27306. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27307. return;
  27308. }
  27309. if (client == INVALID_SOCKET) { continue; }
  27310. serve(client);
  27311. detail::close_socket(client);
  27312. }
  27313. }
  27314. void serve(socket_t client) {
  27315. std::string head;
  27316. char buf[2048];
  27317. while (head.find("\r\n\r\n") == std::string::npos) {
  27318. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27319. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27320. if (n <= 0) { return; }
  27321. head.append(buf, static_cast<size_t>(n));
  27322. }
  27323. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27324. connect_hits_++;
  27325. {
  27326. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27327. connect_request_ = head;
  27328. }
  27329. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27330. if (!send_all(client, res.data(), res.size()) ||
  27331. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27332. return;
  27333. }
  27334. auto origin = connect_to(forward_port_);
  27335. if (origin == INVALID_SOCKET) { return; }
  27336. // When either side stops, shut both down so the other pump returns too.
  27337. auto pump = [&](socket_t from, socket_t to) {
  27338. char b[8192];
  27339. for (;;) {
  27340. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27341. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27342. }
  27343. detail::shutdown_socket(client);
  27344. detail::shutdown_socket(origin);
  27345. };
  27346. std::thread up([&] { pump(client, origin); });
  27347. pump(origin, client);
  27348. up.join();
  27349. detail::close_socket(origin);
  27350. }
  27351. int forward_port_;
  27352. ConnectReply reply_;
  27353. socket_t listen_sock_ = INVALID_SOCKET;
  27354. int port_ = 0;
  27355. std::thread th_;
  27356. std::atomic<bool> stop_{false};
  27357. std::atomic<int> connect_hits_{0};
  27358. mutable std::mutex connect_request_mutex_;
  27359. std::string connect_request_;
  27360. };
  27361. } // namespace proxy_tunnel_test
  27362. #ifdef CPPHTTPLIB_SSL_ENABLED
  27363. namespace proxy_tunnel_test {
  27364. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27365. class ScopedSSLServer {
  27366. public:
  27367. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27368. port_ = svr_.bind_to_any_port("127.0.0.1");
  27369. }
  27370. ~ScopedSSLServer() {
  27371. svr_.stop();
  27372. if (th_.joinable()) { th_.join(); }
  27373. }
  27374. SSLServer &svr() { return svr_; }
  27375. int port() const { return port_; }
  27376. void listen() {
  27377. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27378. svr_.wait_until_ready();
  27379. }
  27380. private:
  27381. SSLServer svr_;
  27382. std::thread th_;
  27383. int port_ = 0;
  27384. };
  27385. // Sends one request through the CONNECT proxy to the TLS origin with a
  27386. // credential configured for each hop, and checks that each credential reaches
  27387. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27388. // origin's (every header in origin_headers) on the tunnelled request.
  27389. void CredentialsStayWithTheirHop(
  27390. const std::function<void(SSLClient &)> &set_credentials,
  27391. const std::string &scheme,
  27392. const std::vector<std::string> &origin_headers = {"Authorization"},
  27393. bool stream = false) {
  27394. std::atomic<int> origin_hits{0};
  27395. std::atomic<bool> origin_saw_proxy_authz{false};
  27396. std::atomic<bool> origin_saw_headers{false};
  27397. ScopedSSLServer origin;
  27398. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27399. origin_hits++;
  27400. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27401. origin_saw_headers =
  27402. std::all_of(origin_headers.begin(), origin_headers.end(),
  27403. [&](const std::string &h) { return req.has_header(h); });
  27404. res.set_content("ok", "text/plain");
  27405. });
  27406. origin.listen();
  27407. ScopedConnectProxy proxy(origin.port());
  27408. ASSERT_NE(0, proxy.port());
  27409. // Pinned to 127.0.0.1 for the same reason as the test below.
  27410. SSLClient cli("127.0.0.1", origin.port());
  27411. cli.enable_server_certificate_verification(false);
  27412. cli.set_proxy("127.0.0.1", proxy.port());
  27413. set_credentials(cli);
  27414. if (stream) {
  27415. auto handle = cli.open_stream("GET", "/x");
  27416. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27417. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27418. } else {
  27419. auto res = cli.Get("/x");
  27420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27421. EXPECT_EQ(StatusCode::OK_200, res->status);
  27422. }
  27423. EXPECT_EQ(1, origin_hits.load());
  27424. EXPECT_EQ(1, proxy.connect_hits());
  27425. EXPECT_TRUE(origin_saw_headers.load());
  27426. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27427. << "Proxy-Authorization must not be sent inside the tunnel";
  27428. auto connect_req = proxy.connect_request();
  27429. EXPECT_NE(std::string::npos,
  27430. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27431. for (const auto &h : origin_headers) {
  27432. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27433. << h << " must not be sent to the proxy on CONNECT";
  27434. }
  27435. }
  27436. } // namespace proxy_tunnel_test
  27437. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27438. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27439. [](SSLClient &cli) {
  27440. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27441. cli.set_basic_auth("origin-user", "origin-pass");
  27442. },
  27443. "Basic");
  27444. }
  27445. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27446. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27447. [](SSLClient &cli) {
  27448. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27449. cli.set_basic_auth("origin-user", "origin-pass");
  27450. },
  27451. "Basic", {"Authorization"}, true);
  27452. }
  27453. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27454. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27455. [](SSLClient &cli) {
  27456. cli.set_proxy_bearer_token_auth("proxy-token");
  27457. cli.set_bearer_token_auth("origin-token");
  27458. },
  27459. "Bearer");
  27460. }
  27461. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27462. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27463. [](SSLClient &cli) {
  27464. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27465. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27466. {"Cookie", "sid=origin-session"},
  27467. {"X-Api-Key", "origin-key"}});
  27468. },
  27469. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27470. }
  27471. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27472. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27473. // retry; otherwise proxy creds would be sent to the origin.
  27474. std::atomic<int> origin_hits{0};
  27475. std::atomic<bool> origin_saw_proxy_authz{false};
  27476. proxy_tunnel_test::ScopedSSLServer origin;
  27477. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27478. origin_hits++;
  27479. if (req.has_header("Proxy-Authorization")) {
  27480. origin_saw_proxy_authz = true;
  27481. }
  27482. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27483. res.set_header("Proxy-Authenticate",
  27484. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27485. "algorithm=MD5");
  27486. });
  27487. origin.listen();
  27488. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27489. ASSERT_NE(0, proxy.port());
  27490. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27491. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27492. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27493. // and answer with its own status, making this test flaky.
  27494. SSLClient cli("127.0.0.1", origin.port());
  27495. cli.enable_server_certificate_verification(false);
  27496. cli.set_proxy("127.0.0.1", proxy.port());
  27497. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27498. auto res = cli.Get("/x");
  27499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27500. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27501. EXPECT_EQ(1, origin_hits.load());
  27502. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27503. EXPECT_EQ(1, proxy.connect_hits());
  27504. }
  27505. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27506. std::string origin_sni;
  27507. std::string origin_host;
  27508. proxy_tunnel_test::ScopedSSLServer origin;
  27509. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27510. origin_sni = req.sni();
  27511. origin_host = req.get_header_value("Host");
  27512. res.set_content("ok", "text/plain");
  27513. });
  27514. origin.listen();
  27515. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27516. ASSERT_NE(0, proxy.port());
  27517. SSLClient cli("origin.example", origin.port());
  27518. cli.enable_server_certificate_verification(false);
  27519. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27520. cli.set_proxy("127.0.0.1", proxy.port());
  27521. auto res = cli.Get("/x");
  27522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27523. EXPECT_EQ(StatusCode::OK_200, res->status);
  27524. auto port = std::to_string(origin.port());
  27525. auto target = "127.0.0.1:" + port;
  27526. auto connect_req = proxy.connect_request();
  27527. EXPECT_EQ(1, proxy.connect_hits());
  27528. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27529. EXPECT_NE(std::string::npos,
  27530. connect_req.find("\r\nHost: " + target + "\r\n"));
  27531. EXPECT_EQ("origin.example", origin_sni);
  27532. EXPECT_EQ("origin.example:" + port, origin_host);
  27533. }
  27534. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27535. proxy_tunnel_test::ScopedSSLServer origin;
  27536. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27537. res.set_content("ok", "text/plain");
  27538. });
  27539. origin.listen();
  27540. proxy_tunnel_test::ScopedConnectProxy proxy(
  27541. origin.port(), [](const std::string &head) -> std::string {
  27542. if (head.find(
  27543. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27544. std::string::npos) {
  27545. return proxy_tunnel_test::kTunnelEstablished;
  27546. }
  27547. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27548. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27549. "nonce=\"abc\", algorithm=MD5\r\n"
  27550. "Content-Length: 0\r\n\r\n";
  27551. });
  27552. ASSERT_NE(0, proxy.port());
  27553. SSLClient cli("origin.example", origin.port());
  27554. cli.enable_server_certificate_verification(false);
  27555. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27556. cli.set_proxy("127.0.0.1", proxy.port());
  27557. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27558. auto res = cli.Get("/x");
  27559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27560. EXPECT_EQ(StatusCode::OK_200, res->status);
  27561. // The retried CONNECT is the one the proxy saw last.
  27562. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27563. auto connect_req = proxy.connect_request();
  27564. EXPECT_EQ(2, proxy.connect_hits());
  27565. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27566. EXPECT_NE(std::string::npos,
  27567. connect_req.find("\r\nHost: " + target + "\r\n"));
  27568. }
  27569. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27570. proxy_tunnel_test::ScopedSSLServer origin;
  27571. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27572. res.set_content("ok", "text/plain");
  27573. });
  27574. origin.listen();
  27575. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27576. ASSERT_NE(0, proxy.port());
  27577. SSLClient cli("origin.example", origin.port());
  27578. cli.enable_server_certificate_verification(false);
  27579. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27580. cli.set_proxy("127.0.0.1", proxy.port());
  27581. auto res = cli.Get("/x");
  27582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27583. EXPECT_EQ(StatusCode::OK_200, res->status);
  27584. auto target = "origin.example:" + std::to_string(origin.port());
  27585. auto connect_req = proxy.connect_request();
  27586. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27587. EXPECT_NE(std::string::npos,
  27588. connect_req.find("\r\nHost: " + target + "\r\n"));
  27589. }
  27590. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27591. proxy_tunnel_test::ScopedSSLServer origin;
  27592. auto port = std::to_string(origin.port());
  27593. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27594. res.set_redirect("https://next.example:" + port + "/y");
  27595. });
  27596. origin.svr().Get("/y", [](const Request &, Response &res) {
  27597. res.set_content("ok", "text/plain");
  27598. });
  27599. origin.listen();
  27600. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27601. ASSERT_NE(0, proxy.port());
  27602. SSLClient cli("origin.example", origin.port());
  27603. cli.enable_server_certificate_verification(false);
  27604. cli.set_tunnel_hostname_addr_map(
  27605. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27606. cli.set_proxy("127.0.0.1", proxy.port());
  27607. cli.set_follow_location(true);
  27608. auto res = cli.Get("/x");
  27609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27610. EXPECT_EQ("ok", res->body);
  27611. // The last CONNECT is the redirect client's.
  27612. ASSERT_EQ(2, proxy.connect_hits());
  27613. auto target = "127.0.0.1:" + port;
  27614. auto connect_req = proxy.connect_request();
  27615. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27616. EXPECT_NE(std::string::npos,
  27617. connect_req.find("\r\nHost: " + target + "\r\n"));
  27618. }
  27619. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  27620. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  27621. std::atomic<int> origin_hits{0};
  27622. proxy_tunnel_test::ScopedSSLServer origin;
  27623. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27624. origin_hits++;
  27625. res.set_content("ok", "text/plain");
  27626. });
  27627. origin.listen();
  27628. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27629. ASSERT_NE(0, proxy.port());
  27630. SSLClient cli("127.0.0.1", origin.port());
  27631. cli.enable_server_certificate_verification(false);
  27632. cli.set_proxy("127.0.0.1", proxy.port());
  27633. cli.set_keep_alive(true);
  27634. cli.set_session_verifier(
  27635. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  27636. auto res = cli.Get("/x");
  27637. EXPECT_FALSE(res);
  27638. ASSERT_FALSE(cli.is_socket_open());
  27639. res = cli.Get("/x");
  27640. EXPECT_FALSE(res);
  27641. EXPECT_EQ(2, proxy.connect_hits());
  27642. auto handle = cli.open_stream("GET", "/x");
  27643. EXPECT_FALSE(handle.is_valid());
  27644. EXPECT_EQ(3, proxy.connect_hits());
  27645. EXPECT_EQ(0, origin_hits.load());
  27646. }
  27647. #endif
  27648. namespace proxy_tunnel_test {
  27649. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27650. // anything else gets a 407 with `challenge`.
  27651. ConnectReply require_proxy_auth(const std::string &expected,
  27652. const std::string &challenge) {
  27653. return [=](const std::string &head) -> std::string {
  27654. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27655. std::string::npos) {
  27656. return kTunnelEstablished;
  27657. }
  27658. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27659. "Proxy-Authenticate: " +
  27660. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27661. };
  27662. }
  27663. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27664. // request, then echoes.
  27665. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27666. ws.send(
  27667. "authorization:" + req.get_header_value("Authorization") +
  27668. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27669. std::string msg;
  27670. while (ws.read(msg)) {
  27671. ws.send(msg);
  27672. }
  27673. }
  27674. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27675. class ScopedWebSocketOrigin {
  27676. public:
  27677. ScopedWebSocketOrigin() {
  27678. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27679. server_.listen();
  27680. }
  27681. int port() const { return server_.port(); }
  27682. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27683. std::string url() const {
  27684. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27685. }
  27686. private:
  27687. no_proxy_test::ScopedServer server_;
  27688. };
  27689. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27690. // passed as a constructor header, and checks that each reaches only its hop.
  27691. void WebSocketCredentialsStayWithTheirHop(
  27692. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27693. const std::string &proxy_authz, const std::string &origin_authz) {
  27694. ScopedWebSocketOrigin origin;
  27695. ScopedConnectProxy proxy(
  27696. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27697. ASSERT_NE(0, proxy.port());
  27698. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27699. client.set_proxy("127.0.0.1", proxy.port());
  27700. set_proxy_credentials(client);
  27701. auto res = client.connect();
  27702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27703. std::string msg;
  27704. ASSERT_TRUE(client.read(msg));
  27705. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27706. client.close();
  27707. EXPECT_EQ(1, proxy.connect_hits());
  27708. EXPECT_EQ(std::string::npos,
  27709. proxy.connect_request().find("\r\nAuthorization: "))
  27710. << "origin credentials must not be sent to the proxy";
  27711. }
  27712. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  27713. void WebSocketSetterCredentialsStayWithTheirHop(
  27714. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  27715. const std::string &proxy_authz, const std::string &origin_authz) {
  27716. ScopedWebSocketOrigin origin;
  27717. ScopedConnectProxy proxy(
  27718. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27719. ASSERT_NE(0, proxy.port());
  27720. ws::WebSocketClient client(origin.url());
  27721. client.set_proxy("127.0.0.1", proxy.port());
  27722. set_credentials(client);
  27723. auto res = client.connect();
  27724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27725. std::string msg;
  27726. ASSERT_TRUE(client.read(msg));
  27727. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27728. client.close();
  27729. EXPECT_EQ(1, proxy.connect_hits());
  27730. EXPECT_EQ(std::string::npos,
  27731. proxy.connect_request().find("\r\nAuthorization: "))
  27732. << "origin credentials must not be sent to the proxy";
  27733. }
  27734. } // namespace proxy_tunnel_test
  27735. namespace {
  27736. // Connects `client` and returns the Authorization header its upgrade
  27737. // request carried, or "<failed>" when the connection could not be opened.
  27738. std::string websocket_authorization(ws::WebSocketClient &client) {
  27739. if (!client.connect()) { return "<failed>"; }
  27740. std::string msg;
  27741. if (!client.read(msg)) { return "<failed>"; }
  27742. client.close();
  27743. auto prefix = std::string("authorization:");
  27744. auto end = msg.find("|proxy-authorization:");
  27745. return msg.substr(prefix.size(), end - prefix.size());
  27746. }
  27747. } // namespace
  27748. TEST(WebSocketClientAuthTest, BasicAuth) {
  27749. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27750. ws::WebSocketClient client(origin.url());
  27751. client.set_basic_auth("user", "pass");
  27752. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27753. websocket_authorization(client));
  27754. }
  27755. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  27756. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27757. ws::WebSocketClient client(origin.url());
  27758. client.set_basic_auth("user", "");
  27759. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  27760. websocket_authorization(client));
  27761. }
  27762. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  27763. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27764. ws::WebSocketClient client(origin.url());
  27765. client.set_bearer_token_auth("token123");
  27766. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  27767. }
  27768. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  27769. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27770. ws::WebSocketClient client(origin.url());
  27771. client.set_bearer_token_auth("token123");
  27772. client.set_basic_auth("user", "pass");
  27773. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27774. websocket_authorization(client));
  27775. }
  27776. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  27777. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27778. ws::WebSocketClient client(origin.url(),
  27779. {{"Authorization", "Bearer from-header"}});
  27780. client.set_bearer_token_auth("from-setter");
  27781. client.set_basic_auth("user", "pass");
  27782. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  27783. }
  27784. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  27785. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27786. ws::WebSocketClient client(origin.url());
  27787. EXPECT_EQ("", websocket_authorization(client));
  27788. client.set_bearer_token_auth("first");
  27789. EXPECT_EQ("Bearer first", websocket_authorization(client));
  27790. client.set_bearer_token_auth("second");
  27791. EXPECT_EQ("Bearer second", websocket_authorization(client));
  27792. client.set_bearer_token_auth("");
  27793. EXPECT_EQ("", websocket_authorization(client));
  27794. }
  27795. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27796. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27797. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27798. ASSERT_NE(0, proxy.port());
  27799. ws::WebSocketClient client(origin.url());
  27800. client.set_proxy("127.0.0.1", proxy.port());
  27801. auto res = client.connect();
  27802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27803. std::string msg;
  27804. ASSERT_TRUE(client.read(msg));
  27805. ASSERT_TRUE(client.send("hello"));
  27806. ASSERT_TRUE(client.read(msg));
  27807. EXPECT_EQ("hello", msg);
  27808. client.close();
  27809. EXPECT_EQ(1, proxy.connect_hits());
  27810. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27811. auto connect_req = proxy.connect_request();
  27812. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27813. EXPECT_NE(std::string::npos,
  27814. connect_req.find("\r\nHost: " + target + "\r\n"));
  27815. }
  27816. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27817. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27818. [](ws::WebSocketClient &cli) {
  27819. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27820. },
  27821. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27822. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27823. }
  27824. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27825. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27826. [](ws::WebSocketClient &cli) {
  27827. cli.set_proxy_bearer_token_auth("proxy-token");
  27828. },
  27829. "Bearer proxy-token", "Bearer origin-token");
  27830. }
  27831. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  27832. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27833. [](ws::WebSocketClient &cli) {
  27834. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27835. cli.set_basic_auth("origin-user", "origin-pass");
  27836. },
  27837. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27838. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27839. }
  27840. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  27841. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27842. [](ws::WebSocketClient &cli) {
  27843. cli.set_proxy_bearer_token_auth("proxy-token");
  27844. cli.set_bearer_token_auth("origin-token");
  27845. },
  27846. "Bearer proxy-token", "Bearer origin-token");
  27847. }
  27848. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27849. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27850. proxy_tunnel_test::ScopedConnectProxy proxy(
  27851. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27852. "Basic " + detail::base64_encode("proxy-user:"),
  27853. "Basic realm=\"proxy\""));
  27854. ASSERT_NE(0, proxy.port());
  27855. ws::WebSocketClient client(origin.url());
  27856. client.set_proxy("127.0.0.1", proxy.port());
  27857. client.set_proxy_basic_auth("proxy-user", "");
  27858. auto res = client.connect();
  27859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27860. client.close();
  27861. EXPECT_EQ(1, proxy.connect_hits());
  27862. }
  27863. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27864. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27865. proxy_tunnel_test::ScopedConnectProxy proxy(
  27866. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27867. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27868. ASSERT_NE(0, proxy.port());
  27869. ws::WebSocketClient client(origin.url());
  27870. client.set_proxy("127.0.0.1", proxy.port());
  27871. auto res = client.connect();
  27872. EXPECT_FALSE(res);
  27873. EXPECT_EQ(Error::ProxyConnection, res.error());
  27874. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27875. EXPECT_EQ("Basic realm=\"proxy\"",
  27876. res.get_header_value("Proxy-Authenticate"));
  27877. EXPECT_FALSE(client.is_open());
  27878. }
  27879. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27880. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27881. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27882. ASSERT_NE(0, proxy.port());
  27883. ws::WebSocketClient client(origin.url());
  27884. client.set_proxy("127.0.0.1", proxy.port());
  27885. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27886. client.set_no_proxy({"127.0.0.1"});
  27887. auto res = client.connect();
  27888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27889. std::string msg;
  27890. ASSERT_TRUE(client.read(msg));
  27891. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27892. << "proxy credentials must not reach a bypassed origin";
  27893. client.close();
  27894. EXPECT_EQ(0, proxy.connect_hits());
  27895. }
  27896. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27897. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27898. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27899. ASSERT_NE(0, proxy.port());
  27900. ws::WebSocketClient client(origin.url());
  27901. client.set_proxy("127.0.0.1", proxy.port());
  27902. ASSERT_TRUE(client.connect());
  27903. ASSERT_TRUE(client.connect());
  27904. client.close();
  27905. EXPECT_EQ(2, proxy.connect_hits());
  27906. }
  27907. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27908. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27909. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27910. ASSERT_NE(0, proxy.port());
  27911. auto port = std::to_string(origin.port());
  27912. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27913. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27914. client.set_proxy("127.0.0.1", proxy.port());
  27915. auto res = client.connect();
  27916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27917. std::string msg;
  27918. ASSERT_TRUE(client.read(msg));
  27919. client.close();
  27920. EXPECT_EQ(1, proxy.connect_hits());
  27921. auto target = "127.0.0.1:" + port;
  27922. auto connect_req = proxy.connect_request();
  27923. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27924. EXPECT_NE(std::string::npos,
  27925. connect_req.find("\r\nHost: " + target + "\r\n"));
  27926. }
  27927. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27928. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27929. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27930. ASSERT_NE(0, proxy.port());
  27931. auto port = std::to_string(origin.port());
  27932. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27933. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27934. client.set_proxy("127.0.0.1", proxy.port());
  27935. auto res = client.connect();
  27936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27937. client.close();
  27938. auto target = "origin.example:" + port;
  27939. auto connect_req = proxy.connect_request();
  27940. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27941. EXPECT_NE(std::string::npos,
  27942. connect_req.find("\r\nHost: " + target + "\r\n"));
  27943. }
  27944. #ifdef CPPHTTPLIB_SSL_ENABLED
  27945. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27946. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27947. proxy_tunnel_test::ScopedConnectProxy proxy(
  27948. origin.port(), [](const std::string &head) -> std::string {
  27949. if (head.find(
  27950. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27951. std::string::npos) {
  27952. return proxy_tunnel_test::kTunnelEstablished;
  27953. }
  27954. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27955. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27956. "nonce=\"abc\", algorithm=MD5\r\n"
  27957. "Content-Length: 0\r\n\r\n";
  27958. });
  27959. ASSERT_NE(0, proxy.port());
  27960. ws::WebSocketClient client(origin.url());
  27961. client.set_proxy("127.0.0.1", proxy.port());
  27962. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27963. auto res = client.connect();
  27964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27965. std::string msg;
  27966. ASSERT_TRUE(client.read(msg));
  27967. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27968. client.close();
  27969. EXPECT_EQ(2, proxy.connect_hits());
  27970. }
  27971. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27972. proxy_tunnel_test::ScopedSSLServer origin;
  27973. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27974. origin.listen();
  27975. proxy_tunnel_test::ScopedConnectProxy proxy(
  27976. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27977. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27978. ASSERT_NE(0, proxy.port());
  27979. ws::WebSocketClient client(
  27980. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27981. client.enable_server_certificate_verification(false);
  27982. client.set_proxy("127.0.0.1", proxy.port());
  27983. client.set_proxy_bearer_token_auth("proxy-token");
  27984. auto res = client.connect();
  27985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27986. std::string msg;
  27987. ASSERT_TRUE(client.read(msg));
  27988. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27989. << "Proxy-Authorization must not be sent inside the tunnel";
  27990. client.close();
  27991. EXPECT_EQ(1, proxy.connect_hits());
  27992. }
  27993. #endif