1
0

test.cc 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809
  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. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  71. namespace impl {
  72. SecTrustSettingsResult
  73. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  74. } // namespace impl
  75. #endif
  76. } // namespace tls
  77. } // namespace httplib
  78. #endif
  79. using namespace std;
  80. using namespace httplib;
  81. const char *HOST = "localhost";
  82. static int get_base_port() {
  83. const char *shard = getenv("GTEST_SHARD_INDEX");
  84. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  85. }
  86. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  87. // New standalone tests MUST use svr.bind_to_any_port() instead.
  88. const int PORT = get_base_port();
  89. const string LONG_QUERY_VALUE = string(25000, '@');
  90. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  91. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  92. const string TOO_LONG_QUERY_URL =
  93. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  94. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  95. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  96. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  97. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  98. return file.name == key;
  99. });
  100. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  101. return *it;
  102. #else
  103. if (it != items.end()) { return *it; }
  104. throw std::runtime_error("invalid multipart form data name error");
  105. #endif
  106. }
  107. static void read_file(const std::string &path, std::string &out) {
  108. std::ifstream fs(path, std::ios_base::binary);
  109. if (!fs) {
  110. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  111. return;
  112. #else
  113. throw std::runtime_error("File not found: " + path);
  114. #endif
  115. }
  116. fs.seekg(0, std::ios_base::end);
  117. auto size = fs.tellg();
  118. fs.seekg(0);
  119. out.resize(static_cast<size_t>(size));
  120. fs.read(&out[0], static_cast<std::streamsize>(size));
  121. }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. static std::string make_sock_path() {
  136. const char *shard = getenv("GTEST_SHARD_INDEX");
  137. return shard ? std::string("./httplib-server-") + shard + ".sock"
  138. : "./httplib-server.sock";
  139. }
  140. const std::string pathname_{make_sock_path()};
  141. const std::string pattern_{"/hi"};
  142. const std::string content_{"Hello World!"};
  143. };
  144. TEST_F(UnixSocketTest, pathname) {
  145. httplib::Server svr;
  146. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  147. res.set_content(content_, "text/plain");
  148. });
  149. std::thread t{[&] {
  150. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  151. }};
  152. auto se = detail::scope_exit([&] {
  153. svr.stop();
  154. t.join();
  155. ASSERT_FALSE(svr.is_running());
  156. });
  157. svr.wait_until_ready();
  158. ASSERT_TRUE(svr.is_running());
  159. client_GET(pathname_);
  160. // ".//x.sock", which is not taken for a URL
  161. client_GET("./" + pathname_.substr(1));
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_TRUE(s0.is_peer_alive());
  254. EXPECT_EQ(0, close(fds[1]));
  255. EXPECT_FALSE(s0.is_peer_alive());
  256. return true;
  257. });
  258. EXPECT_EQ(0, close(fds[0]));
  259. }
  260. TEST(SocketStream, wait_writable_INET) {
  261. sockaddr_in addr;
  262. memset(&addr, 0, sizeof(addr));
  263. addr.sin_family = AF_INET;
  264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  265. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  266. int disconnected_svr_sock = -1;
  267. std::thread svr{[&] {
  268. const int s = socket(AF_INET, SOCK_STREAM, 0);
  269. ASSERT_LE(0, s);
  270. // PORT + 1 is shared with the SSL redirect tests and with
  271. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  272. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  273. // because that happens on a worker thread the ASSERT does not stop the
  274. // test: it runs on and fails at the disconnected_svr_sock check instead.
  275. default_socket_options(s);
  276. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  277. ASSERT_EQ(0, listen(s, 1));
  278. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  282. std::thread cli{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, close(s));
  287. }};
  288. cli.join();
  289. svr.join();
  290. ASSERT_NE(disconnected_svr_sock, -1);
  291. const auto asSocketStream = [&](socket_t fd,
  292. std::function<bool(Stream &)> func) {
  293. return detail::process_client_socket(
  294. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  295. };
  296. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  297. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  298. // wait_writable() returns true because select_write() only checks if the
  299. // send buffer has space. Peer disconnection is detected later by send().
  300. EXPECT_TRUE(ss.wait_writable());
  301. return true;
  302. });
  303. ASSERT_EQ(0, close(disconnected_svr_sock));
  304. }
  305. #endif // #ifndef _WIN32
  306. TEST(SetSocketOptTest, TcpNoDelay) {
  307. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  308. ASSERT_NE(sock, INVALID_SOCKET);
  309. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  310. int val = 0;
  311. socklen_t len = sizeof(val);
  312. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  313. reinterpret_cast<char *>(&val), &len));
  314. EXPECT_NE(val, 0);
  315. detail::close_socket(sock);
  316. }
  317. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  318. // accept() reports failures through WSAGetLastError() on Windows and through
  319. // errno everywhere else. Asking the wrong one is what made the accept loop
  320. // treat every recoverable failure as fatal on Windows.
  321. struct Classification {
  322. bool resource;
  323. bool transient;
  324. };
  325. auto classify = [](int err) {
  326. #ifdef _WIN32
  327. WSASetLastError(err);
  328. #else
  329. errno = err;
  330. #endif
  331. // Read both before asserting: an assertion may clobber the error slot.
  332. Classification c;
  333. c.resource = detail::is_accept_resource_error();
  334. c.transient = detail::is_accept_transient_error();
  335. return c;
  336. };
  337. #ifdef _WIN32
  338. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  339. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  340. WSAECONNRESET, WSAECONNABORTED};
  341. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  342. #else
  343. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  344. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  345. ECONNABORTED};
  346. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  347. #endif
  348. for (auto err : resource_errors) {
  349. const auto c = classify(err);
  350. EXPECT_TRUE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. for (auto err : transient_errors) {
  354. const auto c = classify(err);
  355. EXPECT_TRUE(c.transient) << "error " << err;
  356. EXPECT_FALSE(c.resource) << "error " << err;
  357. }
  358. for (auto err : fatal_errors) {
  359. const auto c = classify(err);
  360. EXPECT_FALSE(c.resource) << "error " << err;
  361. EXPECT_FALSE(c.transient) << "error " << err;
  362. }
  363. #ifdef _WIN32
  364. WSASetLastError(0);
  365. #else
  366. errno = 0;
  367. #endif
  368. }
  369. TEST(ClientTest, MoveConstructible) {
  370. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  371. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  372. }
  373. TEST(ClientTest, MoveAssignable) {
  374. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  375. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  376. }
  377. #ifdef _WIN32
  378. TEST(StartupTest, WSAStartup) {
  379. WSADATA wsaData;
  380. int ret = WSAStartup(0x0002, &wsaData);
  381. ASSERT_EQ(0, ret);
  382. }
  383. #endif
  384. TEST(DecodePathTest, PercentCharacter) {
  385. EXPECT_EQ(
  386. decode_path_component(
  387. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  388. U8("descrip=Gastos áéíóúñÑ 6"));
  389. }
  390. TEST(DecodePathTest, PercentCharacterNUL) {
  391. string expected;
  392. expected.push_back('x');
  393. expected.push_back('\0');
  394. expected.push_back('x');
  395. EXPECT_EQ(decode_path_component("x%00x"), expected);
  396. }
  397. TEST(DecodePathTest, UnicodeEncoding) {
  398. // %u0041 = 'A' (1-byte UTF-8)
  399. EXPECT_EQ("A", decode_path_component("%u0041"));
  400. // %u00E9 = 'é' (2-byte UTF-8)
  401. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  402. // %u3042 = 'あ' (3-byte UTF-8)
  403. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  404. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  405. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  406. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  407. // neighbours)
  408. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  409. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  410. }
  411. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  412. // A sign or whitespace inside the two-character escape window must not be
  413. // accepted as a valid percent-encoding; the sequence is passed through
  414. // literally, matching decode_uri_component / decode_path_component.
  415. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  416. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  417. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  418. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  419. // Well-formed escapes still decode.
  420. EXPECT_EQ("-", decode_query_component("%2D", false));
  421. EXPECT_EQ("A", decode_query_component("%41", false));
  422. }
  423. TEST(SanitizeFilenameTest, VariousPatterns) {
  424. // Path traversal
  425. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  426. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  427. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  428. // Normal and edge cases
  429. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  430. EXPECT_EQ("filename.txt",
  431. httplib::sanitize_filename("/path/to/filename.txt"));
  432. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  433. EXPECT_EQ("", httplib::sanitize_filename(".."));
  434. EXPECT_EQ("", httplib::sanitize_filename(""));
  435. // Null bytes stripped
  436. EXPECT_EQ("safe.txt",
  437. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  438. // Whitespace-only rejected
  439. EXPECT_EQ("", httplib::sanitize_filename(" "));
  440. }
  441. // Forward declaration (see the base64_encode note below): split builds move the
  442. // definition into httplib.cc, so re-declaring it here lets the test link.
  443. namespace httplib {
  444. namespace detail {
  445. bool is_chunked_transfer_encoding(const Headers &headers);
  446. } // namespace detail
  447. } // namespace httplib
  448. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  449. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  450. auto make = [](std::initializer_list<const char *> lines) {
  451. Headers h;
  452. for (auto te : lines) {
  453. if (te) { h.emplace("Transfer-Encoding", te); }
  454. }
  455. return h;
  456. };
  457. // Sole coding, matched case-insensitively.
  458. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  460. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  461. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  462. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  464. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  465. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  466. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  470. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  471. // were received, into one list. Headers preserves that order, so the answer
  472. // is decided by the last coding of the last line and the order the lines
  473. // arrived in is significant.
  474. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  475. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  477. // The split can fall anywhere in the list.
  478. EXPECT_TRUE(
  479. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  480. EXPECT_FALSE(
  481. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  482. // A trailing line naming no coding leaves the list ending in nothing, so it
  483. // must not inherit the chunked from the line before it.
  484. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  485. }
  486. // Forward declarations (see the base64_encode note below).
  487. namespace httplib {
  488. namespace detail {
  489. bool parse_status_line(const char *line, std::string &version, int &status,
  490. std::string &reason);
  491. std::string file_extension(const std::string &path);
  492. std::string
  493. find_content_type(const std::string &path,
  494. const std::map<std::string, std::string> &user_data,
  495. const std::string &default_content_type);
  496. bool can_compress_content_type(const std::string &content_type);
  497. bool is_prohibited_header_name(const std::string &name);
  498. bool is_valid_path(const std::string &path);
  499. #ifdef CPPHTTPLIB_SSL_ENABLED
  500. bool match_hostname(const std::string &pattern, const std::string &hostname);
  501. #endif
  502. } // namespace detail
  503. } // namespace httplib
  504. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  505. struct {
  506. const char *line;
  507. const char *version;
  508. int status;
  509. const char *reason;
  510. } cases[] = {
  511. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  512. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  513. // The reason phrase may be empty, or left out along with its space.
  514. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  515. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  516. };
  517. for (const auto &c : cases) {
  518. std::string version;
  519. int status = 0;
  520. std::string reason = "unset";
  521. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  522. << c.line;
  523. EXPECT_EQ(c.version, version);
  524. EXPECT_EQ(c.status, status);
  525. EXPECT_EQ(c.reason, reason);
  526. }
  527. }
  528. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  529. const char *lines[] = {
  530. "HTTP/2 200 OK\r\n",
  531. "HTTP/1.2 200 OK\r\n",
  532. "HTTP/1.1 20 OK\r\n",
  533. "HTTP/1.1 2000 OK\r\n",
  534. "HTTP/1.1 2x0 OK\r\n",
  535. "HTTP/1.1 200 OK\r\n",
  536. "HTTP/1.1 200OK\r\n",
  537. "HTTP/1.1 200 O\rK\r\n",
  538. "HTTP/1.1 200 OK",
  539. "HTTP/1.1 200 OK\r\nX",
  540. "",
  541. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  542. "HTTP/1.1 200 OK\n",
  543. #endif
  544. };
  545. for (auto line : lines) {
  546. std::string version;
  547. int status = 0;
  548. std::string reason;
  549. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  550. << line;
  551. }
  552. }
  553. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  554. // Long enough to overflow the stack when matched with std::regex.
  555. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  556. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  557. std::string version;
  558. int status = 0;
  559. std::string reason;
  560. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  561. EXPECT_EQ(200, status);
  562. EXPECT_EQ(long_reason, reason);
  563. }
  564. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  565. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  566. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  567. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  568. EXPECT_EQ("", detail::file_extension("noext"));
  569. EXPECT_EQ("", detail::file_extension("a."));
  570. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  571. EXPECT_EQ("", detail::file_extension("a.b-c"));
  572. // Long enough to overflow the stack when matched with std::regex.
  573. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  574. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  575. }
  576. #ifdef CPPHTTPLIB_SSL_ENABLED
  577. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  578. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  579. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  580. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  581. // A wildcard needs two labels after it, in the leftmost label only
  582. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  583. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  584. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  585. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  586. EXPECT_FALSE(
  587. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  588. // No name may have an empty label
  589. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  590. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  591. }
  592. #endif
  593. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  594. detail::case_ignore::hash hash;
  595. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  596. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  597. // Long enough to overflow the stack if hashed one call per character.
  598. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  599. }
  600. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  601. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  602. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  603. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  604. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  605. // Same 26-bit hash as html, svg and js.
  606. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  607. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  608. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  609. }
  610. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  611. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  612. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  613. }
  614. }
  615. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  616. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  617. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  618. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  619. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  620. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  621. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  622. // Same 26-bit hash as application/json.
  623. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  624. }
  625. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  626. Request req;
  627. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  628. EXPECT_TRUE(req.is_multipart_form_data());
  629. std::string boundary;
  630. EXPECT_TRUE(detail::parse_multipart_boundary(
  631. req.get_header_value("Content-Type"), boundary));
  632. EXPECT_EQ("x", boundary);
  633. }
  634. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  635. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  636. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  637. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  638. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  639. // Same 26-bit hash as REMOTE_ADDR.
  640. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  641. }
  642. // Forward declaration: in split builds split.py strips `inline` and moves the
  643. // definition into httplib.cc, so detail::base64_encode is not visible from the
  644. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  645. // in both header-only and split builds.
  646. namespace httplib {
  647. namespace detail {
  648. std::string base64_encode(const std::string &in);
  649. } // namespace detail
  650. } // namespace httplib
  651. TEST(Base64EncodeTest, KnownAnswers) {
  652. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  653. // where the accumulator's top bit is already set before the next shift.
  654. EXPECT_EQ("", detail::base64_encode(""));
  655. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  656. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  657. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  658. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  659. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  660. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  661. // High bytes keep the top bit set across several rounds.
  662. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  663. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  664. }
  665. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  666. string unescapedCharacters = "-_.!~*'()";
  667. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  668. }
  669. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  670. string reservedCharacters = ";,/?:@&=+$";
  671. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  672. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  673. }
  674. TEST(ClientQueryOrder, PreserveOrder) {
  675. // This test reproduces Issue #2259: client may reorder query parameters
  676. // when sending a GET request. The expected behavior is that the client
  677. // preserves the original query string order when the caller supplied it
  678. // as part of the path.
  679. Server svr;
  680. svr.Get("/", [&](const Request &req, Response &res) {
  681. // Echo back the raw target so the test can assert ordering
  682. res.set_content(req.target, "text/plain");
  683. });
  684. std::thread t{[&] { svr.listen(HOST, PORT); }};
  685. auto se = detail::scope_exit([&] {
  686. svr.stop();
  687. t.join();
  688. ASSERT_FALSE(svr.is_running());
  689. });
  690. svr.wait_until_ready();
  691. Client cli(HOST, PORT);
  692. ASSERT_TRUE(cli.is_valid());
  693. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  694. auto res = cli.Get(original);
  695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  696. // Expect the echoed target to exactly match the original path (order
  697. // preserved)
  698. EXPECT_EQ(res->body, original);
  699. }
  700. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  701. string chineseCharacters = U8("中国語");
  702. string russianCharacters = U8("дом");
  703. string brazilianCharacters = U8("óculos");
  704. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  705. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  706. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  707. "%D0%B4%D0%BE%D0%BC");
  708. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  709. }
  710. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  711. string unescapedCharacters = "-_.!~*'()";
  712. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  713. }
  714. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  715. string reservedCharacters = ";,/?:@&=+$";
  716. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  717. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  718. }
  719. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  720. string chineseCharacters = U8("中国語");
  721. string russianCharacters = U8("дом");
  722. string brazilianCharacters = U8("óculos");
  723. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  724. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  725. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  726. "%D0%B4%D0%BE%D0%BC");
  727. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  728. }
  729. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  730. // Issue #2082 use case: encoding path component with ampersand
  731. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  732. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  733. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  734. }
  735. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  736. string unescapedCharacters = "-_.!~*'()";
  737. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  738. }
  739. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  740. string reservedCharacters = ";,/?:@&=+$#";
  741. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  742. }
  743. TEST(EncodeUriTest, TestUTF8Characters) {
  744. string chineseCharacters = U8("中国語");
  745. string russianCharacters = U8("дом");
  746. string brazilianCharacters = U8("óculos");
  747. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  748. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  749. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  750. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  751. }
  752. TEST(EncodeUriTest, TestCompleteUri) {
  753. string uri =
  754. "https://example.com/path/to/resource?query=value&param=test#fragment";
  755. EXPECT_EQ(
  756. httplib::encode_uri(uri),
  757. "https://example.com/path/to/resource?query=value&param=test#fragment");
  758. }
  759. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  760. string uri =
  761. "https://example.com/path with spaces/file name.html?q=hello world";
  762. EXPECT_EQ(httplib::encode_uri(uri),
  763. "https://example.com/path%20with%20spaces/"
  764. "file%20name.html?q=hello%20world");
  765. }
  766. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  767. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  768. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  769. }
  770. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  775. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  776. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  777. string encodedBrazilian = "%C3%B3culos";
  778. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  779. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  780. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  781. }
  782. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  783. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  784. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  785. "Piri Tommy Villiers - on & on");
  786. }
  787. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  788. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  789. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  790. }
  791. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  792. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  793. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  794. }
  795. TEST(DecodeUriTest, TestUTF8Characters) {
  796. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  797. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  798. string encodedBrazilian = "%C3%B3culos";
  799. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  800. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  801. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  802. }
  803. TEST(DecodeUriTest, TestCompleteUri) {
  804. string encodedUri = "https://example.com/path%20with%20spaces/"
  805. "file%20name.html?q=hello%20world";
  806. EXPECT_EQ(
  807. httplib::decode_uri(encodedUri),
  808. "https://example.com/path with spaces/file name.html?q=hello world");
  809. }
  810. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  811. string original =
  812. "https://example.com/path with spaces/file name.html?q=hello world";
  813. string encoded = httplib::encode_uri(original);
  814. string decoded = httplib::decode_uri(encoded);
  815. EXPECT_EQ(decoded, original);
  816. }
  817. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  818. // decode_uri is the inverse of encode_uri: an escaped reserved character
  819. // stays encoded so it is not promoted into a real delimiter, while
  820. // non-reserved escapes still decode (like JS decodeURI).
  821. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  822. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  823. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  824. "%3F%3A%40%26%3D%2B%24%2C%3B");
  825. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  826. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  827. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  828. "http://example.com/a%2Fb");
  829. // decode_uri_component still decodes the reserved character.
  830. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  831. }
  832. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  833. string original = "Piri Tommy Villiers - on & on";
  834. string encoded = httplib::encode_uri_component(original);
  835. string decoded = httplib::decode_uri_component(encoded);
  836. EXPECT_EQ(decoded, original);
  837. }
  838. TEST(TrimTests, TrimStringTests) {
  839. EXPECT_EQ("abc", detail::trim_copy("abc"));
  840. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  841. EXPECT_TRUE(detail::trim_copy("").empty());
  842. }
  843. TEST(AsciiTest, LocaleIndependentClassification) {
  844. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  845. // which consult the global C locale: std::isalnum(0xC5) can return true
  846. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  847. // helpers must classify every byte by the ASCII grammar alone.
  848. for (int i = 0; i < 256; i++) {
  849. auto c = static_cast<char>(i);
  850. auto is_digit = i >= '0' && i <= '9';
  851. auto is_upper = i >= 'A' && i <= 'Z';
  852. auto is_lower = i >= 'a' && i <= 'z';
  853. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  854. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  855. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  856. << "byte " << i;
  857. }
  858. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  859. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  860. // Non-ASCII bytes must be percent-encoded, never passed through as
  861. // alphanumeric.
  862. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  863. }
  864. TEST(FromCharsTest, Double) {
  865. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  866. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  867. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  868. auto parse = [](const std::string &s, double &v) {
  869. return detail::from_chars(s.data(), s.data() + s.size(), v);
  870. };
  871. double v = -1.0;
  872. // Representative quality values.
  873. EXPECT_EQ(parse("0", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.0);
  875. EXPECT_EQ(parse("1", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 1.0);
  877. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.8);
  879. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  880. EXPECT_DOUBLE_EQ(v, 0.001);
  881. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 1.0);
  883. // A missing integer or fractional part is tolerated.
  884. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  885. EXPECT_DOUBLE_EQ(v, 0.5);
  886. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 5.0);
  888. // Values outside [0, 1] still parse; the caller range-checks them.
  889. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 123.456);
  891. // Stops at the first byte that is not part of the number and reports where.
  892. std::string trailing = "0.9, text/html";
  893. auto r = parse(trailing, v);
  894. EXPECT_EQ(r.ec, std::errc{});
  895. EXPECT_DOUBLE_EQ(v, 0.9);
  896. EXPECT_EQ(*r.ptr, ',');
  897. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  898. // outright, and an 'e'/'E' simply ends the number.
  899. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  900. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  901. std::string exp_input = "1.5e3";
  902. r = parse(exp_input, v);
  903. EXPECT_EQ(r.ec, std::errc{});
  904. EXPECT_DOUBLE_EQ(v, 1.5);
  905. EXPECT_EQ(*r.ptr, 'e');
  906. // Invalid inputs.
  907. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  908. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  909. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  910. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  911. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  912. // Pathological but well-formed inputs must stay bounded (no overflow, no
  913. // out-of-bounds table access) and stay within [0, 1] for the caller.
  914. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  915. std::errc{});
  916. EXPECT_DOUBLE_EQ(v, 0.0);
  917. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  918. std::errc{});
  919. EXPECT_GE(v, 0.0);
  920. EXPECT_LE(v, 1.0);
  921. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  922. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  923. }
  924. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  925. // Simple case without quality values
  926. std::vector<std::string> result1;
  927. EXPECT_TRUE(detail::parse_accept_header(
  928. "text/html,application/json,text/plain", result1));
  929. EXPECT_EQ(result1.size(), 3U);
  930. EXPECT_EQ(result1[0], "text/html");
  931. EXPECT_EQ(result1[1], "application/json");
  932. EXPECT_EQ(result1[2], "text/plain");
  933. // With quality values
  934. std::vector<std::string> result2;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  937. EXPECT_EQ(result2.size(), 3U);
  938. EXPECT_EQ(result2[0], "application/json"); // highest q value
  939. EXPECT_EQ(result2[1], "text/html");
  940. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  941. }
  942. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  943. // Mixed with and without quality values
  944. std::vector<std::string> result;
  945. EXPECT_TRUE(detail::parse_accept_header(
  946. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  947. EXPECT_EQ(result.size(), 3U);
  948. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  949. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  950. EXPECT_EQ(result[2], "application/json"); // q=0.5
  951. }
  952. TEST(ParseAcceptHeaderTest, EdgeCases) {
  953. // Empty header
  954. std::vector<std::string> empty_result;
  955. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  956. EXPECT_TRUE(empty_result.empty());
  957. // Single type
  958. std::vector<std::string> single_result;
  959. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  960. EXPECT_EQ(single_result.size(), 1U);
  961. EXPECT_EQ(single_result[0], "application/json");
  962. // Wildcard types
  963. std::vector<std::string> wildcard_result;
  964. EXPECT_TRUE(detail::parse_accept_header(
  965. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  966. EXPECT_EQ(wildcard_result.size(), 3U);
  967. EXPECT_EQ(wildcard_result[0], "application/json");
  968. EXPECT_EQ(wildcard_result[1], "text/*");
  969. EXPECT_EQ(wildcard_result[2], "*/*");
  970. }
  971. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  972. // Common browser Accept header
  973. std::vector<std::string> browser_result;
  974. EXPECT_TRUE(
  975. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  976. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  977. browser_result));
  978. EXPECT_EQ(browser_result.size(), 6U);
  979. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  980. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  981. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  982. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  983. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  984. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  985. // API client header
  986. std::vector<std::string> api_result;
  987. EXPECT_TRUE(detail::parse_accept_header(
  988. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  989. api_result));
  990. EXPECT_EQ(api_result.size(), 3U);
  991. EXPECT_EQ(api_result[0], "application/json");
  992. EXPECT_EQ(api_result[1], "application/xml");
  993. EXPECT_EQ(api_result[2], "text/plain");
  994. }
  995. TEST(ParseAcceptHeaderTest, SpecialCases) {
  996. // Quality value with 3 decimal places
  997. std::vector<std::string> decimal_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1000. EXPECT_EQ(decimal_result.size(), 2U);
  1001. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1002. EXPECT_EQ(decimal_result[1], "text/html");
  1003. // Zero quality (should still be included but with lowest priority)
  1004. std::vector<std::string> zero_q_result;
  1005. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1006. zero_q_result));
  1007. EXPECT_EQ(zero_q_result.size(), 2U);
  1008. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1009. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1010. // No spaces around commas
  1011. std::vector<std::string> no_space_result;
  1012. EXPECT_TRUE(detail::parse_accept_header(
  1013. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1014. no_space_result));
  1015. EXPECT_EQ(no_space_result.size(), 3U);
  1016. EXPECT_EQ(no_space_result[0], "text/html");
  1017. EXPECT_EQ(no_space_result[1], "application/json");
  1018. EXPECT_EQ(no_space_result[2], "text/plain");
  1019. }
  1020. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1021. // Quality values always use '.' as the decimal separator, so parsing must
  1022. // not depend on the process locale. An embedding application may have
  1023. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1024. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1025. std::string saved = cur ? cur : "C";
  1026. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1027. "fr_FR.UTF-8"};
  1028. bool switched = false;
  1029. for (const auto loc : comma_locales) {
  1030. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1031. std::localeconv()->decimal_point[0] == ',') {
  1032. switched = true;
  1033. break;
  1034. }
  1035. }
  1036. if (!switched) {
  1037. std::setlocale(LC_NUMERIC, saved.c_str());
  1038. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1039. }
  1040. // The higher-weighted type appears later in the list, so a correct parse
  1041. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1042. // sensitive parse reads both weights as 0 and leaves the original order.
  1043. std::vector<std::string> result;
  1044. EXPECT_TRUE(detail::parse_accept_header(
  1045. "application/json;q=0.1,text/html;q=0.9", result));
  1046. ASSERT_EQ(result.size(), 2U);
  1047. EXPECT_EQ(result[0], "text/html");
  1048. EXPECT_EQ(result[1], "application/json");
  1049. std::setlocale(LC_NUMERIC, saved.c_str());
  1050. }
  1051. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1052. std::vector<std::string> result;
  1053. // Invalid quality value (> 1.0)
  1054. EXPECT_FALSE(
  1055. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1056. // Invalid quality value (< 0.0)
  1057. EXPECT_FALSE(
  1058. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1059. // Invalid quality value (not a number)
  1060. EXPECT_FALSE(detail::parse_accept_header(
  1061. "text/html;q=invalid,application/json", result));
  1062. // A valid numeric prefix does not make the entire quality value valid.
  1063. EXPECT_FALSE(detail::parse_accept_header(
  1064. "text/html;q=0.5junk,application/json", result));
  1065. // Empty quality value
  1066. EXPECT_FALSE(
  1067. detail::parse_accept_header("text/html;q=,application/json", result));
  1068. // Invalid media type format (no slash and not wildcard)
  1069. EXPECT_FALSE(
  1070. detail::parse_accept_header("invalidtype,application/json", result));
  1071. // Valid cases should still work
  1072. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1073. EXPECT_EQ(result.size(), 1U);
  1074. EXPECT_EQ(result[0], "*/*");
  1075. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1076. EXPECT_EQ(result.size(), 1U);
  1077. EXPECT_EQ(result[0], "*");
  1078. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1079. EXPECT_EQ(result.size(), 1U);
  1080. EXPECT_EQ(result[0], "text/*");
  1081. }
  1082. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1083. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1084. // and must not be answered with 400 Bad Request.
  1085. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1086. struct {
  1087. const char *value;
  1088. std::vector<std::string> expected;
  1089. } cases[] = {
  1090. {",application/json", {"application/json"}},
  1091. {"text/html,", {"text/html"}},
  1092. {"text/html,,*/*", {"text/html", "*/*"}},
  1093. // An empty element may be spelled with whitespace in it
  1094. {"text/html, , application/json", {"text/html", "application/json"}},
  1095. // Nothing but empty elements is an empty list, which means the same
  1096. // thing as no Accept header at all
  1097. {",,,", {}},
  1098. // Quality values still apply across ignored empty elements
  1099. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1100. };
  1101. for (const auto &c : cases) {
  1102. std::vector<std::string> result;
  1103. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1104. << "value: " << c.value;
  1105. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1106. }
  1107. // An invalid entry is still rejected when empty elements surround it
  1108. std::vector<std::string> result;
  1109. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1110. }
  1111. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1112. // or ';' inside one does not end the list element or the parameter. Section
  1113. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1114. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1115. struct {
  1116. const char *value;
  1117. std::vector<std::string> expected;
  1118. } cases[] = {
  1119. {"text/html;profile=\"a,b\",application/json",
  1120. {"text/html", "application/json"}},
  1121. // A "q=" inside a quoted value is not the weight
  1122. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1123. {"text/html", "application/json"}},
  1124. // The weight after a quoted value still applies
  1125. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1126. {"application/json", "text/html"}},
  1127. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1128. {"application/json", "text/html"}},
  1129. {"text/html;profile=\"a\\\"b\",application/json",
  1130. {"text/html", "application/json"}},
  1131. // An escaped backslash does not escape the '"' after it
  1132. {"text/html;profile=\"a\\\\\",application/json",
  1133. {"text/html", "application/json"}},
  1134. };
  1135. for (const auto &c : cases) {
  1136. std::vector<std::string> result;
  1137. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1138. << "value: " << c.value;
  1139. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1140. }
  1141. }
  1142. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1143. Server svr;
  1144. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1145. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1146. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1147. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1148. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1149. res.set_content("ok", "text/plain");
  1150. });
  1151. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1152. EXPECT_TRUE(false);
  1153. res.set_content("bad request", "text/plain");
  1154. });
  1155. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1156. auto se = detail::scope_exit([&] {
  1157. svr.stop();
  1158. listen_thread.join();
  1159. ASSERT_FALSE(svr.is_running());
  1160. });
  1161. svr.wait_until_ready();
  1162. Client cli("localhost", PORT);
  1163. {
  1164. auto res = cli.Get(
  1165. "/accept_ok",
  1166. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1168. EXPECT_EQ(StatusCode::OK_200, res->status);
  1169. }
  1170. {
  1171. auto res = cli.Get("/accept_bad_request",
  1172. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1174. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1175. }
  1176. }
  1177. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1178. Server svr;
  1179. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1180. res.set_content("ok", "text/plain");
  1181. });
  1182. std::atomic<int> start_count{0};
  1183. std::atomic<bool> running_when_called{false};
  1184. svr.set_start_handler([&]() {
  1185. running_when_called = svr.is_running();
  1186. start_count++;
  1187. });
  1188. auto port = svr.bind_to_any_port(HOST);
  1189. std::thread t([&]() { svr.listen_after_bind(); });
  1190. auto se = detail::scope_exit([&] {
  1191. svr.stop();
  1192. t.join();
  1193. ASSERT_FALSE(svr.is_running());
  1194. });
  1195. svr.wait_until_ready();
  1196. // A successful request proves the accept loop is running, which the start
  1197. // handler precedes; so by now the handler must have run exactly once.
  1198. Client cli(HOST, port);
  1199. cli.set_connection_timeout(std::chrono::seconds(5));
  1200. auto res = cli.Get("/");
  1201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1202. EXPECT_EQ(StatusCode::OK_200, res->status);
  1203. EXPECT_EQ(1, start_count.load());
  1204. EXPECT_TRUE(running_when_called.load());
  1205. }
  1206. TEST(DivideTest, DivideStringTests) {
  1207. auto divide = [](const std::string &str, char d) {
  1208. std::string lhs;
  1209. std::string rhs;
  1210. detail::divide(str, d,
  1211. [&](const char *lhs_data, std::size_t lhs_size,
  1212. const char *rhs_data, std::size_t rhs_size) {
  1213. lhs.assign(lhs_data, lhs_size);
  1214. rhs.assign(rhs_data, rhs_size);
  1215. });
  1216. return std::make_pair(std::move(lhs), std::move(rhs));
  1217. };
  1218. {
  1219. const auto res = divide("", '=');
  1220. EXPECT_EQ(res.first, "");
  1221. EXPECT_EQ(res.second, "");
  1222. }
  1223. {
  1224. const auto res = divide("=", '=');
  1225. EXPECT_EQ(res.first, "");
  1226. EXPECT_EQ(res.second, "");
  1227. }
  1228. {
  1229. const auto res = divide(" ", '=');
  1230. EXPECT_EQ(res.first, " ");
  1231. EXPECT_EQ(res.second, "");
  1232. }
  1233. {
  1234. const auto res = divide("a", '=');
  1235. EXPECT_EQ(res.first, "a");
  1236. EXPECT_EQ(res.second, "");
  1237. }
  1238. {
  1239. const auto res = divide("a=", '=');
  1240. EXPECT_EQ(res.first, "a");
  1241. EXPECT_EQ(res.second, "");
  1242. }
  1243. {
  1244. const auto res = divide("=b", '=');
  1245. EXPECT_EQ(res.first, "");
  1246. EXPECT_EQ(res.second, "b");
  1247. }
  1248. {
  1249. const auto res = divide("a=b", '=');
  1250. EXPECT_EQ(res.first, "a");
  1251. EXPECT_EQ(res.second, "b");
  1252. }
  1253. {
  1254. const auto res = divide("a=b=", '=');
  1255. EXPECT_EQ(res.first, "a");
  1256. EXPECT_EQ(res.second, "b=");
  1257. }
  1258. {
  1259. const auto res = divide("a=b=c", '=');
  1260. EXPECT_EQ(res.first, "a");
  1261. EXPECT_EQ(res.second, "b=c");
  1262. }
  1263. }
  1264. TEST(SplitTest, ParseQueryString) {
  1265. string s = "key1=val1&key2=val2&key3=val3";
  1266. Params dic;
  1267. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1268. [&](const char *b, const char *e) {
  1269. string key, val;
  1270. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1271. if (key.empty()) {
  1272. key.assign(b2, e2);
  1273. } else {
  1274. val.assign(b2, e2);
  1275. }
  1276. });
  1277. dic.emplace(key, val);
  1278. });
  1279. EXPECT_EQ("val1", dic.find("key1")->second);
  1280. EXPECT_EQ("val2", dic.find("key2")->second);
  1281. EXPECT_EQ("val3", dic.find("key3")->second);
  1282. }
  1283. TEST(SplitTest, ParseInvalidQueryTests) {
  1284. {
  1285. string s = " ";
  1286. Params dict;
  1287. detail::parse_query_text(s, dict);
  1288. EXPECT_TRUE(dict.empty());
  1289. }
  1290. {
  1291. string s = " = =";
  1292. Params dict;
  1293. detail::parse_query_text(s, dict);
  1294. EXPECT_TRUE(dict.empty());
  1295. }
  1296. }
  1297. TEST(ParseQueryTest, ParseQueryString) {
  1298. {
  1299. std::string s = "key1=val1&key2=val2&key3=val3";
  1300. Params dic;
  1301. detail::parse_query_text(s, dic);
  1302. EXPECT_EQ("val1", dic.find("key1")->second);
  1303. EXPECT_EQ("val2", dic.find("key2")->second);
  1304. EXPECT_EQ("val3", dic.find("key3")->second);
  1305. }
  1306. {
  1307. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1308. Params dic;
  1309. detail::parse_query_text(s, dic);
  1310. EXPECT_EQ("", dic.find("key1")->second);
  1311. EXPECT_EQ("val1", dic.find("key2")->second);
  1312. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1313. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1314. }
  1315. }
  1316. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1317. Params dic;
  1318. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1319. dic.emplace("key1", "val1");
  1320. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1321. dic.emplace("key2", "val2");
  1322. dic.emplace("key3", "val3");
  1323. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1324. }
  1325. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1326. Params params;
  1327. params.emplace("a", "1");
  1328. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1329. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1330. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1331. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1332. // Long enough to overflow the stack when matched with std::regex.
  1333. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1334. EXPECT_EQ("/p?" + long_query + "&a=1",
  1335. append_query_params("/p?" + long_query, params));
  1336. }
  1337. // Joins every entry of a Headers or Params into "key=value " so a whole
  1338. // traversal can be compared in one assertion. Both are instantiations of the
  1339. // same insertion-ordered container, so one helper serves both.
  1340. template <typename Map> static std::string entries_to_string(const Map &m) {
  1341. std::string s;
  1342. for (const auto &entry : m) {
  1343. s += entry.first + "=" + entry.second + " ";
  1344. }
  1345. return s;
  1346. }
  1347. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1348. // Params used to be a std::multimap, which sorted by name and handed the
  1349. // caller's query back alphabetised. A client signing its query string could
  1350. // not reproduce the order it asked for.
  1351. Params dic;
  1352. dic.emplace("zulu", "1");
  1353. dic.emplace("alpha", "2");
  1354. dic.emplace("mike", "3");
  1355. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1356. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1357. }
  1358. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1359. Params dic;
  1360. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1361. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1362. }
  1363. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1364. Request req;
  1365. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1366. req.params);
  1367. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1368. EXPECT_EQ("first", req.get_param_value("tag"));
  1369. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1370. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1371. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1372. EXPECT_EQ("", req.get_param_value("tag", 3));
  1373. }
  1374. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1375. // Params shares its container with Headers, which matches field names
  1376. // case-insensitively. Parameter names must not pick that up.
  1377. Params dic;
  1378. dic.emplace("Key", "upper");
  1379. dic.emplace("key", "lower");
  1380. EXPECT_EQ(2U, dic.size());
  1381. EXPECT_EQ(1U, dic.count("Key"));
  1382. EXPECT_EQ(1U, dic.count("key"));
  1383. EXPECT_EQ("upper", dic.find("Key")->second);
  1384. EXPECT_EQ("lower", dic.find("key")->second);
  1385. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1386. }
  1387. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1388. Server svr;
  1389. std::string order;
  1390. svr.Get("/order", [&](const Request &req, Response &res) {
  1391. order = entries_to_string(req.params);
  1392. res.set_content("ok", "text/plain");
  1393. });
  1394. auto port = svr.bind_to_any_port(HOST);
  1395. thread t = thread([&] { svr.listen_after_bind(); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. t.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, port);
  1403. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1404. ASSERT_TRUE(res);
  1405. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1406. }
  1407. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1408. Server svr;
  1409. std::string field_order, file_order;
  1410. svr.Post("/order", [&](const Request &req, Response &res) {
  1411. for (const auto &field : req.form.fields) {
  1412. field_order += field.first + "=" + field.second.content + " ";
  1413. }
  1414. for (const auto &file : req.form.files) {
  1415. file_order += file.first + "=" + file.second.filename + " ";
  1416. }
  1417. res.set_content("ok", "text/plain");
  1418. });
  1419. auto port = svr.bind_to_any_port(HOST);
  1420. thread t = thread([&] { svr.listen_after_bind(); });
  1421. auto se = detail::scope_exit([&] {
  1422. svr.stop();
  1423. t.join();
  1424. ASSERT_FALSE(svr.is_running());
  1425. });
  1426. svr.wait_until_ready();
  1427. UploadFormDataItems items = {
  1428. {"zulu", "1", "", ""},
  1429. {"alpha", "2", "", ""},
  1430. {"mike", "3", "", ""},
  1431. {"zebra", "z", "z.txt", "text/plain"},
  1432. {"apple", "a", "a.txt", "text/plain"},
  1433. };
  1434. Client cli(HOST, port);
  1435. auto res = cli.Post("/order", items);
  1436. ASSERT_TRUE(res);
  1437. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1438. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1439. }
  1440. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1441. Server svr;
  1442. std::vector<std::string> values;
  1443. std::string first, second, out_of_range, order;
  1444. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1445. values = req.form.get_fields("tag");
  1446. first = req.form.get_field("tag", 0);
  1447. second = req.form.get_field("tag", 1);
  1448. out_of_range = req.form.get_field("tag", 2);
  1449. for (const auto &field : req.form.fields) {
  1450. order += field.first + "=" + field.second.content + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1463. // not adjacent in the container.
  1464. UploadFormDataItems items = {
  1465. {"tag", "first", "", ""},
  1466. {"other", "x", "", ""},
  1467. {"tag", "second", "", ""},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/repeated", items);
  1471. ASSERT_TRUE(res);
  1472. ASSERT_EQ(2U, values.size());
  1473. EXPECT_EQ("first", values[0]);
  1474. EXPECT_EQ("second", values[1]);
  1475. EXPECT_EQ("first", first);
  1476. EXPECT_EQ("second", second);
  1477. // std::multimap already kept entries sharing a name in insertion order, so
  1478. // everything above passes without this change too. The whole traversal is
  1479. // what tells the two apart: sorting by name would hoist "other" to the front
  1480. // and the two "tag" parts would end up adjacent.
  1481. EXPECT_EQ("tag=first other=x tag=second ", order);
  1482. // Advancing past the last entry of a name used to run off the container;
  1483. // the container's saturating increment makes it return the default instead.
  1484. EXPECT_EQ("", out_of_range);
  1485. }
  1486. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1487. Server svr;
  1488. std::string file_names;
  1489. svr.Post("/upload", [&](const Request &req, Response &res) {
  1490. for (const auto &file : req.form.files) {
  1491. file_names += file.first + "|" + file.second.filename + " ";
  1492. }
  1493. res.set_content("ok", "text/plain");
  1494. });
  1495. auto port = svr.bind_to_any_port(HOST);
  1496. thread t = thread([&] { svr.listen_after_bind(); });
  1497. auto se = detail::scope_exit([&] {
  1498. svr.stop();
  1499. t.join();
  1500. ASSERT_FALSE(svr.is_running());
  1501. });
  1502. svr.wait_until_ready();
  1503. // A trailing backslash would otherwise escape the closing quote.
  1504. UploadFormDataItems items = {
  1505. {"dir\\", "x", "a.txt", "text/plain"},
  1506. {"b", "y", "a\\\\b.txt", "text/plain"},
  1507. };
  1508. Client cli(HOST, port);
  1509. auto res = cli.Post("/upload", items);
  1510. ASSERT_TRUE(res);
  1511. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1512. }
  1513. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1514. // Server::read_content() keeps a FormFields::iterator alive across the
  1515. // content callbacks that fill the part it points at. The container is
  1516. // vector-backed, so a later emplace can reallocate and invalidate an older
  1517. // iterator; 64 parts grow the vector through seven reallocations, which
  1518. // checks that every part's content still lands in its own entry.
  1519. const size_t part_count = 64;
  1520. // One formula for both the parts sent and the values expected back, so the
  1521. // two cannot drift apart.
  1522. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1523. auto content_of = [](size_t i) {
  1524. return std::string(64, static_cast<char>('a' + (i % 26)));
  1525. };
  1526. Server svr;
  1527. std::vector<std::pair<std::string, std::string>> received;
  1528. svr.Post("/many", [&](const Request &req, Response &res) {
  1529. for (const auto &field : req.form.fields) {
  1530. received.emplace_back(field.first, field.second.content);
  1531. }
  1532. res.set_content("ok", "text/plain");
  1533. });
  1534. auto port = svr.bind_to_any_port(HOST);
  1535. thread t = thread([&] { svr.listen_after_bind(); });
  1536. auto se = detail::scope_exit([&] {
  1537. svr.stop();
  1538. t.join();
  1539. ASSERT_FALSE(svr.is_running());
  1540. });
  1541. svr.wait_until_ready();
  1542. UploadFormDataItems items;
  1543. for (size_t i = 0; i < part_count; i++) {
  1544. items.push_back({name_of(i), content_of(i), "", ""});
  1545. }
  1546. Client cli(HOST, port);
  1547. auto res = cli.Post("/many", items);
  1548. ASSERT_TRUE(res);
  1549. ASSERT_EQ(part_count, received.size());
  1550. for (size_t i = 0; i < part_count; i++) {
  1551. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1552. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1553. }
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1556. string content_type = "multipart/form-data; boundary=something";
  1557. string boundary;
  1558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(boundary, "something");
  1561. }
  1562. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1563. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1564. string boundary;
  1565. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1566. EXPECT_TRUE(ret);
  1567. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1568. }
  1569. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1570. string content_type =
  1571. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1572. string boundary;
  1573. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1574. EXPECT_TRUE(ret);
  1575. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1576. }
  1577. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1578. string content_type =
  1579. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1580. string boundary;
  1581. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1582. EXPECT_TRUE(ret);
  1583. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1584. }
  1585. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=" + boundary;
  1588. string parsed;
  1589. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1590. EXPECT_TRUE(ret);
  1591. EXPECT_EQ(parsed, boundary);
  1592. }
  1593. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1594. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1595. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1596. string parsed;
  1597. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1598. EXPECT_FALSE(ret);
  1599. }
  1600. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1601. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1602. // is 72 characters on the wire and still valid.
  1603. const string boundary(70, 'a');
  1604. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, boundary);
  1608. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1609. parsed.clear();
  1610. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1613. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1614. // The parameter parser must not treat that '=' as the key/value separator.
  1615. string content_type =
  1616. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1617. "charset=UTF-8";
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1620. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1621. }
  1622. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1623. // A ';' inside the quoted-string is part of the value, not a parameter
  1624. // separator, so it must not truncate the boundary.
  1625. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1626. string parsed;
  1627. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1628. EXPECT_EQ(parsed, "a;b");
  1629. }
  1630. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1631. string parsed;
  1632. EXPECT_TRUE(detail::parse_multipart_boundary(
  1633. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1634. EXPECT_EQ("a\\b", parsed);
  1635. EXPECT_TRUE(detail::parse_multipart_boundary(
  1636. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1637. EXPECT_EQ("a\"b", parsed);
  1638. }
  1639. TEST(ParseDispositionParamsTest, QuotedValues) {
  1640. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1641. // ';' and '=' are ordinary characters inside one.
  1642. struct {
  1643. const char *value;
  1644. std::vector<std::pair<const char *, const char *>> expected;
  1645. } cases[] = {
  1646. {"name=\"file1\"; filename=\"a.txt\"",
  1647. {{"name", "file1"}, {"filename", "a.txt"}}},
  1648. // Whitespace around '=' and ';' is still trimmed
  1649. {"name=\"file2\" ;filename = \"a.html\"",
  1650. {{"name", "file2"}, {"filename", "a.html"}}},
  1651. // '=' inside the value used to leave only the text after the last one
  1652. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1653. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1654. {"name=\"x=y\"", {{"name", "x=y"}}},
  1655. // ';' inside the value used to truncate the pair and leave a bogus one
  1656. {"name=\"file3\"; filename=\"a;b.txt\"",
  1657. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1658. // An unquoted value keeps working, and so does filename*
  1659. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1660. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1661. // A parameter with no key is dropped rather than turned into one whose
  1662. // key is the value
  1663. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1664. // An escaped quote does not end the value
  1665. {"name=\"a\\\"; filename=evil.php\"",
  1666. {{"name", "a\"; filename=evil.php"}}},
  1667. // Other backslashes, as in a Windows path, are kept
  1668. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1669. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1670. };
  1671. for (const auto &c : cases) {
  1672. Params params;
  1673. detail::parse_disposition_params(c.value, params);
  1674. for (const auto &kv : c.expected) {
  1675. auto it = params.find(kv.first);
  1676. ASSERT_NE(it, params.end())
  1677. << "value: " << c.value << ", key: " << kv.first;
  1678. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1679. }
  1680. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1681. }
  1682. }
  1683. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1684. Server svr;
  1685. std::string filename;
  1686. std::string content;
  1687. svr.Post("/upload", [&](const Request &req, Response &) {
  1688. const auto &file = req.form.get_file("file");
  1689. filename = file.filename;
  1690. content = file.content;
  1691. });
  1692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1693. auto se = detail::scope_exit([&] {
  1694. svr.stop();
  1695. thread.join();
  1696. ASSERT_FALSE(svr.is_running());
  1697. });
  1698. svr.wait_until_ready();
  1699. std::string body = "--B\r\n"
  1700. "Content-Disposition: form-data; name=\"file\"; "
  1701. "filename=\"a.txt\"\r\n"
  1702. "Content-Type: text/plain\r\n"
  1703. "\r\n"
  1704. "hello\r\n"
  1705. "--B--\r\n";
  1706. Client cli(HOST, PORT);
  1707. auto res = cli.Post(
  1708. "/upload",
  1709. [&](size_t offset, DataSink &sink) {
  1710. if (offset < body.size()) {
  1711. sink.write(&body[offset], 1);
  1712. } else {
  1713. sink.done();
  1714. }
  1715. return true;
  1716. },
  1717. "multipart/form-data; boundary=B");
  1718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. EXPECT_EQ("a.txt", filename);
  1721. EXPECT_EQ("hello", content);
  1722. }
  1723. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1724. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1725. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1726. Server svr;
  1727. std::string field_value, file_name, file_filename;
  1728. bool has_field = false, has_file = false;
  1729. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1730. has_field = req.form.has_field("x=y");
  1731. field_value = req.form.get_field("x=y");
  1732. has_file = req.form.has_file("file1");
  1733. const auto &file = req.form.get_file("file1");
  1734. file_name = file.name;
  1735. file_filename = file.filename;
  1736. res.set_content("ok", "text/plain");
  1737. });
  1738. auto port = svr.bind_to_any_port(HOST);
  1739. thread t = thread([&] { svr.listen_after_bind(); });
  1740. auto se = detail::scope_exit([&] {
  1741. svr.stop();
  1742. t.join();
  1743. ASSERT_FALSE(svr.is_running());
  1744. });
  1745. svr.wait_until_ready();
  1746. UploadFormDataItems items = {
  1747. {"x=y", "field-value", "", ""},
  1748. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1749. };
  1750. Client cli(HOST, port);
  1751. auto res = cli.Post("/quoted", items);
  1752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1753. ASSERT_EQ(StatusCode::OK_200, res->status);
  1754. EXPECT_TRUE(has_field);
  1755. EXPECT_EQ("field-value", field_value);
  1756. EXPECT_TRUE(has_file);
  1757. EXPECT_EQ("file1", file_name);
  1758. EXPECT_EQ("a;b=report.pdf", file_filename);
  1759. }
  1760. TEST(GetHeaderValueTest, DefaultValue) {
  1761. Headers headers = {{"Dummy", "Dummy"}};
  1762. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1763. EXPECT_STREQ("text/plain", val);
  1764. }
  1765. TEST(GetHeaderValueTest, DefaultValueInt) {
  1766. Headers headers = {{"Dummy", "Dummy"}};
  1767. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1768. EXPECT_EQ(100ull, val);
  1769. }
  1770. TEST(GetHeaderValueTest, RegularValue) {
  1771. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1772. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1773. EXPECT_STREQ("text/html", val);
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1776. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1778. EXPECT_STREQ("text/html", val);
  1779. }
  1780. TEST(GetHeaderValueTest, SetContent) {
  1781. Response res;
  1782. res.set_content("html", "text/html");
  1783. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1784. res.set_content("text", "text/plain");
  1785. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1786. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1787. }
  1788. TEST(GetHeaderValueTest, RegularValueInt) {
  1789. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1790. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1791. EXPECT_EQ(100ull, val);
  1792. }
  1793. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1794. Headers headers = {{"Content-Length", "x"}};
  1795. auto is_invalid_value = false;
  1796. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1797. is_invalid_value);
  1798. EXPECT_EQ(0ull, val);
  1799. EXPECT_TRUE(is_invalid_value);
  1800. }
  1801. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1802. // An all-digit value that overflows size_t must be reported as invalid, not
  1803. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1804. // a large length to a small one on 32-bit builds, leaving the framing length
  1805. // wrong while is_invalid_value stayed false.
  1806. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1807. auto is_invalid_value = false;
  1808. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1809. is_invalid_value);
  1810. EXPECT_TRUE(is_invalid_value);
  1811. // A well-formed length is unaffected.
  1812. Headers ok = {{"Content-Length", "1234"}};
  1813. is_invalid_value = false;
  1814. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1815. is_invalid_value);
  1816. EXPECT_EQ(1234ull, val);
  1817. EXPECT_FALSE(is_invalid_value);
  1818. }
  1819. TEST(GetHeaderValueTest, Range) {
  1820. {
  1821. Headers headers = {make_range_header({{1, -1}})};
  1822. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1823. EXPECT_STREQ("bytes=1-", val);
  1824. }
  1825. {
  1826. Headers headers = {make_range_header({{-1, 1}})};
  1827. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1828. EXPECT_STREQ("bytes=-1", val);
  1829. }
  1830. {
  1831. Headers headers = {make_range_header({{1, 10}})};
  1832. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1833. EXPECT_STREQ("bytes=1-10", val);
  1834. }
  1835. {
  1836. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1837. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1838. EXPECT_STREQ("bytes=1-10, 100-", val);
  1839. }
  1840. {
  1841. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1842. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1843. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1844. }
  1845. {
  1846. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1848. EXPECT_STREQ("bytes=0-0, -1", val);
  1849. }
  1850. }
  1851. TEST(BearerTokenAuthTest, SchemeValidation) {
  1852. // A value shorter than "Bearer " must not throw from the fixed-length
  1853. // substr, and a non-Bearer scheme must not be reported as a token.
  1854. struct {
  1855. const char *value;
  1856. const char *expected;
  1857. } cases[] = {
  1858. {"x", ""},
  1859. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1860. {"Bearer abc123", "abc123"},
  1861. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1862. };
  1863. for (const auto &c : cases) {
  1864. Request req;
  1865. req.set_header("Authorization", c.value);
  1866. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1867. }
  1868. }
  1869. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1870. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1871. // to depend on the standard library (libstdc++ handed back duplicates in
  1872. // reverse insertion order, libc++ in insertion order).
  1873. Request req;
  1874. req.set_header("Accept-Encoding", "gzip");
  1875. req.set_header("Accept-Encoding", "deflate");
  1876. req.set_header("Accept-Encoding", "br");
  1877. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1878. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1879. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1880. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1881. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1882. }
  1883. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1884. Request req;
  1885. req.set_header("X-Test", "only");
  1886. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1888. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1889. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1890. }
  1891. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1892. Request req;
  1893. req.set_header("X-First", "1");
  1894. req.set_header("X-Test", "2");
  1895. req.params.emplace("first", "1");
  1896. req.params.emplace("test", "2");
  1897. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1898. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1899. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1900. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1901. // The second one is negative when read as a signed value
  1902. const auto max_id = (std::numeric_limits<size_t>::max)();
  1903. for (auto id : {max_id / 2, max_id}) {
  1904. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1905. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1906. EXPECT_EQ("", req.get_param_value("test", id));
  1907. EXPECT_EQ("", req.form.get_field("test", id));
  1908. EXPECT_EQ("", req.form.get_file("test", id).content);
  1909. }
  1910. }
  1911. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1912. Headers headers;
  1913. headers.emplace("Host", "example.com");
  1914. headers.emplace("Accept-Encoding", "gzip");
  1915. headers.emplace("User-Agent", "test");
  1916. headers.emplace("Accept-Encoding", "deflate");
  1917. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1918. "Accept-Encoding=deflate ",
  1919. entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1922. Headers headers = {{"Content-Type", "text/html"},
  1923. {"CONTENT-TYPE", "text/xml"}};
  1924. EXPECT_EQ(2U, headers.count("content-type"));
  1925. auto it = headers.find("content-type");
  1926. ASSERT_TRUE(it != headers.end());
  1927. EXPECT_EQ("text/html", it->second);
  1928. }
  1929. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1930. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1931. // drop only those fields and leave everything positioned between them.
  1932. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1933. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1934. auto rng = headers.equal_range("a");
  1935. headers.erase(rng.first, rng.second);
  1936. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1937. }
  1938. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1939. Headers headers = {
  1940. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1941. EXPECT_EQ(3U, headers.erase("A"));
  1942. EXPECT_EQ(0U, headers.count("A"));
  1943. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1944. }
  1945. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1946. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1947. headers.emplace_front("Host", "example.com");
  1948. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1949. entries_to_string(headers));
  1950. }
  1951. TEST(ParseHeaderValueTest, Range) {
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1957. }
  1958. {
  1959. Ranges ranges;
  1960. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1961. EXPECT_TRUE(ret);
  1962. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1969. }
  1970. {
  1971. Ranges ranges;
  1972. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1973. EXPECT_FALSE(ret);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1980. }
  1981. {
  1982. Ranges ranges;
  1983. auto ret =
  1984. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1985. EXPECT_TRUE(ret);
  1986. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1987. }
  1988. {
  1989. Ranges ranges;
  1990. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2003. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2004. EXPECT_FALSE(
  2005. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2006. EXPECT_TRUE(ranges.empty());
  2007. }
  2008. {
  2009. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2010. // remainder of the representation, so it stays accepted.
  2011. Ranges ranges;
  2012. auto ret =
  2013. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2014. EXPECT_TRUE(ret);
  2015. ASSERT_EQ(1u, ranges.size());
  2016. EXPECT_EQ(0, ranges[0].first);
  2017. EXPECT_EQ(-1, ranges[0].second);
  2018. }
  2019. // RFC 9110 14.1: range unit names are case-insensitive.
  2020. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2021. Ranges ranges;
  2022. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2023. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2024. }
  2025. }
  2026. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2027. Request req;
  2028. req.set_header("Accept-Encoding", "gzip");
  2029. Response res;
  2030. res.set_header("Content-Type", "text/plain");
  2031. auto ret = detail::encoding_type(req, res);
  2032. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #else
  2035. EXPECT_TRUE(ret == detail::EncodingType::None);
  2036. #endif
  2037. }
  2038. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2039. Request req;
  2040. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2041. Response res;
  2042. res.set_header("Content-Type", "text/plain");
  2043. auto ret = detail::encoding_type(req, res);
  2044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2046. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2048. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2050. #else
  2051. EXPECT_TRUE(ret == detail::EncodingType::None);
  2052. #endif
  2053. }
  2054. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2055. Request req;
  2056. req.set_header("Accept-Encoding",
  2057. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2058. Response res;
  2059. res.set_header("Content-Type", "text/plain");
  2060. auto ret = detail::encoding_type(req, res);
  2061. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2063. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2065. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2072. // All supported encodings rejected with q=0 should return None
  2073. Request req;
  2074. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2075. Response res;
  2076. res.set_header("Content-Type", "text/plain");
  2077. auto ret = detail::encoding_type(req, res);
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. }
  2080. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2081. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2082. Request req;
  2083. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2084. Response res;
  2085. res.set_header("Content-Type", "text/plain");
  2086. auto ret = detail::encoding_type(req, res);
  2087. EXPECT_TRUE(ret == detail::EncodingType::None);
  2088. }
  2089. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2092. Response res;
  2093. res.set_header("Content-Type", "text/plain");
  2094. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2095. }
  2096. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2097. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2098. Request req;
  2099. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2100. Response res;
  2101. res.set_header("Content-Type", "text/plain");
  2102. auto ret = detail::encoding_type(req, res);
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. }
  2105. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2106. // RFC 7231: Accept-Encoding values are case-insensitive
  2107. Request req;
  2108. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2109. Response res;
  2110. res.set_header("Content-Type", "text/plain");
  2111. auto ret = detail::encoding_type(req, res);
  2112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2113. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2114. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2116. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2118. #else
  2119. EXPECT_TRUE(ret == detail::EncodingType::None);
  2120. #endif
  2121. }
  2122. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2123. // q value should determine priority, not hardcoded order
  2124. Request req;
  2125. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2126. Response res;
  2127. res.set_header("Content-Type", "text/plain");
  2128. auto ret = detail::encoding_type(req, res);
  2129. // gzip has highest q=1.0, so it should be selected even though
  2130. // br and zstd are also supported
  2131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2132. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2133. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2135. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2137. #else
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. #endif
  2140. }
  2141. TEST(BufferStreamTest, read) {
  2142. detail::BufferStream strm1;
  2143. Stream &strm = strm1;
  2144. EXPECT_EQ(5, strm.write("hello"));
  2145. char buf[512];
  2146. EXPECT_EQ(2, strm.read(buf, 2));
  2147. EXPECT_EQ('h', buf[0]);
  2148. EXPECT_EQ('e', buf[1]);
  2149. EXPECT_EQ(2, strm.read(buf, 2));
  2150. EXPECT_EQ('l', buf[0]);
  2151. EXPECT_EQ('l', buf[1]);
  2152. EXPECT_EQ(1, strm.read(buf, 1));
  2153. EXPECT_EQ('o', buf[0]);
  2154. EXPECT_EQ(0, strm.read(buf, 1));
  2155. }
  2156. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2157. auto host = "www.httpwatch.com";
  2158. auto ip = hosted_at(host);
  2159. EXPECT_EQ("23.96.13.243", ip);
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(1u, addrs.size());
  2163. }
  2164. #if 0 // It depends on each test environment...
  2165. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2166. auto host = "www.youtube.com";
  2167. std::vector<std::string> addrs;
  2168. hosted_at(host, addrs);
  2169. EXPECT_EQ(20u, addrs.size());
  2170. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2171. EXPECT_TRUE(it != addrs.end());
  2172. }
  2173. #endif
  2174. class ChunkedEncodingTest : public ::testing::Test {
  2175. protected:
  2176. ChunkedEncodingTest()
  2177. : cli_(HOST, PORT)
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. ,
  2180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2181. #endif
  2182. {
  2183. cli_.set_connection_timeout(2);
  2184. #ifdef CPPHTTPLIB_SSL_ENABLED
  2185. cli_.enable_server_certificate_verification(false);
  2186. #endif
  2187. }
  2188. virtual void SetUp() {
  2189. read_file("./image.jpg", image_data_);
  2190. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2191. res.set_content("Hello World!", "text/plain");
  2192. });
  2193. svr_.Get(
  2194. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2195. res.set_chunked_content_provider(
  2196. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2197. size_t remaining = image_data_.size() - offset;
  2198. if (remaining == 0) {
  2199. sink.done();
  2200. } else {
  2201. constexpr size_t CHUNK_SIZE = 1024;
  2202. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2203. sink.write(&image_data_[offset], send_size);
  2204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2205. }
  2206. return true;
  2207. });
  2208. });
  2209. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2210. svr_.wait_until_ready();
  2211. }
  2212. virtual void TearDown() {
  2213. svr_.stop();
  2214. if (!request_threads_.empty()) {
  2215. std::this_thread::sleep_for(std::chrono::seconds(1));
  2216. for (auto &t : request_threads_) {
  2217. t.join();
  2218. }
  2219. }
  2220. t_.join();
  2221. }
  2222. #ifdef CPPHTTPLIB_SSL_ENABLED
  2223. SSLClient cli_;
  2224. SSLServer svr_;
  2225. #else
  2226. Client cli_;
  2227. Server svr_;
  2228. #endif
  2229. thread t_;
  2230. std::vector<thread> request_threads_;
  2231. std::string image_data_;
  2232. };
  2233. TEST_F(ChunkedEncodingTest, NormalGet) {
  2234. auto res = cli_.Get("/chunked");
  2235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2236. std::string out;
  2237. read_file("./image.jpg", out);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. EXPECT_EQ(out, res->body);
  2240. }
  2241. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2242. std::string body;
  2243. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2244. body.append(data, data_length);
  2245. return true;
  2246. });
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. std::string out;
  2249. read_file("./image.jpg", out);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ(out, body);
  2252. }
  2253. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2254. std::string body;
  2255. auto res = cli_.Get(
  2256. "/chunked",
  2257. [&](const Response &response) {
  2258. EXPECT_EQ(StatusCode::OK_200, response.status);
  2259. return true;
  2260. },
  2261. [&](const char *data, size_t data_length) {
  2262. body.append(data, data_length);
  2263. return true;
  2264. });
  2265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2266. std::string out;
  2267. read_file("./image.jpg", out);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ(out, body);
  2270. }
  2271. TEST(RangeTest, FromHTTPBin_Online) {
  2272. auto host = "httpbingo.org";
  2273. auto path = std::string{"/range/32"};
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 443;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 80;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(5);
  2282. {
  2283. auto res = cli.Get(path);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::OK_200, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, -1}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. {
  2296. Headers headers = {make_range_header({{1, 10}})};
  2297. auto res = cli.Get(path, headers);
  2298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2299. EXPECT_EQ("bcdefghijk", res->body);
  2300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2301. }
  2302. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2303. // entire resource, while the original httpbin returned 200. Both are
  2304. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2305. {
  2306. Headers headers = {make_range_header({{0, 31}})};
  2307. auto res = cli.Get(path, headers);
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2310. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2311. res->status == StatusCode::PartialContent_206);
  2312. }
  2313. {
  2314. Headers headers = {make_range_header({{0, -1}})};
  2315. auto res = cli.Get(path, headers);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2318. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2319. res->status == StatusCode::PartialContent_206);
  2320. }
  2321. // go-httpbin returns 206 with clamped range for over-range requests,
  2322. // while the original httpbin returned 416. Both behaviors are observed
  2323. // in real servers, so we only verify the request succeeds.
  2324. {
  2325. Headers headers = {make_range_header({{0, 32}})};
  2326. auto res = cli.Get(path, headers);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. }
  2329. }
  2330. TEST(RangeTest, IgnoredForPost) {
  2331. Server svr;
  2332. svr.Post("/", [](const Request &, Response &res) {
  2333. res.set_content("abcdefg", "text/plain");
  2334. });
  2335. auto port = svr.bind_to_any_port(HOST);
  2336. ASSERT_GT(port, 0);
  2337. thread t = thread([&] { svr.listen_after_bind(); });
  2338. auto se = detail::scope_exit([&] {
  2339. svr.stop();
  2340. t.join();
  2341. ASSERT_FALSE(svr.is_running());
  2342. });
  2343. svr.wait_until_ready();
  2344. Client cli(HOST, port);
  2345. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2346. auto res = cli.Post("/", Headers{{"Range", range}});
  2347. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2348. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2349. EXPECT_EQ("abcdefg", res->body) << range;
  2350. }
  2351. }
  2352. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2353. auto host = "unresolvableaddress.local";
  2354. auto path = std::string{"/"};
  2355. #ifdef CPPHTTPLIB_SSL_ENABLED
  2356. auto port = 443;
  2357. SSLClient cli(host, port);
  2358. #else
  2359. auto port = 80;
  2360. Client cli(host, port);
  2361. #endif
  2362. cli.set_connection_timeout(1);
  2363. {
  2364. auto res = cli.Get(path);
  2365. ASSERT_FALSE(res);
  2366. }
  2367. std::this_thread::sleep_for(std::chrono::seconds(8));
  2368. }
  2369. #if defined(__linux__) && defined(__GLIBC__) && \
  2370. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2371. // Forward declaration: in split builds split.py strips `inline` and moves the
  2372. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2373. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2374. // against the symbol in both header-only and split builds.
  2375. namespace httplib {
  2376. namespace detail {
  2377. int getaddrinfo_with_timeout(const char *node, const char *service,
  2378. const struct addrinfo *hints,
  2379. struct addrinfo **res, time_t timeout_sec);
  2380. } // namespace detail
  2381. } // namespace httplib
  2382. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2383. //
  2384. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2385. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2386. // gai_suspend() call hits the connection timeout the function calls
  2387. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2388. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2389. // still alive and still references the now-destroyed stack frame.
  2390. //
  2391. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2392. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2393. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2394. // and runs them in a container.
  2395. namespace {
  2396. bool should_run_issue_2431_tests() {
  2397. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2398. return v && *v && std::string(v) != "0";
  2399. }
  2400. std::string unique_unresolvable_host(int n) {
  2401. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2402. // glibc still asks the configured nameserver — which is exactly the path
  2403. // we want to exercise. A unique label per call avoids the resolver cache.
  2404. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2405. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2406. std::to_string(n) + ".invalid";
  2407. }
  2408. } // namespace
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. for (int i = 0; i < 8; ++i) {
  2415. struct addrinfo hints;
  2416. memset(&hints, 0, sizeof(hints));
  2417. hints.ai_family = AF_UNSPEC;
  2418. hints.ai_socktype = SOCK_STREAM;
  2419. auto host = unique_unresolvable_host(i);
  2420. struct addrinfo *result = nullptr;
  2421. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2422. &result, /*timeout_sec=*/1);
  2423. if (rc == 0 && result) { freeaddrinfo(result); }
  2424. }
  2425. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2426. // stack region they still believe holds their gaicb.
  2427. std::this_thread::sleep_for(std::chrono::seconds(3));
  2428. }
  2429. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2430. if (!should_run_issue_2431_tests()) {
  2431. GTEST_SKIP()
  2432. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2433. }
  2434. std::atomic<bool> stop{false};
  2435. std::vector<std::thread> threads;
  2436. for (int t = 0; t < 8; ++t) {
  2437. threads.emplace_back([t, &stop] {
  2438. int i = 0;
  2439. while (!stop.load(std::memory_order_relaxed)) {
  2440. struct addrinfo hints;
  2441. memset(&hints, 0, sizeof(hints));
  2442. hints.ai_family = AF_UNSPEC;
  2443. hints.ai_socktype = SOCK_STREAM;
  2444. auto host = unique_unresolvable_host(t * 100000 + i++);
  2445. struct addrinfo *result = nullptr;
  2446. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2447. &result, /*timeout_sec=*/1);
  2448. if (rc == 0 && result) { freeaddrinfo(result); }
  2449. }
  2450. });
  2451. }
  2452. std::this_thread::sleep_for(std::chrono::seconds(8));
  2453. stop.store(true, std::memory_order_relaxed);
  2454. for (auto &th : threads) {
  2455. th.join();
  2456. }
  2457. std::this_thread::sleep_for(std::chrono::seconds(3));
  2458. }
  2459. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2460. if (!should_run_issue_2431_tests()) {
  2461. GTEST_SKIP()
  2462. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2463. }
  2464. std::atomic<bool> stop{false};
  2465. std::vector<std::thread> threads;
  2466. for (int t = 0; t < 8; ++t) {
  2467. threads.emplace_back([t, &stop] {
  2468. int i = 0;
  2469. while (!stop.load(std::memory_order_relaxed)) {
  2470. auto host = unique_unresolvable_host(t * 100000 + i++);
  2471. Client cli(host, 80);
  2472. cli.set_connection_timeout(1, 0);
  2473. cli.set_read_timeout(1, 0);
  2474. cli.set_write_timeout(1, 0);
  2475. (void)cli.Get("/");
  2476. }
  2477. });
  2478. }
  2479. std::this_thread::sleep_for(std::chrono::seconds(8));
  2480. stop.store(true, std::memory_order_relaxed);
  2481. for (auto &th : threads) {
  2482. th.join();
  2483. }
  2484. std::this_thread::sleep_for(std::chrono::seconds(3));
  2485. }
  2486. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2487. TEST(ConnectionErrorTest, InvalidHost) {
  2488. auto host = "-abcde.com";
  2489. #ifdef CPPHTTPLIB_SSL_ENABLED
  2490. auto port = 443;
  2491. SSLClient cli(host, port);
  2492. #else
  2493. auto port = 80;
  2494. Client cli(host, port);
  2495. #endif
  2496. cli.set_connection_timeout(std::chrono::seconds(2));
  2497. auto res = cli.Get("/");
  2498. ASSERT_TRUE(!res);
  2499. EXPECT_EQ(Error::Connection, res.error());
  2500. }
  2501. TEST(ConnectionErrorTest, InvalidHost2) {
  2502. auto host = "httpcan.org/";
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. SSLClient cli(host);
  2505. #else
  2506. Client cli(host);
  2507. #endif
  2508. cli.set_connection_timeout(std::chrono::seconds(2));
  2509. auto res = cli.Get("/");
  2510. ASSERT_TRUE(!res);
  2511. EXPECT_EQ(Error::Connection, res.error());
  2512. }
  2513. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2514. auto host = "httpcan.org/";
  2515. #ifdef CPPHTTPLIB_SSL_ENABLED
  2516. SSLClient cli(host);
  2517. #else
  2518. Client cli(host);
  2519. #endif
  2520. cli.set_connection_timeout(std::chrono::seconds(2));
  2521. auto res = cli.Get("/");
  2522. ASSERT_TRUE(!res);
  2523. stringstream s;
  2524. s << "error code: " << res.error();
  2525. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2526. }
  2527. TEST(ConnectionErrorTest, InvalidPort) {
  2528. auto host = "localhost";
  2529. auto port = 44380;
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. SSLClient cli(host, port);
  2532. #else
  2533. Client cli(host, port);
  2534. #endif
  2535. cli.set_connection_timeout(std::chrono::seconds(2));
  2536. auto res = cli.Get("/");
  2537. ASSERT_TRUE(!res);
  2538. EXPECT_TRUE(Error::Connection == res.error() ||
  2539. Error::ConnectionTimeout == res.error());
  2540. }
  2541. TEST(ConnectionErrorTest, Timeout_Online) {
  2542. auto host = "google.com";
  2543. #ifdef CPPHTTPLIB_SSL_ENABLED
  2544. auto port = 44380;
  2545. SSLClient cli(host, port);
  2546. #else
  2547. auto port = 8080;
  2548. Client cli(host, port);
  2549. #endif
  2550. cli.set_connection_timeout(std::chrono::seconds(2));
  2551. // only probe one address type so that the error reason
  2552. // correlates to the timed-out IPv4, not the unsupported
  2553. // IPv6 connection attempt
  2554. cli.set_address_family(AF_INET);
  2555. auto res = cli.Get("/");
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2558. }
  2559. TEST(CancelTest, NoCancel_Online) {
  2560. auto host = "httpbingo.org";
  2561. auto path = std::string{"/range/32"};
  2562. #ifdef CPPHTTPLIB_SSL_ENABLED
  2563. auto port = 443;
  2564. SSLClient cli(host, port);
  2565. #else
  2566. auto port = 80;
  2567. Client cli(host, port);
  2568. #endif
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2572. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2573. EXPECT_EQ(StatusCode::OK_200, res->status);
  2574. }
  2575. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2576. // Use /bytes with a large payload so that the DownloadProgress callback
  2577. // (which only fires for Content-Length responses) is invoked before the
  2578. // entire body is received, giving cancellation a chance to fire.
  2579. auto host = "httpbingo.org";
  2580. auto path = std::string{"/bytes/524288"};
  2581. #ifdef CPPHTTPLIB_SSL_ENABLED
  2582. auto port = 443;
  2583. SSLClient cli(host, port);
  2584. #else
  2585. auto port = 80;
  2586. Client cli(host, port);
  2587. #endif
  2588. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2589. cli.set_connection_timeout(std::chrono::seconds(5));
  2590. ASSERT_TRUE(!res);
  2591. EXPECT_EQ(Error::Canceled, res.error());
  2592. }
  2593. TEST(CancelTest, WithCancelLargePayload_Online) {
  2594. auto host = "httpbingo.org";
  2595. auto path = std::string{"/bytes/524288"};
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. auto port = 443;
  2598. SSLClient cli(host, port);
  2599. #else
  2600. auto port = 80;
  2601. Client cli(host, port);
  2602. #endif
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. uint32_t count = 0;
  2605. auto res =
  2606. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2607. ASSERT_TRUE(!res);
  2608. EXPECT_EQ(Error::Canceled, res.error());
  2609. }
  2610. TEST(CancelTest, NoCancelPost) {
  2611. Server svr;
  2612. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2613. res.set_content("Hello World!", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. cli.set_connection_timeout(std::chrono::seconds(5));
  2624. auto res =
  2625. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2626. "application/json", [](uint64_t, uint64_t) { return true; });
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. EXPECT_EQ("Hello World!", res->body);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. }
  2631. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2632. Server svr;
  2633. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2634. res.set_content("Hello World!", "text/plain");
  2635. });
  2636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2637. auto se = detail::scope_exit([&] {
  2638. svr.stop();
  2639. thread.join();
  2640. ASSERT_FALSE(svr.is_running());
  2641. });
  2642. svr.wait_until_ready();
  2643. Client cli(HOST, PORT);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, WithCancelLargePayloadPost) {
  2652. Server svr;
  2653. svr.set_payload_max_length(200 * 1024 * 1024);
  2654. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2655. res.set_content(LARGE_DATA, "text/plain");
  2656. });
  2657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2658. auto se = detail::scope_exit([&] {
  2659. svr.stop();
  2660. thread.join();
  2661. ASSERT_FALSE(svr.is_running());
  2662. });
  2663. svr.wait_until_ready();
  2664. Client cli(HOST, PORT);
  2665. cli.set_payload_max_length(200 * 1024 * 1024);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return false; });
  2670. ASSERT_TRUE(!res);
  2671. EXPECT_EQ(Error::Canceled, res.error());
  2672. }
  2673. TEST(CancelTest, NoCancelPut) {
  2674. Server svr;
  2675. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2676. res.set_content("Hello World!", "text/plain");
  2677. });
  2678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2679. auto se = detail::scope_exit([&] {
  2680. svr.stop();
  2681. thread.join();
  2682. ASSERT_FALSE(svr.is_running());
  2683. });
  2684. svr.wait_until_ready();
  2685. Client cli(HOST, PORT);
  2686. cli.set_connection_timeout(std::chrono::seconds(5));
  2687. auto res =
  2688. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2689. "application/json", [](uint64_t, uint64_t) { return true; });
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ("Hello World!", res->body);
  2692. EXPECT_EQ(StatusCode::OK_200, res->status);
  2693. }
  2694. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2695. Server svr;
  2696. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2697. res.set_content("Hello World!", "text/plain");
  2698. });
  2699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2700. auto se = detail::scope_exit([&] {
  2701. svr.stop();
  2702. thread.join();
  2703. ASSERT_FALSE(svr.is_running());
  2704. });
  2705. svr.wait_until_ready();
  2706. Client cli(HOST, PORT);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, WithCancelLargePayloadPut) {
  2715. Server svr;
  2716. svr.set_payload_max_length(200 * 1024 * 1024);
  2717. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2718. res.set_content(LARGE_DATA, "text/plain");
  2719. });
  2720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. Client cli(HOST, PORT);
  2728. cli.set_payload_max_length(200 * 1024 * 1024);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return false; });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelPatch) {
  2737. Server svr;
  2738. svr.Patch("/", [&](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.Patch("/", 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, WithCancelSmallPayloadPatch) {
  2758. Server svr;
  2759. svr.Patch("/", [&](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.Patch("/", 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, WithCancelLargePayloadPatch) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Patch("/", [&](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.Patch("/", 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, NoCancelDelete) {
  2800. Server svr;
  2801. svr.Delete("/", [&](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.Delete("/", 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, WithCancelSmallPayloadDelete) {
  2821. Server svr;
  2822. svr.Delete("/", [&](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.Delete("/", 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, WithCancelLargePayloadDelete) {
  2841. Server svr;
  2842. svr.set_payload_max_length(200 * 1024 * 1024);
  2843. svr.Delete("/", [&](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.Delete("/", 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. static std::string remove_whitespace(const std::string &input) {
  2863. std::string output;
  2864. output.reserve(input.size());
  2865. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2866. [](unsigned char c) { return !std::isspace(c); });
  2867. return output;
  2868. }
  2869. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2870. auto host = "httpbingo.org";
  2871. auto path = std::string{"/basic-auth/hello/world"};
  2872. #ifdef CPPHTTPLIB_SSL_ENABLED
  2873. auto port = 443;
  2874. SSLClient cli(host, port);
  2875. #else
  2876. auto port = 80;
  2877. Client cli(host, port);
  2878. #endif
  2879. {
  2880. auto res = cli.Get(path);
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2883. }
  2884. {
  2885. auto res = cli.Get(
  2886. path, Headers{make_basic_authentication_header("hello", "world")});
  2887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2888. auto body = remove_whitespace(res->body);
  2889. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2890. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. }
  2893. {
  2894. cli.set_basic_auth("hello", "world");
  2895. auto res = cli.Get(path);
  2896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2897. auto body = remove_whitespace(res->body);
  2898. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2899. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2900. EXPECT_EQ(StatusCode::OK_200, res->status);
  2901. }
  2902. {
  2903. cli.set_basic_auth("hello", "bad");
  2904. auto res = cli.Get(path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. {
  2909. cli.set_basic_auth("bad", "world");
  2910. auto res = cli.Get(path);
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2913. }
  2914. }
  2915. #ifdef CPPHTTPLIB_SSL_ENABLED
  2916. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2917. auto host = "httpbingo.org";
  2918. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2919. auto paths = std::vector<std::string>{
  2920. "/digest-auth/auth/hello/world/MD5",
  2921. "/digest-auth/auth/hello/world/SHA-256",
  2922. };
  2923. auto port = 443;
  2924. SSLClient cli(host, port);
  2925. {
  2926. auto res = cli.Get(unauth_path);
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2929. }
  2930. {
  2931. cli.set_digest_auth("hello", "world");
  2932. for (const auto &path : paths) {
  2933. auto res = cli.Get(path.c_str());
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. auto body = remove_whitespace(res->body);
  2936. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2937. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2938. EXPECT_EQ(StatusCode::OK_200, res->status);
  2939. }
  2940. cli.set_digest_auth("hello", "bad");
  2941. for (const auto &path : paths) {
  2942. auto res = cli.Get(path.c_str());
  2943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2944. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2945. }
  2946. }
  2947. }
  2948. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2949. // comma-separated list of challenges, and each challenge may itself carry a
  2950. // comma-separated auth-param list, so a server can legally offer Basic
  2951. // before Digest, either as two field lines or packed into one. Runs one 401
  2952. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2953. // value() joins them in receipt order) and checks that the retry carries a
  2954. // well-formed Digest Authorization header naming expected_realm.
  2955. static void
  2956. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2957. const std::string &expected_realm) {
  2958. std::atomic<int> hits{0};
  2959. Server svr;
  2960. svr.Get("/x", [&](const Request &req, Response &res) {
  2961. if (++hits == 1) {
  2962. res.status = StatusCode::Unauthorized_401;
  2963. for (const auto &challenge : challenges) {
  2964. res.set_header("WWW-Authenticate", challenge);
  2965. }
  2966. } else {
  2967. auto authorization = req.get_header_value("Authorization");
  2968. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2969. EXPECT_NE(std::string::npos,
  2970. authorization.find("realm=\"" + expected_realm + "\""));
  2971. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2972. res.set_content("ok", "text/plain");
  2973. }
  2974. });
  2975. auto port = svr.bind_to_any_port(HOST);
  2976. std::thread t([&]() { svr.listen_after_bind(); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. t.join();
  2980. });
  2981. svr.wait_until_ready();
  2982. Client cli(HOST, port);
  2983. cli.set_digest_auth("hello", "world");
  2984. auto res = cli.Get("/x");
  2985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2986. EXPECT_EQ(2, hits.load());
  2987. }
  2988. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2989. static const char *kDigestChallenge =
  2990. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2991. "algorithm=MD5";
  2992. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2993. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2994. "testrealm");
  2995. }
  2996. // Same challenge list with the schemes in the opposite order, to make sure
  2997. // the fix above didn't just special-case "Basic first".
  2998. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2999. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3000. "testrealm");
  3001. }
  3002. // A comma inside a quoted auth-param value must not be mistaken for the
  3003. // separator between two challenges (or two auth-params).
  3004. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3005. run_digest_challenge_list_test(
  3006. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3007. "algorithm=MD5"},
  3008. "test,realm");
  3009. }
  3010. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3011. // the params and leaves out the fragment.
  3012. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3013. Server svr;
  3014. std::string uri, target;
  3015. svr.Get("/a b", [&](const Request &req, Response &res) {
  3016. auto auth = req.get_header_value("Authorization");
  3017. if (auth.empty()) {
  3018. res.status = StatusCode::Unauthorized_401;
  3019. res.set_header("WWW-Authenticate",
  3020. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3021. return;
  3022. }
  3023. auto b = auth.find("uri=\"") + 5;
  3024. uri = auth.substr(b, auth.find('"', b) - b);
  3025. target = req.target;
  3026. });
  3027. auto port = svr.bind_to_any_port(HOST);
  3028. std::thread t([&]() { svr.listen_after_bind(); });
  3029. auto se = detail::scope_exit([&] {
  3030. svr.stop();
  3031. t.join();
  3032. });
  3033. svr.wait_until_ready();
  3034. Client cli(HOST, port);
  3035. cli.set_digest_auth("hello", "world");
  3036. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. EXPECT_EQ("/a%20b?x=1", target);
  3039. EXPECT_EQ(target, uri);
  3040. }
  3041. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3042. // make_digest_authentication_header() dereferences both unconditionally, so
  3043. // a server sending a challenge missing either one must not be treated as
  3044. // usable -- doing so used to crash the client with std::out_of_range.
  3045. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3048. res.status = StatusCode::Unauthorized_401;
  3049. res.set_header("WWW-Authenticate", challenge);
  3050. });
  3051. auto port = svr.bind_to_any_port(HOST);
  3052. std::thread t([&]() { svr.listen_after_bind(); });
  3053. auto se = detail::scope_exit([&] {
  3054. svr.stop();
  3055. t.join();
  3056. });
  3057. svr.wait_until_ready();
  3058. Client cli(HOST, port);
  3059. cli.set_digest_auth("hello", "world");
  3060. auto res = cli.Get("/x");
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3063. }
  3064. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3065. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3066. }
  3067. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3068. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3069. }
  3070. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3071. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3072. }
  3073. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3074. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3075. // when storing the values, so the header builder has to re-escape them (and
  3076. // keep algorithm a bare token); otherwise the value breaks out of its
  3077. // quoted-string and injects extra auth-params into the client's Authorization.
  3078. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3079. std::atomic<int> hits{0};
  3080. std::string authorization;
  3081. Server svr;
  3082. svr.Get("/x", [&](const Request &req, Response &res) {
  3083. if (++hits == 1) {
  3084. res.status = StatusCode::Unauthorized_401;
  3085. // On the wire the quotes embedded in the values are backslash-escaped.
  3086. res.set_header("WWW-Authenticate",
  3087. "Digest realm=\"testrealm\", "
  3088. "nonce=\"n\\\"; injected=\\\"x\", "
  3089. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3090. } else {
  3091. authorization = req.get_header_value("Authorization");
  3092. res.set_content("ok", "text/plain");
  3093. }
  3094. });
  3095. auto port = svr.bind_to_any_port(HOST);
  3096. std::thread t([&]() { svr.listen_after_bind(); });
  3097. auto se = detail::scope_exit([&] {
  3098. svr.stop();
  3099. t.join();
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_digest_auth("hello", "world");
  3104. auto res = cli.Get("/x");
  3105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3106. EXPECT_EQ(2, hits.load());
  3107. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3108. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3109. // inside its quoted-string rather than starting an "injected" auth-param.
  3110. EXPECT_NE(std::string::npos,
  3111. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3112. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3113. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3114. }
  3115. #endif
  3116. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3117. auto host = "google.com";
  3118. auto another_host = "example.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3128. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3131. auto host = "google.com";
  3132. auto wrong_ip = "0.0.0.0";
  3133. #ifdef CPPHTTPLIB_SSL_ENABLED
  3134. SSLClient cli(host);
  3135. #else
  3136. Client cli(host);
  3137. #endif
  3138. cli.set_hostname_addr_map({{host, wrong_ip}});
  3139. auto res = cli.Get("/");
  3140. ASSERT_TRUE(!res);
  3141. EXPECT_EQ(Error::Connection, res.error());
  3142. }
  3143. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3144. // A mapped value that is not an IP literal must be resolved. "localhost"
  3145. // resolves from the hosts file, so this test needs no external DNS.
  3146. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3147. auto host = "target.invalid";
  3148. Server svr;
  3149. std::string received_host;
  3150. svr.Get("/hi", [&](const Request &req, Response &res) {
  3151. received_host = req.get_header_value("Host");
  3152. res.set_content("Hello World!", "text/plain");
  3153. });
  3154. auto port = svr.bind_to_any_port(HOST);
  3155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. Client cli(host, port);
  3163. cli.set_hostname_addr_map({{host, HOST}});
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. // The mapping only redirects the connection; the identity stays host_.
  3168. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3169. }
  3170. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3171. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3172. auto host = "target.invalid";
  3173. Server svr;
  3174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3175. res.set_content("Hello World!", "text/plain");
  3176. });
  3177. auto port = svr.bind_to_any_port("127.0.0.1");
  3178. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3179. auto se = detail::scope_exit([&] {
  3180. svr.stop();
  3181. thread.join();
  3182. ASSERT_FALSE(svr.is_running());
  3183. });
  3184. svr.wait_until_ready();
  3185. Client cli(host, port);
  3186. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3187. auto res = cli.Get("/hi");
  3188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3189. EXPECT_EQ(StatusCode::OK_200, res->status);
  3190. }
  3191. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3192. // An empty mapped value must leave host_ as the connection target. Without
  3193. // that guard the empty value would become the host argument, getaddrinfo
  3194. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3195. // loopback - silently connecting somewhere the caller never asked for.
  3196. // The server listens on loopback, so such a fallback would succeed and is
  3197. // therefore observable as a failure of this test.
  3198. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3199. Server svr;
  3200. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3201. res.set_content("Hello World!", "text/plain");
  3202. });
  3203. auto port = svr.bind_to_any_port(HOST);
  3204. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3205. auto se = detail::scope_exit([&] {
  3206. svr.stop();
  3207. thread.join();
  3208. ASSERT_FALSE(svr.is_running());
  3209. });
  3210. svr.wait_until_ready();
  3211. Client cli(blackhole, port);
  3212. cli.set_hostname_addr_map({{blackhole, ""}});
  3213. cli.set_connection_timeout(1);
  3214. auto res = cli.Get("/hi");
  3215. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3216. }
  3217. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/absolute-redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(RelativeRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/relative-redirect/3"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. }
  3256. TEST(TooManyRedirectTest, Redirect_Online) {
  3257. auto host = "httpbingo.org";
  3258. auto path = std::string{"/redirect/21"};
  3259. #ifdef CPPHTTPLIB_SSL_ENABLED
  3260. SSLClient cli(host);
  3261. #else
  3262. Client cli(host);
  3263. #endif
  3264. cli.set_follow_location(true);
  3265. auto res = cli.Get(path);
  3266. ASSERT_TRUE(!res);
  3267. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3268. }
  3269. #ifdef CPPHTTPLIB_SSL_ENABLED
  3270. TEST(YahooRedirectTest, Redirect_Online) {
  3271. Client cli("yahoo.com");
  3272. auto res = cli.Get("/");
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3275. cli.set_follow_location(true);
  3276. res = cli.Get("/");
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3280. }
  3281. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3282. #define REDIR_HOST "httpbingo.org"
  3283. #define REDIR_PATH "/redirect-to"
  3284. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3285. SSLClient cli(REDIR_HOST);
  3286. cli.set_follow_location(true);
  3287. auto res =
  3288. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(StatusCode::OK_200, res->status);
  3291. }
  3292. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3293. SSLClient cli(REDIR_HOST);
  3294. cli.set_follow_location(true);
  3295. Params params;
  3296. params.emplace("url", "http://example.com");
  3297. params.emplace("status_code", "302");
  3298. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. }
  3302. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3303. SSLClient cli(REDIR_HOST);
  3304. cli.set_follow_location(true);
  3305. Params params;
  3306. params.emplace("url", "http://example.com");
  3307. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3309. EXPECT_EQ(StatusCode::OK_200, res->status);
  3310. }
  3311. TEST(UrlWithSpace, Redirect_Online) {
  3312. SSLClient cli("edge.forgecdn.net");
  3313. cli.set_follow_location(true);
  3314. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3316. EXPECT_EQ(StatusCode::OK_200, res->status);
  3317. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3318. }
  3319. #endif
  3320. #if !defined(_WIN32) && !defined(_WIN64)
  3321. TEST(ReceiveSignals, Signal) {
  3322. auto setupSignalHandlers = []() {
  3323. struct sigaction act;
  3324. sigemptyset(&act.sa_mask);
  3325. act.sa_flags = SA_SIGINFO;
  3326. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3327. switch (sig) {
  3328. case SIGINT:
  3329. default: break;
  3330. }
  3331. };
  3332. ::sigaction(SIGINT, &act, nullptr);
  3333. };
  3334. Server svr;
  3335. int port = 0;
  3336. auto thread = std::thread([&]() {
  3337. setupSignalHandlers();
  3338. port = svr.bind_to_any_port(HOST);
  3339. svr.listen_after_bind();
  3340. });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. ASSERT_TRUE(svr.is_running());
  3348. pthread_kill(thread.native_handle(), SIGINT);
  3349. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3350. ASSERT_TRUE(svr.is_running());
  3351. }
  3352. #endif
  3353. TEST(RedirectToDifferentPort, Redirect) {
  3354. Server svr1;
  3355. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3356. res.set_content("Hello World!", "text/plain");
  3357. });
  3358. int svr1_port = 0;
  3359. auto thread1 = std::thread([&]() {
  3360. svr1_port = svr1.bind_to_any_port(HOST);
  3361. svr1.listen_after_bind();
  3362. });
  3363. Server svr2;
  3364. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3365. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3366. });
  3367. int svr2_port = 0;
  3368. auto thread2 = std::thread([&]() {
  3369. svr2_port = svr2.bind_to_any_port(HOST);
  3370. svr2.listen_after_bind();
  3371. });
  3372. auto se = detail::scope_exit([&] {
  3373. svr2.stop();
  3374. thread2.join();
  3375. svr1.stop();
  3376. thread1.join();
  3377. ASSERT_FALSE(svr2.is_running());
  3378. ASSERT_FALSE(svr1.is_running());
  3379. });
  3380. svr1.wait_until_ready();
  3381. svr2.wait_until_ready();
  3382. Client cli("localhost", svr2_port);
  3383. cli.set_follow_location(true);
  3384. auto res = cli.Get("/2");
  3385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3386. EXPECT_EQ(StatusCode::OK_200, res->status);
  3387. EXPECT_EQ("Hello World!", res->body);
  3388. }
  3389. // GET /redir on one server redirects to /target on another port, so the
  3390. // client follows it with a new client.
  3391. static Result
  3392. GetThroughRedirectToDifferentPort(Server::Handler target,
  3393. const std::function<void(Client &)> &setup,
  3394. const Headers &headers = Headers()) {
  3395. Server target_svr;
  3396. target_svr.Get("/target", target);
  3397. int target_port = 0;
  3398. auto target_thread = std::thread([&]() {
  3399. target_port = target_svr.bind_to_any_port(HOST);
  3400. target_svr.listen_after_bind();
  3401. });
  3402. Server origin_svr;
  3403. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3404. res.set_redirect(
  3405. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3406. });
  3407. int origin_port = 0;
  3408. auto origin_thread = std::thread([&]() {
  3409. origin_port = origin_svr.bind_to_any_port(HOST);
  3410. origin_svr.listen_after_bind();
  3411. });
  3412. auto se = detail::scope_exit([&] {
  3413. origin_svr.stop();
  3414. origin_thread.join();
  3415. target_svr.stop();
  3416. target_thread.join();
  3417. });
  3418. target_svr.wait_until_ready();
  3419. origin_svr.wait_until_ready();
  3420. Client cli("localhost", origin_port);
  3421. cli.set_follow_location(true);
  3422. setup(cli);
  3423. return cli.Get("/redir", headers);
  3424. }
  3425. static void
  3426. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3427. std::string captured_authorization;
  3428. auto result = GetThroughRedirectToDifferentPort(
  3429. [&](const Request &req, Response &res) {
  3430. captured_authorization = req.get_header_value("Authorization");
  3431. res.set_content("OK", "text/plain");
  3432. },
  3433. set_auth);
  3434. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3435. EXPECT_EQ(StatusCode::OK_200, result->status);
  3436. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3437. EXPECT_TRUE(captured_authorization.empty());
  3438. }
  3439. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3440. TestDoNotForwardCredentialsOnRedirect(
  3441. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3442. }
  3443. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3444. TestDoNotForwardCredentialsOnRedirect(
  3445. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3446. }
  3447. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3448. std::string captured_cookie;
  3449. auto result = GetThroughRedirectToDifferentPort(
  3450. [&](const Request &req, Response &res) {
  3451. captured_cookie = req.get_header_value("Cookie");
  3452. res.set_content("OK", "text/plain");
  3453. },
  3454. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3455. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3456. EXPECT_EQ(StatusCode::OK_200, result->status);
  3457. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3458. EXPECT_TRUE(captured_cookie.empty());
  3459. }
  3460. TEST(RedirectToSamePort, ForwardCookie) {
  3461. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3462. // header so that ordinary session flows keep working.
  3463. Server svr;
  3464. std::string captured_cookie;
  3465. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3466. res.set_redirect("/target", 302);
  3467. });
  3468. svr.Get("/target", [&](const Request &req, Response &res) {
  3469. captured_cookie = req.get_header_value("Cookie");
  3470. res.set_content("OK", "text/plain");
  3471. });
  3472. auto port = svr.bind_to_any_port(HOST);
  3473. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3474. auto se = detail::scope_exit([&] {
  3475. svr.stop();
  3476. thread.join();
  3477. ASSERT_FALSE(svr.is_running());
  3478. });
  3479. svr.wait_until_ready();
  3480. Client cli(HOST, port);
  3481. cli.set_follow_location(true);
  3482. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3483. auto res = cli.Get("/redir", headers);
  3484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3487. }
  3488. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3489. std::string authorization;
  3490. std::string trace_id;
  3491. auto result = GetThroughRedirectToDifferentPort(
  3492. [&](const Request &req, Response &res) {
  3493. authorization = req.get_header_value("Authorization");
  3494. trace_id = req.get_header_value("X-Trace-Id");
  3495. res.set_content("OK", "text/plain");
  3496. },
  3497. [](Client &cli) {
  3498. cli.set_default_headers(
  3499. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3500. });
  3501. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3502. EXPECT_EQ(StatusCode::OK_200, result->status);
  3503. // Like a header given with the request, a default one goes along unless it
  3504. // carries credentials (RFC 9110 15.4).
  3505. EXPECT_TRUE(authorization.empty());
  3506. EXPECT_EQ("42", trace_id);
  3507. }
  3508. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3509. auto result = GetThroughRedirectToDifferentPort(
  3510. [](const Request &, Response &res) {
  3511. res.set_content(std::string(2048, 'x'), "text/plain");
  3512. },
  3513. [](Client &cli) { cli.set_payload_max_length(1024); });
  3514. EXPECT_FALSE(result);
  3515. }
  3516. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3517. auto result = GetThroughRedirectToDifferentPort(
  3518. [](const Request &req, Response &res) {
  3519. // Answer after a second, or once the client gives up.
  3520. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3521. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3522. }
  3523. res.set_content("late", "text/plain");
  3524. },
  3525. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3526. ASSERT_FALSE(result);
  3527. EXPECT_EQ(Error::Read, result.error());
  3528. }
  3529. #ifdef CPPHTTPLIB_SSL_ENABLED
  3530. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3531. auto result = GetThroughRedirectToDifferentPort(
  3532. [](const Request &, Response &res) {
  3533. res.status = StatusCode::Unauthorized_401;
  3534. res.set_header("WWW-Authenticate",
  3535. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3536. },
  3537. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3538. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3539. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3540. }
  3541. #endif
  3542. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3543. Server svr;
  3544. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3545. // Port number that overflows int — should not crash
  3546. res.set_redirect("http://localhost:99999999999999999999/target");
  3547. });
  3548. auto port = svr.bind_to_any_port(HOST);
  3549. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3550. auto se = detail::scope_exit([&] {
  3551. svr.stop();
  3552. thread.join();
  3553. ASSERT_FALSE(svr.is_running());
  3554. });
  3555. svr.wait_until_ready();
  3556. Client cli(HOST, port);
  3557. cli.set_follow_location(true);
  3558. auto res = cli.Get("/redir");
  3559. // Should fail gracefully, not crash (no valid response due to bad port)
  3560. EXPECT_FALSE(res);
  3561. }
  3562. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3563. Server svr;
  3564. auto port = svr.bind_to_any_port(HOST);
  3565. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3566. // The server's own port followed by junk must not be followed
  3567. res.set_redirect("http://" + std::string(HOST) + ":" +
  3568. std::to_string(port) + "junk/target");
  3569. });
  3570. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3571. res.set_content("target", "text/plain");
  3572. });
  3573. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3574. auto se = detail::scope_exit([&] {
  3575. svr.stop();
  3576. thread.join();
  3577. ASSERT_FALSE(svr.is_running());
  3578. });
  3579. svr.wait_until_ready();
  3580. Client cli(HOST, port);
  3581. cli.set_follow_location(true);
  3582. auto res = cli.Get("/redir");
  3583. EXPECT_FALSE(res);
  3584. }
  3585. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3586. Server svr;
  3587. std::atomic<bool> followed{false};
  3588. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3589. res.status = StatusCode::NotModified_304;
  3590. res.set_header("Location", "/target");
  3591. });
  3592. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3593. res.status = StatusCode::UseProxy_305;
  3594. res.set_header("Location", "/target");
  3595. });
  3596. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3597. followed = true;
  3598. res.set_content("target", "text/plain");
  3599. });
  3600. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3601. auto se = detail::scope_exit([&] {
  3602. svr.stop();
  3603. th.join();
  3604. ASSERT_FALSE(svr.is_running());
  3605. });
  3606. svr.wait_until_ready();
  3607. Client cli("localhost", PORT);
  3608. cli.set_follow_location(true);
  3609. auto res = cli.Get("/304");
  3610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3611. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3612. res = cli.Get("/305");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3615. EXPECT_FALSE(followed);
  3616. }
  3617. TEST(RedirectFromPageWithContent, Redirect) {
  3618. Server svr;
  3619. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3620. res.set_content("___", "text/plain");
  3621. res.set_redirect("/2");
  3622. });
  3623. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3624. res.set_content("Hello World!", "text/plain");
  3625. });
  3626. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. th.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. {
  3634. Client cli("localhost", PORT);
  3635. cli.set_follow_location(true);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ("Hello World!", body);
  3644. }
  3645. {
  3646. Client cli("localhost", PORT);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::Found_302, res->status);
  3654. EXPECT_EQ("___", body);
  3655. }
  3656. }
  3657. // A server can close the connection after a request with "Connection: close"
  3658. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3659. // redirected request must go out on a new connection.
  3660. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3661. #ifndef _WIN32
  3662. signal(SIGPIPE, SIG_IGN);
  3663. #endif
  3664. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3665. default_socket_options(srv);
  3666. sockaddr_in addr{};
  3667. addr.sin_family = AF_INET;
  3668. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3669. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3670. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3671. ASSERT_EQ(0, ::listen(srv, 2));
  3672. auto send_text = [](socket_t sock, const std::string &text) {
  3673. ::send(sock,
  3674. #ifdef _WIN32
  3675. static_cast<const char *>(text.c_str()),
  3676. static_cast<int>(text.size()),
  3677. #else
  3678. text.c_str(), text.size(),
  3679. #endif
  3680. 0);
  3681. };
  3682. auto reused = false;
  3683. auto server_thread = std::thread([&] {
  3684. char buf[4096];
  3685. auto first = ::accept(srv, nullptr, nullptr);
  3686. if (first == INVALID_SOCKET) { return; }
  3687. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3688. ::recv(first, buf, sizeof(buf), 0);
  3689. send_text(
  3690. first,
  3691. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3692. auto next = first;
  3693. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3694. reused = true;
  3695. } else {
  3696. detail::close_socket(first);
  3697. next = ::accept(srv, nullptr, nullptr);
  3698. if (next == INVALID_SOCKET) { return; }
  3699. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3700. ::recv(next, buf, sizeof(buf), 0);
  3701. }
  3702. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3703. "Connection: close\r\n\r\nok");
  3704. detail::close_socket(next);
  3705. });
  3706. Client cli("127.0.0.1", PORT + 2);
  3707. cli.set_follow_location(true);
  3708. cli.set_read_timeout(5, 0);
  3709. auto res = cli.Get("/1");
  3710. server_thread.join();
  3711. detail::close_socket(srv);
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. EXPECT_EQ("ok", res->body);
  3715. EXPECT_FALSE(reused);
  3716. }
  3717. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3718. Server svr;
  3719. auto port_str = std::to_string(PORT);
  3720. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3721. auto expected_host = "[::1]:" + port_str;
  3722. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3723. res.set_content("___", "text/plain");
  3724. // res.set_redirect("/2");
  3725. res.set_redirect(redirect_url);
  3726. });
  3727. svr.Get("/2", [&](const Request &req, Response &res) {
  3728. auto host_header = req.headers.find("Host");
  3729. ASSERT_TRUE(host_header != req.headers.end());
  3730. EXPECT_EQ(expected_host, host_header->second);
  3731. res.set_content("Hello World!", "text/plain");
  3732. });
  3733. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3734. auto se = detail::scope_exit([&] {
  3735. svr.stop();
  3736. th.join();
  3737. ASSERT_FALSE(svr.is_running());
  3738. });
  3739. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3740. // actually starts anything, so the condition !svr.is_running() will
  3741. // always remain true, and the loop never stops.
  3742. // This basically counts how many milliseconds have passed since the
  3743. // call to svr.listen(), and if after 5 seconds nothing started yet
  3744. // aborts the test.
  3745. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3746. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3747. ASSERT_LT(milliseconds, 5000U);
  3748. }
  3749. {
  3750. Client cli("::1", PORT);
  3751. cli.set_follow_location(true);
  3752. std::string body;
  3753. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3754. body.append(data, data_length);
  3755. return true;
  3756. });
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("Hello World!", body);
  3760. }
  3761. {
  3762. Client cli("::1", PORT);
  3763. std::string body;
  3764. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3765. body.append(data, data_length);
  3766. return true;
  3767. });
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::Found_302, res->status);
  3770. EXPECT_EQ("___", body);
  3771. }
  3772. }
  3773. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3774. Server svr;
  3775. svr.Get("/foo", [](const Request &req, Response &res) {
  3776. auto a = req.params.find("a");
  3777. if (a != req.params.end()) {
  3778. res.set_content((*a).second, "text/plain");
  3779. res.status = StatusCode::OK_200;
  3780. } else {
  3781. res.status = StatusCode::BadRequest_400;
  3782. }
  3783. });
  3784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, PORT);
  3793. cli.set_path_encode(false);
  3794. auto res = cli.Get("/foo?a=explicitly+encoded");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. // This expects it back with a space, as the `+` won't have been
  3798. // url-encoded, and server-side the params get decoded turning `+`
  3799. // into spaces.
  3800. EXPECT_EQ("explicitly encoded", res->body);
  3801. }
  3802. }
  3803. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3804. // When path encoding is disabled the client must transmit the supplied
  3805. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3806. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3807. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3808. // than a space (0x20). Assert on the raw wire target to catch this.
  3809. Server svr;
  3810. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3811. svr.Get("/foo", [&](const Request &req, Response &res) {
  3812. EXPECT_EQ(expected_target, req.target);
  3813. res.status = StatusCode::OK_200;
  3814. });
  3815. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3816. auto se = detail::scope_exit([&] {
  3817. svr.stop();
  3818. thread.join();
  3819. ASSERT_FALSE(svr.is_running());
  3820. });
  3821. svr.wait_until_ready();
  3822. {
  3823. Client cli(HOST, PORT);
  3824. cli.set_path_encode(false);
  3825. auto res = cli.Get(expected_target.c_str());
  3826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3827. EXPECT_EQ(StatusCode::OK_200, res->status);
  3828. }
  3829. }
  3830. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3831. // `open_stream()` used to skip the path encoding that the buffered send
  3832. // path applies, so the same `path` produced different bytes in the request
  3833. // line depending on which API was used. Assert the two agree.
  3834. Server svr;
  3835. std::string target;
  3836. svr.Get(".*", [&](const Request &req, Response &res) {
  3837. target = req.target;
  3838. res.status = StatusCode::OK_200;
  3839. });
  3840. auto port = svr.bind_to_any_port(HOST);
  3841. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3842. auto se = detail::scope_exit([&] {
  3843. svr.stop();
  3844. thread.join();
  3845. ASSERT_FALSE(svr.is_running());
  3846. });
  3847. svr.wait_until_ready();
  3848. struct {
  3849. const char *path;
  3850. const char *expected;
  3851. } cases[] = {
  3852. {"/a b?x=1", "/a%20b?x=1"},
  3853. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3854. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3855. };
  3856. for (const auto &c : cases) {
  3857. Client cli(HOST, port);
  3858. target.clear();
  3859. auto res = cli.Get(c.path);
  3860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3861. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3862. auto buffered_target = target;
  3863. target.clear();
  3864. auto handle = cli.open_stream("GET", c.path);
  3865. EXPECT_TRUE(handle.is_valid())
  3866. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3867. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3868. }
  3869. }
  3870. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3871. // The `set_path_encode(false)` contract — transmit the supplied target
  3872. // verbatim — must hold for the streaming API too.
  3873. Server svr;
  3874. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3875. std::string target;
  3876. svr.Get("/foo", [&](const Request &req, Response &res) {
  3877. target = req.target;
  3878. res.status = StatusCode::OK_200;
  3879. });
  3880. auto port = svr.bind_to_any_port(HOST);
  3881. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3882. auto se = detail::scope_exit([&] {
  3883. svr.stop();
  3884. thread.join();
  3885. ASSERT_FALSE(svr.is_running());
  3886. });
  3887. svr.wait_until_ready();
  3888. {
  3889. Client cli(HOST, port);
  3890. cli.set_path_encode(false);
  3891. auto handle = cli.open_stream("GET", expected_target);
  3892. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3893. EXPECT_EQ(expected_target, target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3897. // With path encoding enabled a CR/LF in the target is percent-encoded
  3898. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3899. // write_request_line still backstops `set_path_encode(false)`, which is
  3900. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3901. Server svr;
  3902. // Captured before routing: the decoded path contains a newline, which a
  3903. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3904. std::string target;
  3905. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3906. target = req.target;
  3907. res.status = StatusCode::OK_200;
  3908. return Server::HandlerResponse::Handled;
  3909. });
  3910. auto port = svr.bind_to_any_port(HOST);
  3911. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3912. auto se = detail::scope_exit([&] {
  3913. svr.stop();
  3914. thread.join();
  3915. ASSERT_FALSE(svr.is_running());
  3916. });
  3917. svr.wait_until_ready();
  3918. {
  3919. Client cli(HOST, port);
  3920. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3921. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3922. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3923. }
  3924. }
  3925. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3926. // Every control character is percent-encoded, not just CR/LF, so the target
  3927. // passes the request-target check in write_request_line.
  3928. Server svr;
  3929. std::string target;
  3930. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3931. target = req.target;
  3932. res.status = StatusCode::OK_200;
  3933. return Server::HandlerResponse::Handled;
  3934. });
  3935. auto port = svr.bind_to_any_port(HOST);
  3936. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli(HOST, port);
  3945. auto res = cli.Get("/a\tb\x1b\x7f");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ("/a%09b%1B%7F", target);
  3948. }
  3949. }
  3950. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3951. // Nothing may reach the wire: a raw CR/LF target would split the request
  3952. // line and inject headers.
  3953. Server svr;
  3954. // Pre-routing so that "not called" means nothing reached the server at all,
  3955. // rather than merely failing to match a handler pattern.
  3956. auto handler_called = false;
  3957. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3958. handler_called = true;
  3959. res.status = StatusCode::OK_200;
  3960. return Server::HandlerResponse::Handled;
  3961. });
  3962. auto port = svr.bind_to_any_port(HOST);
  3963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3964. auto se = detail::scope_exit([&] {
  3965. svr.stop();
  3966. thread.join();
  3967. ASSERT_FALSE(svr.is_running());
  3968. });
  3969. svr.wait_until_ready();
  3970. {
  3971. Client cli(HOST, port);
  3972. cli.set_path_encode(false);
  3973. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3974. EXPECT_FALSE(handle.is_valid());
  3975. EXPECT_EQ(Error::Write, handle.error);
  3976. EXPECT_FALSE(handler_called);
  3977. }
  3978. }
  3979. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3980. // Which of the two branches runs is decided by whether the query component
  3981. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3982. // an empty query and must still fall back to building one from
  3983. // `req.params`, while a non-empty query must win over `req.params`.
  3984. Server svr;
  3985. std::string target;
  3986. svr.Get("/foo", [&](const Request &req, Response &res) {
  3987. target = req.target;
  3988. res.status = StatusCode::OK_200;
  3989. });
  3990. auto port = svr.bind_to_any_port(HOST);
  3991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3992. auto se = detail::scope_exit([&] {
  3993. svr.stop();
  3994. thread.join();
  3995. ASSERT_FALSE(svr.is_running());
  3996. });
  3997. svr.wait_until_ready();
  3998. {
  3999. // Trailing `?` -> empty query component -> `req.params` is used.
  4000. Client cli(HOST, port);
  4001. Request req;
  4002. req.method = "GET";
  4003. req.path = "/foo?";
  4004. req.params.emplace("a", "1");
  4005. target.clear();
  4006. auto res = cli.send(req);
  4007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4008. EXPECT_EQ("/foo?a=1", target);
  4009. }
  4010. {
  4011. // Non-empty query in `req.path` -> `req.params` is not appended.
  4012. Client cli(HOST, port);
  4013. Request req;
  4014. req.method = "GET";
  4015. req.path = "/foo?b=2";
  4016. req.params.emplace("a", "1");
  4017. target.clear();
  4018. auto res = cli.send(req);
  4019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4020. EXPECT_EQ("/foo?b=2", target);
  4021. }
  4022. }
  4023. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4024. Server svr;
  4025. svr.Get("/", [](const Request &req, Response &) {
  4026. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4027. });
  4028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4029. auto se = detail::scope_exit([&] {
  4030. svr.stop();
  4031. thread.join();
  4032. ASSERT_FALSE(svr.is_running());
  4033. });
  4034. svr.wait_until_ready();
  4035. {
  4036. Client cli(HOST, PORT);
  4037. cli.set_path_encode(false);
  4038. auto res = cli.Get("/?something=%0A");
  4039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4040. EXPECT_EQ(StatusCode::OK_200, res->status);
  4041. }
  4042. }
  4043. TEST(BindServerTest, BindDualStack) {
  4044. Server svr;
  4045. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4046. res.set_content("Hello World!", "text/plain");
  4047. });
  4048. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4049. auto se = detail::scope_exit([&] {
  4050. svr.stop();
  4051. thread.join();
  4052. ASSERT_FALSE(svr.is_running());
  4053. });
  4054. svr.wait_until_ready();
  4055. {
  4056. Client cli("127.0.0.1", PORT);
  4057. auto res = cli.Get("/1");
  4058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4059. EXPECT_EQ(StatusCode::OK_200, res->status);
  4060. EXPECT_EQ("Hello World!", res->body);
  4061. }
  4062. {
  4063. Client cli("::1", PORT);
  4064. auto res = cli.Get("/1");
  4065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4066. EXPECT_EQ(StatusCode::OK_200, res->status);
  4067. EXPECT_EQ("Hello World!", res->body);
  4068. }
  4069. }
  4070. TEST(BindServerTest, BindAndListenSeparately) {
  4071. Server svr;
  4072. int port = svr.bind_to_any_port("0.0.0.0");
  4073. ASSERT_TRUE(svr.is_valid());
  4074. ASSERT_TRUE(port > 0);
  4075. svr.stop();
  4076. }
  4077. // Reports whether anything is still listening on a loopback port. A plain
  4078. // connect() is used instead of a Client request because a socket left bound by
  4079. // mistake accepts the connection into its backlog and never answers, which
  4080. // would hang the test instead of failing it.
  4081. static bool is_loopback_port_accepting(int port) {
  4082. sockaddr_in addr{};
  4083. addr.sin_family = AF_INET;
  4084. addr.sin_port = htons(static_cast<uint16_t>(port));
  4085. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4086. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4087. EXPECT_NE(sock, INVALID_SOCKET);
  4088. if (sock == INVALID_SOCKET) { return false; }
  4089. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4090. static_cast<socklen_t>(sizeof(addr)));
  4091. detail::close_socket(sock);
  4092. return ret == 0;
  4093. }
  4094. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4095. Server svr;
  4096. auto port = svr.bind_to_any_port("127.0.0.1");
  4097. ASSERT_TRUE(port > 0);
  4098. svr.stop();
  4099. // bind_to_any_port() already called listen(2), so until stop() closed the
  4100. // descriptor the port kept accepting connections into the backlog. ASSERT
  4101. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4102. // below blocks forever in the accept loop.
  4103. ASSERT_FALSE(is_loopback_port_accepting(port));
  4104. // Nothing is left to accept on, so listen_after_bind() must report failure
  4105. // instead of returning success without ever serving.
  4106. EXPECT_FALSE(svr.listen_after_bind());
  4107. // The failed listen marks the server decommissioned, so a waiter returns
  4108. // instead of spinning forever.
  4109. svr.wait_until_ready();
  4110. }
  4111. #ifdef CPPHTTPLIB_SSL_ENABLED
  4112. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4114. CLIENT_CA_CERT_DIR);
  4115. int port = svr.bind_to_any_port("0.0.0.0");
  4116. ASSERT_TRUE(svr.is_valid());
  4117. ASSERT_TRUE(port > 0);
  4118. svr.stop();
  4119. }
  4120. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4121. // or a rejected CustomRoute() registration would not stop the server binding.
  4122. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4123. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4124. CLIENT_CA_CERT_DIR);
  4125. ASSERT_TRUE(svr.is_valid());
  4126. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4127. EXPECT_FALSE(svr.is_valid());
  4128. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4129. }
  4130. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4131. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4132. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4133. int port = svr.bind_to_any_port("0.0.0.0");
  4134. ASSERT_TRUE(svr.is_valid());
  4135. ASSERT_TRUE(port > 0);
  4136. svr.stop();
  4137. }
  4138. TEST(BindServerTest, UpdateCertsPem) {
  4139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4140. int port = svr.bind_to_any_port("0.0.0.0");
  4141. ASSERT_TRUE(svr.is_valid());
  4142. ASSERT_TRUE(port > 0);
  4143. // Read PEM files
  4144. std::string cert_pem, key_pem, ca_pem;
  4145. read_file(SERVER_CERT_FILE, cert_pem);
  4146. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4147. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4148. // Update server certificates using PEM API
  4149. ASSERT_TRUE(
  4150. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4151. ASSERT_TRUE(svr.is_valid());
  4152. svr.stop();
  4153. }
  4154. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4155. // Start server with client CA (enables client auth)
  4156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4157. ASSERT_TRUE(svr.is_valid());
  4158. bool handler_called = false;
  4159. svr.Get("/test", [&](const Request &req, Response &res) {
  4160. handler_called = true;
  4161. // Verify client certificate is present
  4162. auto cert = req.peer_cert();
  4163. EXPECT_TRUE(static_cast<bool>(cert));
  4164. res.set_content("ok", "text/plain");
  4165. });
  4166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4167. auto se = detail::scope_exit([&] {
  4168. svr.stop();
  4169. t.join();
  4170. ASSERT_FALSE(svr.is_running());
  4171. });
  4172. svr.wait_until_ready();
  4173. // Read PEM files
  4174. std::string cert_pem, key_pem, ca_pem;
  4175. read_file(SERVER_CERT_FILE, cert_pem);
  4176. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4177. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4178. // Update server certificates and client CA using PEM API while server running
  4179. ASSERT_TRUE(
  4180. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4181. // Connect with client certificate
  4182. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4183. cli.enable_server_certificate_verification(false);
  4184. cli.set_connection_timeout(30);
  4185. auto res = cli.Get("/test");
  4186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4187. ASSERT_EQ(StatusCode::OK_200, res->status);
  4188. ASSERT_TRUE(handler_called);
  4189. EXPECT_EQ("ok", res->body);
  4190. }
  4191. // Puts a CA that did not sign the client's certificate in the old one's place.
  4192. static bool replace_client_ca(SSLServer &svr) {
  4193. std::string cert_pem, key_pem, ca_pem;
  4194. read_file(SERVER_CERT_FILE, cert_pem);
  4195. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4196. read_file(SERVER_CERT2_FILE, ca_pem);
  4197. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4198. ca_pem.c_str());
  4199. }
  4200. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4202. ASSERT_TRUE(svr.is_valid());
  4203. svr.Get("/test", [](const Request &, Response &res) {
  4204. res.set_content("ok", "text/plain");
  4205. });
  4206. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4207. auto se = detail::scope_exit([&] {
  4208. svr.stop();
  4209. t.join();
  4210. ASSERT_FALSE(svr.is_running());
  4211. });
  4212. svr.wait_until_ready();
  4213. auto get = [] {
  4214. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4215. cli.enable_server_certificate_verification(false);
  4216. return cli.Get("/test");
  4217. };
  4218. ASSERT_TRUE(get());
  4219. ASSERT_TRUE(replace_client_ca(svr));
  4220. EXPECT_FALSE(get());
  4221. }
  4222. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4223. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4225. ASSERT_TRUE(svr.is_valid());
  4226. tls::set_verify_callback(svr.tls_context(),
  4227. [](const tls::VerifyContext &) -> bool {
  4228. throw std::runtime_error("verify");
  4229. });
  4230. svr.Get("/test", [](const Request &, Response &res) {
  4231. res.set_content("ok", "text/plain");
  4232. });
  4233. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4234. auto se = detail::scope_exit([&] {
  4235. svr.stop();
  4236. t.join();
  4237. ASSERT_FALSE(svr.is_running());
  4238. });
  4239. svr.wait_until_ready();
  4240. auto get = [] {
  4241. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4242. cli.enable_server_certificate_verification(false);
  4243. return cli.Get("/test");
  4244. };
  4245. EXPECT_FALSE(get());
  4246. // The handshake is over, so an update does not wait for it.
  4247. std::string cert_pem, key_pem;
  4248. read_file(SERVER_CERT_FILE, cert_pem);
  4249. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4250. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4251. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4252. return v.preverify_ok;
  4253. });
  4254. auto res = get();
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ("ok", res->body);
  4257. }
  4258. #endif
  4259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4260. // Sends each request over a new connection with a client certificate,
  4261. // resuming the session of the one before when there is one.
  4262. class ResumingClient {
  4263. public:
  4264. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4265. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4266. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4267. SSL_FILETYPE_PEM);
  4268. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4269. // callback, not through SSL_get1_session().
  4270. SSL_CTX_set_app_data(ctx_, this);
  4271. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4272. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4273. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4274. auto self = static_cast<ResumingClient *>(
  4275. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4276. SSL_SESSION_free(self->session_);
  4277. self->session_ = session;
  4278. return 1; // Keeps the reference
  4279. });
  4280. }
  4281. ~ResumingClient() {
  4282. SSL_SESSION_free(session_);
  4283. SSL_CTX_free(ctx_);
  4284. }
  4285. // Tells whether the request was answered.
  4286. bool get() {
  4287. auto error = Error::Success;
  4288. auto sock = detail::create_client_socket(
  4289. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4290. /*connection_timeout_sec=*/5, 0,
  4291. /*read_timeout_sec=*/5, 0,
  4292. /*write_timeout_sec=*/5, 0, std::string(), error);
  4293. if (sock == INVALID_SOCKET) { return false; }
  4294. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4295. auto ssl = SSL_new(ctx_);
  4296. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4297. SSL_set_fd(ssl, static_cast<int>(sock));
  4298. if (session_) { SSL_set_session(ssl, session_); }
  4299. if (SSL_connect(ssl) != 1) { return false; }
  4300. reused_ = SSL_session_reused(ssl) == 1;
  4301. // Reading the response also takes in a TLS 1.3 session ticket.
  4302. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4303. "Connection: close\r\n\r\n";
  4304. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4305. std::string res;
  4306. char buf[256];
  4307. int n;
  4308. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4309. res.append(buf, static_cast<size_t>(n));
  4310. }
  4311. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4312. SSL_shutdown(ssl);
  4313. return res.find("200 OK") != std::string::npos;
  4314. }
  4315. // Whether the last connection resumed a session
  4316. bool reused() const { return reused_; }
  4317. private:
  4318. SSL_CTX *ctx_;
  4319. SSL_SESSION *session_ = nullptr;
  4320. bool reused_ = false;
  4321. };
  4322. // A client that resumes its session gets through, but not once the client CA
  4323. // has changed, as a resumed session does not show the certificate again.
  4324. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4326. ASSERT_TRUE(svr.is_valid());
  4327. svr.Get("/test", [](const Request &, Response &res) {
  4328. res.set_content("ok", "text/plain");
  4329. });
  4330. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4331. auto se = detail::scope_exit([&] {
  4332. svr.stop();
  4333. t.join();
  4334. ASSERT_FALSE(svr.is_running());
  4335. });
  4336. svr.wait_until_ready();
  4337. ResumingClient cli;
  4338. ASSERT_TRUE(cli.get());
  4339. ASSERT_TRUE(cli.get());
  4340. EXPECT_TRUE(cli.reused());
  4341. ASSERT_TRUE(replace_client_ca(svr));
  4342. EXPECT_FALSE(cli.get());
  4343. }
  4344. // A resumed session does not show the certificate again, so the server does
  4345. // not resume one with a verify callback to run on it.
  4346. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4348. ASSERT_TRUE(svr.is_valid());
  4349. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4350. return v.preverify_ok;
  4351. });
  4352. svr.Get("/test", [](const Request &, Response &res) {
  4353. res.set_content("ok", "text/plain");
  4354. });
  4355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4356. auto se = detail::scope_exit([&] {
  4357. svr.stop();
  4358. t.join();
  4359. ASSERT_FALSE(svr.is_running());
  4360. });
  4361. svr.wait_until_ready();
  4362. ResumingClient cli;
  4363. ASSERT_TRUE(cli.get());
  4364. ASSERT_TRUE(cli.get());
  4365. EXPECT_FALSE(cli.reused());
  4366. }
  4367. #endif
  4368. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4369. // wolfSSL shares its session cache between contexts, so a resumed session
  4370. // could carry a client certificate checked against another server's CA, or
  4371. // against a client CA since replaced.
  4372. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4374. ASSERT_TRUE(svr.is_valid());
  4375. // Trusts a CA that did not sign the client's certificate.
  4376. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4377. ASSERT_TRUE(other.is_valid());
  4378. for (auto s : {&svr, &other}) {
  4379. s->Get("/test", [](const Request &, Response &res) {
  4380. res.set_content("ok", "text/plain");
  4381. });
  4382. }
  4383. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4384. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4385. auto se = detail::scope_exit([&] {
  4386. other.stop();
  4387. svr.stop();
  4388. t2.join();
  4389. t.join();
  4390. });
  4391. svr.wait_until_ready();
  4392. other.wait_until_ready();
  4393. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4394. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4395. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4396. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4397. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4398. ASSERT_EQ(WOLFSSL_SUCCESS,
  4399. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4400. WOLFSSL_FILETYPE_PEM));
  4401. WOLFSSL_SESSION *session = nullptr;
  4402. auto session_se = detail::scope_exit([&] {
  4403. if (session) { wolfSSL_SESSION_free(session); }
  4404. });
  4405. // A request over a new connection, resuming `session` when there is one and
  4406. // keeping the connection's own in its place. Tells whether it was answered.
  4407. auto get = [&](int port) {
  4408. auto error = Error::Success;
  4409. auto sock = detail::create_client_socket(
  4410. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4411. /*connection_timeout_sec=*/5, 0,
  4412. /*read_timeout_sec=*/5, 0,
  4413. /*write_timeout_sec=*/5, 0, std::string(), error);
  4414. if (sock == INVALID_SOCKET) { return false; }
  4415. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4416. auto ssl = wolfSSL_new(ctx);
  4417. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4418. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4419. if (session) { wolfSSL_set_session(ssl, session); }
  4420. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4421. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4422. "Connection: close\r\n\r\n";
  4423. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4424. std::string res;
  4425. char buf[256];
  4426. int n;
  4427. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4428. res.append(buf, static_cast<size_t>(n));
  4429. }
  4430. wolfSSL_shutdown(ssl);
  4431. if (session) { wolfSSL_SESSION_free(session); }
  4432. session = wolfSSL_get1_session(ssl);
  4433. return res.find("200 OK") != std::string::npos;
  4434. };
  4435. ASSERT_TRUE(get(PORT));
  4436. EXPECT_FALSE(get(PORT + 1));
  4437. ASSERT_TRUE(get(PORT));
  4438. ASSERT_TRUE(replace_client_ca(svr));
  4439. EXPECT_FALSE(get(PORT));
  4440. }
  4441. #endif
  4442. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4444. ASSERT_TRUE(svr.is_valid());
  4445. svr.Get("/test", [](const Request &, Response &res) {
  4446. res.set_content("ok", "text/plain");
  4447. });
  4448. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4449. auto se = detail::scope_exit([&] {
  4450. svr.stop();
  4451. t.join();
  4452. ASSERT_FALSE(svr.is_running());
  4453. });
  4454. svr.wait_until_ready();
  4455. // A connection that sends no ClientHello keeps its handshake in progress,
  4456. // once the server has had a moment to start it.
  4457. auto error = Error::Success;
  4458. auto sock = detail::create_client_socket(
  4459. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4460. /*connection_timeout_sec=*/5, 0,
  4461. /*read_timeout_sec=*/5, 0,
  4462. /*write_timeout_sec=*/5, 0, std::string(), error);
  4463. ASSERT_NE(INVALID_SOCKET, sock);
  4464. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4465. std::string cert_pem, key_pem;
  4466. read_file(SERVER_CERT_FILE, cert_pem);
  4467. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4468. auto update = std::async(std::launch::async, [&]() {
  4469. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4470. });
  4471. EXPECT_EQ(std::future_status::timeout,
  4472. update.wait_for(std::chrono::milliseconds(200)));
  4473. detail::close_socket(sock);
  4474. EXPECT_TRUE(update.get());
  4475. SSLClient cli(HOST, PORT);
  4476. cli.enable_server_certificate_verification(false);
  4477. auto res = cli.Get("/test");
  4478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4479. EXPECT_EQ(StatusCode::OK_200, res->status);
  4480. }
  4481. #endif
  4482. TEST(ErrorHandlerTest, ContentLength) {
  4483. Server svr;
  4484. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4485. res.status = StatusCode::OK_200;
  4486. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4487. "text/html"); // <= Content-Length still 13
  4488. });
  4489. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4490. res.set_content("Hello World!\n", "text/plain");
  4491. res.status = 524;
  4492. });
  4493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4494. auto se = detail::scope_exit([&] {
  4495. svr.stop();
  4496. thread.join();
  4497. ASSERT_FALSE(svr.is_running());
  4498. });
  4499. svr.wait_until_ready();
  4500. {
  4501. Client cli(HOST, PORT);
  4502. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::OK_200, res->status);
  4505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4506. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4507. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4508. }
  4509. }
  4510. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4511. TEST(ExceptionTest, WithoutExceptionHandler) {
  4512. Server svr;
  4513. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4514. throw std::runtime_error("exception...");
  4515. });
  4516. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4517. throw std::runtime_error("exception\r\n...");
  4518. });
  4519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4520. auto se = detail::scope_exit([&] {
  4521. svr.stop();
  4522. listen_thread.join();
  4523. ASSERT_FALSE(svr.is_running());
  4524. });
  4525. svr.wait_until_ready();
  4526. Client cli("localhost", PORT);
  4527. {
  4528. auto res = cli.Get("/exception");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4531. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4532. }
  4533. {
  4534. auto res = cli.Get("/unknown");
  4535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4536. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4537. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4538. }
  4539. }
  4540. TEST(ExceptionTest, WithExceptionHandler) {
  4541. Server svr;
  4542. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4543. std::exception_ptr ep) {
  4544. EXPECT_FALSE(ep == nullptr);
  4545. try {
  4546. std::rethrow_exception(ep);
  4547. } catch (std::exception &e) {
  4548. EXPECT_EQ("abc", std::string(e.what()));
  4549. } catch (...) {}
  4550. res.status = StatusCode::InternalServerError_500;
  4551. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4552. "text/html"); // <= Content-Length still 13 at this point
  4553. });
  4554. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4555. res.set_content("Hello World!\n", "text/plain");
  4556. throw std::runtime_error("abc");
  4557. });
  4558. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4559. auto se = detail::scope_exit([&] {
  4560. svr.stop();
  4561. thread.join();
  4562. ASSERT_FALSE(svr.is_running());
  4563. });
  4564. svr.wait_until_ready();
  4565. for (size_t i = 0; i < 10; i++) {
  4566. Client cli(HOST, PORT);
  4567. for (size_t j = 0; j < 100; j++) {
  4568. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4571. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4572. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4573. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4574. }
  4575. cli.set_keep_alive(true);
  4576. for (size_t j = 0; j < 100; j++) {
  4577. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4579. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4580. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4581. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4583. }
  4584. }
  4585. }
  4586. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4587. Server svr;
  4588. svr.set_exception_handler(
  4589. [](const Request &, Response &res, std::exception_ptr) {
  4590. res.set_content("oops", "text/plain");
  4591. });
  4592. svr.Get("/throw", [](const Request &, Response &) {
  4593. throw std::runtime_error("throw");
  4594. });
  4595. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4596. res.status = StatusCode::Created_201;
  4597. throw std::runtime_error("created-then-throw");
  4598. });
  4599. auto port = svr.bind_to_any_port(HOST);
  4600. ASSERT_GT(port, 0);
  4601. thread t = thread([&] { svr.listen_after_bind(); });
  4602. auto se = detail::scope_exit([&] {
  4603. svr.stop();
  4604. t.join();
  4605. ASSERT_FALSE(svr.is_running());
  4606. });
  4607. svr.wait_until_ready();
  4608. Client cli(HOST, port);
  4609. for (auto path : {"/throw", "/created-then-throw"}) {
  4610. auto res = cli.Get(path);
  4611. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4612. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4613. }
  4614. }
  4615. TEST(ExceptionTest, AndErrorHandler) {
  4616. Server svr;
  4617. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4618. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4619. });
  4620. svr.set_exception_handler(
  4621. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4622. EXPECT_FALSE(ep == nullptr);
  4623. try {
  4624. std::rethrow_exception(ep);
  4625. } catch (std::exception &e) {
  4626. res.set_content(e.what(), "text/html");
  4627. } catch (...) {}
  4628. res.status = StatusCode::InternalServerError_500;
  4629. });
  4630. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4631. throw std::runtime_error("EXCEPTION");
  4632. });
  4633. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4634. res.set_content("ERROR", "text/html");
  4635. res.status = StatusCode::InternalServerError_500;
  4636. });
  4637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4638. auto se = detail::scope_exit([&] {
  4639. svr.stop();
  4640. thread.join();
  4641. ASSERT_FALSE(svr.is_running());
  4642. });
  4643. svr.wait_until_ready();
  4644. Client cli(HOST, PORT);
  4645. {
  4646. auto res = cli.Get("/exception");
  4647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4648. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4649. EXPECT_EQ("EXCEPTION", res->body);
  4650. }
  4651. {
  4652. auto res = cli.Get("/error");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4655. EXPECT_EQ("ERROR", res->body);
  4656. }
  4657. {
  4658. auto res = cli.Get("/invalid");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4661. EXPECT_EQ("NOT_FOUND", res->body);
  4662. }
  4663. }
  4664. #endif
  4665. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4666. // An exception from a user callback outside process_request()'s try/catch
  4667. // used to unwind into the task queue - which does not catch - and terminate
  4668. // the process. Each test below runs the server on a single worker thread: a
  4669. // guard that catches the exception but still loses the thread would otherwise
  4670. // be hidden by a spare worker serving the follow-up request. Note that a
  4671. // regression here aborts the whole test binary rather than failing one test.
  4672. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4673. Server svr;
  4674. svr.new_task_queue = [] { return new ThreadPool(1); };
  4675. std::atomic<int> reported{0};
  4676. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4677. if (err == Error::UserCallbackException) { reported++; }
  4678. });
  4679. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4680. res.set_content_provider(
  4681. 1024, "text/plain",
  4682. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4683. sink.write("hello", 5);
  4684. throw std::runtime_error("from the content provider");
  4685. });
  4686. });
  4687. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4688. res.set_content("ok", "text/plain");
  4689. });
  4690. auto port = svr.bind_to_any_port(HOST);
  4691. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4692. auto se = detail::scope_exit([&] {
  4693. svr.stop();
  4694. listen_thread.join();
  4695. ASSERT_FALSE(svr.is_running());
  4696. });
  4697. svr.wait_until_ready();
  4698. {
  4699. Client cli(HOST, port);
  4700. cli.set_read_timeout(5, 0);
  4701. EXPECT_FALSE(cli.Get("/throw"));
  4702. }
  4703. EXPECT_TRUE(svr.is_running());
  4704. EXPECT_EQ(1, reported.load());
  4705. // A request on a fresh connection is still served.
  4706. {
  4707. Client cli(HOST, port);
  4708. auto res = cli.Get("/ok");
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. EXPECT_EQ("ok", res->body);
  4712. }
  4713. }
  4714. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4715. Server svr;
  4716. svr.new_task_queue = [] { return new ThreadPool(1); };
  4717. std::atomic<bool> should_throw{true};
  4718. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4719. res.set_content("hi", "text/plain");
  4720. });
  4721. svr.set_post_routing_handler(
  4722. [&](const Request & /*req*/, Response & /*res*/) {
  4723. if (should_throw) {
  4724. throw std::runtime_error("from the post-routing handler");
  4725. }
  4726. });
  4727. auto port = svr.bind_to_any_port(HOST);
  4728. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4729. auto se = detail::scope_exit([&] {
  4730. svr.stop();
  4731. listen_thread.join();
  4732. ASSERT_FALSE(svr.is_running());
  4733. });
  4734. svr.wait_until_ready();
  4735. {
  4736. Client cli(HOST, port);
  4737. cli.set_read_timeout(5, 0);
  4738. EXPECT_FALSE(cli.Get("/hi"));
  4739. }
  4740. EXPECT_TRUE(svr.is_running());
  4741. should_throw = false;
  4742. {
  4743. Client cli(HOST, port);
  4744. auto res = cli.Get("/hi");
  4745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. EXPECT_EQ("hi", res->body);
  4748. }
  4749. }
  4750. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4751. // The guard reports the caught exception through the error logger, which is
  4752. // a user callback too. A logger that throws has to be contained as well, or
  4753. // the process would terminate from inside the catch.
  4754. Server svr;
  4755. svr.new_task_queue = [] { return new ThreadPool(1); };
  4756. std::atomic<int> reported{0};
  4757. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4758. if (err == Error::UserCallbackException) {
  4759. reported++;
  4760. throw std::runtime_error("from the error logger");
  4761. }
  4762. });
  4763. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4764. res.set_content_provider(
  4765. 1024, "text/plain",
  4766. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4767. sink.write("hello", 5);
  4768. throw std::runtime_error("from the content provider");
  4769. });
  4770. });
  4771. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4772. res.set_content("ok", "text/plain");
  4773. });
  4774. auto port = svr.bind_to_any_port(HOST);
  4775. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4776. auto se = detail::scope_exit([&] {
  4777. svr.stop();
  4778. listen_thread.join();
  4779. ASSERT_FALSE(svr.is_running());
  4780. });
  4781. svr.wait_until_ready();
  4782. {
  4783. Client cli(HOST, port);
  4784. cli.set_read_timeout(5, 0);
  4785. EXPECT_FALSE(cli.Get("/throw"));
  4786. }
  4787. EXPECT_TRUE(svr.is_running());
  4788. EXPECT_EQ(1, reported.load());
  4789. {
  4790. Client cli(HOST, port);
  4791. auto res = cli.Get("/ok");
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ("ok", res->body);
  4795. }
  4796. }
  4797. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4798. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4799. // so the exception unwinds through the ws::WebSocket object on its way to
  4800. // the guard. None of the HTTP cases above cross that.
  4801. Server svr;
  4802. svr.new_task_queue = [] { return new ThreadPool(1); };
  4803. std::atomic<int> reported{0};
  4804. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4805. if (err == Error::UserCallbackException) { reported++; }
  4806. });
  4807. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4808. throw std::runtime_error("from the WebSocket handler");
  4809. });
  4810. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4811. res.set_content("ok", "text/plain");
  4812. });
  4813. auto port = svr.bind_to_any_port(HOST);
  4814. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. listen_thread.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. {
  4822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4823. "/ws");
  4824. auto res = client.connect();
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. // The server dropped the connection instead of dying.
  4827. std::string msg;
  4828. EXPECT_FALSE(client.read(msg));
  4829. client.close();
  4830. }
  4831. EXPECT_TRUE(svr.is_running());
  4832. EXPECT_EQ(1, reported.load());
  4833. {
  4834. Client cli(HOST, port);
  4835. auto res = cli.Get("/ok");
  4836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4837. EXPECT_EQ(StatusCode::OK_200, res->status);
  4838. EXPECT_EQ("ok", res->body);
  4839. }
  4840. }
  4841. #ifdef CPPHTTPLIB_SSL_ENABLED
  4842. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4843. // SSLServer::process_and_close_socket() is a separate overload with its own
  4844. // guard, so it is exercised on its own.
  4845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4846. ASSERT_TRUE(svr.is_valid());
  4847. svr.new_task_queue = [] { return new ThreadPool(1); };
  4848. std::atomic<int> reported{0};
  4849. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4850. if (err == Error::UserCallbackException) { reported++; }
  4851. });
  4852. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4853. res.set_content_provider(
  4854. 1024, "text/plain",
  4855. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4856. sink.write("hello", 5);
  4857. throw std::runtime_error("from the content provider");
  4858. });
  4859. });
  4860. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4861. res.set_content("ok", "text/plain");
  4862. });
  4863. auto port = svr.bind_to_any_port(HOST);
  4864. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4865. auto se = detail::scope_exit([&] {
  4866. svr.stop();
  4867. listen_thread.join();
  4868. ASSERT_FALSE(svr.is_running());
  4869. });
  4870. svr.wait_until_ready();
  4871. {
  4872. SSLClient cli(HOST, port);
  4873. cli.enable_server_certificate_verification(false);
  4874. cli.set_read_timeout(5, 0);
  4875. EXPECT_FALSE(cli.Get("/throw"));
  4876. }
  4877. EXPECT_TRUE(svr.is_running());
  4878. EXPECT_EQ(1, reported.load());
  4879. {
  4880. SSLClient cli(HOST, port);
  4881. cli.enable_server_certificate_verification(false);
  4882. auto res = cli.Get("/ok");
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ(StatusCode::OK_200, res->status);
  4885. EXPECT_EQ("ok", res->body);
  4886. }
  4887. }
  4888. #endif
  4889. #endif
  4890. TEST(NoContentTest, ContentLength) {
  4891. Server svr;
  4892. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4893. res.status = StatusCode::NoContent_204;
  4894. });
  4895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4896. auto se = detail::scope_exit([&] {
  4897. svr.stop();
  4898. thread.join();
  4899. ASSERT_FALSE(svr.is_running());
  4900. });
  4901. svr.wait_until_ready();
  4902. {
  4903. Client cli(HOST, PORT);
  4904. auto res = cli.Get("/hi");
  4905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4906. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4907. // RFC 9110 8.6: none in a 204 response
  4908. EXPECT_FALSE(res->has_header("Content-Length"));
  4909. }
  4910. }
  4911. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4912. Server svr;
  4913. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4914. res.set_header("Content-Length", "5");
  4915. res.set_content("hello world", "text/plain");
  4916. });
  4917. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4918. // A body that reads as the last chunk, were it taken as chunked
  4919. res.set_header("Transfer-Encoding", "chunked");
  4920. res.set_content("0\r\n\r\n", "text/plain");
  4921. });
  4922. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4923. res.set_header("Content-Length", "2");
  4924. res.set_content_provider(5, "text/plain",
  4925. [](size_t offset, size_t length, DataSink &sink) {
  4926. sink.write(&"hello"[offset], length);
  4927. return true;
  4928. });
  4929. });
  4930. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4931. res.set_header("Content-Length", "1234");
  4932. });
  4933. thread t = thread([&] { svr.listen(HOST, PORT); });
  4934. auto se = detail::scope_exit([&] {
  4935. svr.stop();
  4936. t.join();
  4937. ASSERT_FALSE(svr.is_running());
  4938. });
  4939. svr.wait_until_ready();
  4940. Client cli(HOST, PORT);
  4941. cli.set_read_timeout(1, 0);
  4942. auto expect_body = [&](const Result &res, const std::string &body) {
  4943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4944. EXPECT_EQ(body, res->body);
  4945. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4946. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4947. };
  4948. Headers identity{{"Accept-Encoding", ""}};
  4949. expect_body(cli.Get("/body", identity), "hello world");
  4950. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4951. expect_body(cli.Get("/body",
  4952. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4953. "he");
  4954. expect_body(cli.Get("/provider", identity), "hello");
  4955. expect_body(cli.Get("/empty", identity), "");
  4956. // A HEAD response may give the length of the body a GET would get.
  4957. auto res = cli.Head("/empty");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4960. }
  4961. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4962. Server svr;
  4963. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4964. res.set_content("short", "text/plain");
  4965. });
  4966. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4967. res.body += " with a footer";
  4968. res.set_header("Transfer-Encoding", "chunked");
  4969. });
  4970. thread t = thread([&] { svr.listen(HOST, PORT); });
  4971. auto se = detail::scope_exit([&] {
  4972. svr.stop();
  4973. t.join();
  4974. ASSERT_FALSE(svr.is_running());
  4975. });
  4976. svr.wait_until_ready();
  4977. Client cli(HOST, PORT);
  4978. cli.set_read_timeout(1, 0);
  4979. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ("short with a footer", res->body);
  4982. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4983. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4984. }
  4985. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4986. Server svr;
  4987. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4988. res.set_header("Content-Length", "3");
  4989. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4990. sink.write("abc", 3);
  4991. sink.done();
  4992. return true;
  4993. });
  4994. });
  4995. thread t = thread([&] { svr.listen(HOST, PORT); });
  4996. auto se = detail::scope_exit([&] {
  4997. svr.stop();
  4998. t.join();
  4999. ASSERT_FALSE(svr.is_running());
  5000. });
  5001. svr.wait_until_ready();
  5002. Client cli(HOST, PORT);
  5003. cli.set_keep_alive(true);
  5004. auto res = cli.Get("/");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ("abc", res->body);
  5007. EXPECT_FALSE(res->has_header("Content-Length"));
  5008. EXPECT_EQ("close", res->get_header_value("Connection"));
  5009. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5010. // No body to delimit
  5011. auto head = cli.Head("/");
  5012. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5013. EXPECT_FALSE(head->has_header("Connection"));
  5014. }
  5015. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5016. #ifdef CPPHTTPLIB_SSL_ENABLED
  5017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5018. ASSERT_TRUE(svr.is_valid());
  5019. #else
  5020. Server svr;
  5021. #endif
  5022. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5023. if (req.path == "/routing_handler") {
  5024. res.set_header("PRE_ROUTING", "on");
  5025. res.set_content("Routing Handler", "text/plain");
  5026. return httplib::Server::HandlerResponse::Handled;
  5027. }
  5028. return httplib::Server::HandlerResponse::Unhandled;
  5029. });
  5030. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5031. res.set_content("Error", "text/html");
  5032. });
  5033. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5034. if (req.path == "/routing_handler") {
  5035. res.set_header("POST_ROUTING", "on");
  5036. }
  5037. });
  5038. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5039. res.set_content("Hello World!\n", "text/plain");
  5040. });
  5041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5042. auto se = detail::scope_exit([&] {
  5043. svr.stop();
  5044. thread.join();
  5045. ASSERT_FALSE(svr.is_running());
  5046. });
  5047. svr.wait_until_ready();
  5048. {
  5049. #ifdef CPPHTTPLIB_SSL_ENABLED
  5050. SSLClient cli(HOST, PORT);
  5051. cli.enable_server_certificate_verification(false);
  5052. #else
  5053. Client cli(HOST, PORT);
  5054. #endif
  5055. auto res = cli.Get("/routing_handler");
  5056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("Routing Handler", res->body);
  5059. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5060. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5061. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5062. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5063. }
  5064. {
  5065. #ifdef CPPHTTPLIB_SSL_ENABLED
  5066. SSLClient cli(HOST, PORT);
  5067. cli.enable_server_certificate_verification(false);
  5068. #else
  5069. Client cli(HOST, PORT);
  5070. #endif
  5071. auto res = cli.Get("/hi");
  5072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5073. EXPECT_EQ(StatusCode::OK_200, res->status);
  5074. EXPECT_EQ("Hello World!\n", res->body);
  5075. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5076. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5077. }
  5078. {
  5079. #ifdef CPPHTTPLIB_SSL_ENABLED
  5080. SSLClient cli(HOST, PORT);
  5081. cli.enable_server_certificate_verification(false);
  5082. #else
  5083. Client cli(HOST, PORT);
  5084. #endif
  5085. auto res = cli.Get("/aaa");
  5086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5087. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5088. EXPECT_EQ("Error", res->body);
  5089. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5090. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5091. }
  5092. }
  5093. TEST(RequestHandlerTest, PreRequestHandler) {
  5094. auto route_path = "/user/:user";
  5095. Server svr;
  5096. svr.Get("/hi", [](const Request &, Response &res) {
  5097. res.set_content("hi", "text/plain");
  5098. });
  5099. svr.Get(route_path, [](const Request &req, Response &res) {
  5100. res.set_content(req.path_params.at("user"), "text/plain");
  5101. });
  5102. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5103. if (req.matched_route == route_path) {
  5104. auto user = req.path_params.at("user");
  5105. if (user != "john") {
  5106. res.status = StatusCode::Forbidden_403;
  5107. res.set_content("error", "text/html");
  5108. return Server::HandlerResponse::Handled;
  5109. }
  5110. }
  5111. return Server::HandlerResponse::Unhandled;
  5112. });
  5113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5114. auto se = detail::scope_exit([&] {
  5115. svr.stop();
  5116. thread.join();
  5117. ASSERT_FALSE(svr.is_running());
  5118. });
  5119. svr.wait_until_ready();
  5120. Client cli(HOST, PORT);
  5121. {
  5122. auto res = cli.Get("/hi");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("hi", res->body);
  5126. }
  5127. {
  5128. auto res = cli.Get("/user/john");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. EXPECT_EQ("john", res->body);
  5132. }
  5133. {
  5134. auto res = cli.Get("/user/invalid-user");
  5135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5136. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5137. EXPECT_EQ("error", res->body);
  5138. }
  5139. }
  5140. // The pre-request handler must run before the request body is read, so a
  5141. // rejected request never forces the server to buffer a (potentially large)
  5142. // body. Here the posted body is larger than the payload limit: if the body
  5143. // were read first the server would answer 413, but because the pre-request
  5144. // handler runs first it answers 403 and the body is never read.
  5145. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5146. Server svr;
  5147. svr.set_payload_max_length(8);
  5148. auto handler_ran = false;
  5149. svr.Post("/reject", [&](const Request &req, Response &res) {
  5150. handler_ran = true;
  5151. res.set_content(req.body, "text/plain");
  5152. });
  5153. svr.Post("/accept", [](const Request &req, Response &res) {
  5154. res.set_content(req.body, "text/plain");
  5155. });
  5156. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5157. if (req.matched_route == "/reject") {
  5158. res.status = StatusCode::Forbidden_403;
  5159. res.set_content("denied", "text/plain");
  5160. return Server::HandlerResponse::Handled;
  5161. }
  5162. return Server::HandlerResponse::Unhandled;
  5163. });
  5164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. thread.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5173. // rejects with 403 before the body is read, so 413 is never reached.
  5174. {
  5175. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5178. EXPECT_EQ("denied", res->body);
  5179. EXPECT_FALSE(handler_ran);
  5180. }
  5181. // An approved route still reads the body and enforces the payload limit.
  5182. {
  5183. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5186. }
  5187. }
  5188. TEST(UserDataTest, BasicOperations) {
  5189. httplib::UserData ud;
  5190. // Initially empty
  5191. EXPECT_FALSE(ud.has("key"));
  5192. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5193. // set and get
  5194. ud.set("key", 42);
  5195. EXPECT_TRUE(ud.has("key"));
  5196. auto *p = ud.get<int>("key");
  5197. ASSERT_NE(nullptr, p);
  5198. EXPECT_EQ(42, *p);
  5199. // Type mismatch → nullptr
  5200. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5201. // Overwrite with different type
  5202. ud.set("key", std::string("hello"));
  5203. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5204. auto *s = ud.get<std::string>("key");
  5205. ASSERT_NE(nullptr, s);
  5206. EXPECT_EQ("hello", *s);
  5207. // erase
  5208. ud.erase("key");
  5209. EXPECT_FALSE(ud.has("key"));
  5210. // clear
  5211. ud.set("a", 1);
  5212. ud.set("b", 2);
  5213. ud.clear();
  5214. EXPECT_FALSE(ud.has("a"));
  5215. EXPECT_FALSE(ud.has("b"));
  5216. }
  5217. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5218. struct AuthCtx {
  5219. std::string user_id;
  5220. };
  5221. Server svr;
  5222. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5223. res.user_data.set("auth", AuthCtx{"alice"});
  5224. return Server::HandlerResponse::Unhandled;
  5225. });
  5226. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5227. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5228. ASSERT_NE(nullptr, ctx);
  5229. res.set_content("Hello " + ctx->user_id, "text/plain");
  5230. });
  5231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5232. auto se = detail::scope_exit([&] {
  5233. svr.stop();
  5234. thread.join();
  5235. ASSERT_FALSE(svr.is_running());
  5236. });
  5237. svr.wait_until_ready();
  5238. Client cli(HOST, PORT);
  5239. auto res = cli.Get("/me");
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. EXPECT_EQ(StatusCode::OK_200, res->status);
  5242. EXPECT_EQ("Hello alice", res->body);
  5243. }
  5244. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5245. struct RoleCtx {
  5246. std::string role;
  5247. };
  5248. Server svr;
  5249. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5250. res.user_data.set("role", RoleCtx{"admin"});
  5251. return Server::HandlerResponse::Unhandled;
  5252. });
  5253. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5254. auto *ctx = res.user_data.get<RoleCtx>("role");
  5255. ASSERT_NE(nullptr, ctx);
  5256. res.set_content(ctx->role, "text/plain");
  5257. });
  5258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5259. auto se = detail::scope_exit([&] {
  5260. svr.stop();
  5261. thread.join();
  5262. ASSERT_FALSE(svr.is_running());
  5263. });
  5264. svr.wait_until_ready();
  5265. Client cli(HOST, PORT);
  5266. auto res = cli.Get("/role");
  5267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5268. EXPECT_EQ(StatusCode::OK_200, res->status);
  5269. EXPECT_EQ("admin", res->body);
  5270. }
  5271. TEST(InvalidFormatTest, StatusCode) {
  5272. Server svr;
  5273. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5274. res.set_content("Hello World!\n", "text/plain");
  5275. res.status = 9999; // Status should be a three-digit code...
  5276. });
  5277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5278. auto se = detail::scope_exit([&] {
  5279. svr.stop();
  5280. thread.join();
  5281. ASSERT_FALSE(svr.is_running());
  5282. });
  5283. svr.wait_until_ready();
  5284. {
  5285. Client cli(HOST, PORT);
  5286. auto res = cli.Get("/hi");
  5287. ASSERT_FALSE(res);
  5288. }
  5289. }
  5290. TEST(URLFragmentTest, WithFragment) {
  5291. Server svr;
  5292. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5293. EXPECT_TRUE(req.target == "/hi");
  5294. });
  5295. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5296. auto se = detail::scope_exit([&] {
  5297. svr.stop();
  5298. thread.join();
  5299. ASSERT_FALSE(svr.is_running());
  5300. });
  5301. svr.wait_until_ready();
  5302. {
  5303. Client cli(HOST, PORT);
  5304. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5305. EXPECT_TRUE(res);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. res = cli.Get("/hi%23key1=val1=key2=val2");
  5308. EXPECT_TRUE(res);
  5309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5310. }
  5311. }
  5312. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5313. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5314. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5315. Server svr;
  5316. std::vector<std::string> targets;
  5317. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5318. targets.push_back(req.target);
  5319. });
  5320. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5321. auto se = detail::scope_exit([&] {
  5322. svr.stop();
  5323. thread.join();
  5324. ASSERT_FALSE(svr.is_running());
  5325. });
  5326. svr.wait_until_ready();
  5327. Client cli(HOST, PORT);
  5328. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5329. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5330. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5331. // A '?' after the '#' belongs to the fragment, not to the query.
  5332. Request req;
  5333. req.method = "GET";
  5334. req.path = "/hi#f?x=1";
  5335. req.params.emplace("a", "1");
  5336. Response res;
  5337. auto error = Error::Success;
  5338. EXPECT_TRUE(cli.send(req, res, error));
  5339. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5340. "/hi?a=1"}),
  5341. targets);
  5342. }
  5343. TEST(HeaderWriter, SetHeaderWriter) {
  5344. Server svr;
  5345. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5346. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5347. return detail::write_headers(strm, hdrs);
  5348. });
  5349. svr.Get("/hi", [](const Request &req, Response &res) {
  5350. auto it = req.headers.find("CustomClientHeader");
  5351. EXPECT_TRUE(it != req.headers.end());
  5352. EXPECT_EQ(it->second, "CustomClientValue");
  5353. res.set_content("Hello World!\n", "text/plain");
  5354. });
  5355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5356. auto se = detail::scope_exit([&] {
  5357. svr.stop();
  5358. thread.join();
  5359. ASSERT_FALSE(svr.is_running());
  5360. });
  5361. svr.wait_until_ready();
  5362. {
  5363. Client cli(HOST, PORT);
  5364. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5365. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5366. return detail::write_headers(strm, hdrs);
  5367. });
  5368. auto res = cli.Get("/hi");
  5369. EXPECT_TRUE(res);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. auto it = res->headers.find("CustomServerHeader");
  5372. EXPECT_TRUE(it != res->headers.end());
  5373. EXPECT_EQ(it->second, "CustomServerValue");
  5374. }
  5375. }
  5376. class ServerTest : public ::testing::Test {
  5377. protected:
  5378. ServerTest()
  5379. : cli_(HOST, PORT)
  5380. #ifdef CPPHTTPLIB_SSL_ENABLED
  5381. ,
  5382. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5383. #endif
  5384. {
  5385. #ifdef CPPHTTPLIB_SSL_ENABLED
  5386. cli_.enable_server_certificate_verification(false);
  5387. #endif
  5388. // Allow LARGE_DATA (100MB) responses
  5389. cli_.set_payload_max_length(200 * 1024 * 1024);
  5390. }
  5391. virtual void SetUp() {
  5392. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5393. svr_.set_payload_max_length(200 * 1024 * 1024);
  5394. svr_.set_mount_point("/", "./www");
  5395. svr_.set_mount_point("/mount", "./www2");
  5396. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5397. svr_.Get("/hi",
  5398. [&](const Request & /*req*/, Response &res) {
  5399. res.set_content("Hello World!", "text/plain");
  5400. })
  5401. .Get("/file_content",
  5402. [&](const Request & /*req*/, Response &res) {
  5403. res.set_file_content("./www/dir/test.html");
  5404. })
  5405. .Get("/file_content_with_content_type",
  5406. [&](const Request & /*req*/, Response &res) {
  5407. res.set_file_content("./www/file", "text/plain");
  5408. })
  5409. .Get("/invalid_file_content",
  5410. [&](const Request & /*req*/, Response &res) {
  5411. res.set_file_content("./www/dir/invalid_file_path");
  5412. })
  5413. .Get("/http_response_splitting",
  5414. [&](const Request & /*req*/, Response &res) {
  5415. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5416. EXPECT_EQ(0U, res.headers.size());
  5417. EXPECT_FALSE(res.has_header("a"));
  5418. res.set_header("a", "1\nSet-Cookie: a=1");
  5419. EXPECT_EQ(0U, res.headers.size());
  5420. EXPECT_FALSE(res.has_header("a"));
  5421. res.set_header("a", "1\rSet-Cookie: a=1");
  5422. EXPECT_EQ(0U, res.headers.size());
  5423. EXPECT_FALSE(res.has_header("a"));
  5424. res.set_header("a\r\nb", "0");
  5425. EXPECT_EQ(0U, res.headers.size());
  5426. EXPECT_FALSE(res.has_header("a"));
  5427. res.set_header("a\rb", "0");
  5428. EXPECT_EQ(0U, res.headers.size());
  5429. EXPECT_FALSE(res.has_header("a"));
  5430. res.set_header("a\nb", "0");
  5431. EXPECT_EQ(0U, res.headers.size());
  5432. EXPECT_FALSE(res.has_header("a"));
  5433. res.set_redirect("1\r\nSet-Cookie: a=1");
  5434. EXPECT_EQ(0U, res.headers.size());
  5435. EXPECT_FALSE(res.has_header("Location"));
  5436. })
  5437. .Get("/slow",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. std::this_thread::sleep_for(std::chrono::seconds(4));
  5440. res.set_content("slow", "text/plain");
  5441. })
  5442. #if 0
  5443. .Post("/slowpost",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. std::this_thread::sleep_for(std::chrono::seconds(2));
  5446. res.set_content("slow", "text/plain");
  5447. })
  5448. #endif
  5449. .Get("/remote_addr",
  5450. [&](const Request &req, Response &res) {
  5451. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5452. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5453. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5454. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5455. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5456. #endif
  5457. res.set_content(req.remote_addr, "text/plain");
  5458. })
  5459. .Get("/local_addr",
  5460. [&](const Request &req, Response &res) {
  5461. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5462. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5463. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5464. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5465. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5466. #endif
  5467. auto local_addr = req.local_addr;
  5468. auto local_port = std::to_string(req.local_port);
  5469. res.set_content(local_addr.append(":").append(local_port),
  5470. "text/plain");
  5471. })
  5472. .Get("/endwith%",
  5473. [&](const Request & /*req*/, Response &res) {
  5474. res.set_content("Hello World!", "text/plain");
  5475. })
  5476. .Get("/a\\+\\+b",
  5477. [&](const Request &req, Response &res) {
  5478. ASSERT_TRUE(req.has_param("a +b"));
  5479. auto val = req.get_param_value("a +b");
  5480. res.set_content(val, "text/plain");
  5481. })
  5482. .Get("/", [&](const Request & /*req*/,
  5483. Response &res) { res.set_redirect("/hi"); })
  5484. .Post("/1",
  5485. [](const Request & /*req*/, Response &res) {
  5486. res.set_redirect("/2", StatusCode::SeeOther_303);
  5487. })
  5488. .Get("/2",
  5489. [](const Request & /*req*/, Response &res) {
  5490. res.set_content("redirected.", "text/plain");
  5491. res.status = StatusCode::OK_200;
  5492. })
  5493. .Post("/person",
  5494. [&](const Request &req, Response &res) {
  5495. if (req.has_param("name") && req.has_param("note")) {
  5496. persons_[req.get_param_value("name")] =
  5497. req.get_param_value("note");
  5498. } else {
  5499. res.status = StatusCode::BadRequest_400;
  5500. }
  5501. })
  5502. .Put("/person",
  5503. [&](const Request &req, Response &res) {
  5504. if (req.has_param("name") && req.has_param("note")) {
  5505. persons_[req.get_param_value("name")] =
  5506. req.get_param_value("note");
  5507. } else {
  5508. res.status = StatusCode::BadRequest_400;
  5509. }
  5510. })
  5511. .Get("/person/(.*)",
  5512. [&](const Request &req, Response &res) {
  5513. string name = req.matches[1];
  5514. if (persons_.find(name) != persons_.end()) {
  5515. auto note = persons_[name];
  5516. res.set_content(note, "text/plain");
  5517. } else {
  5518. res.status = StatusCode::NotFound_404;
  5519. }
  5520. })
  5521. .Delete("/person",
  5522. [&](const Request &req, Response &res) {
  5523. if (req.has_param("name")) {
  5524. string name = req.get_param_value("name");
  5525. if (persons_.find(name) != persons_.end()) {
  5526. persons_.erase(name);
  5527. res.set_content("DELETED", "text/plain");
  5528. } else {
  5529. res.status = StatusCode::NotFound_404;
  5530. }
  5531. } else {
  5532. res.status = StatusCode::BadRequest_400;
  5533. }
  5534. })
  5535. .Post("/x-www-form-urlencoded-json",
  5536. [&](const Request &req, Response &res) {
  5537. auto json = req.get_param_value("json");
  5538. ASSERT_EQ(JSON_DATA, json);
  5539. res.set_content(json, "appliation/json");
  5540. res.status = StatusCode::OK_200;
  5541. })
  5542. .Get("/streamed-chunked",
  5543. [&](const Request & /*req*/, Response &res) {
  5544. res.set_chunked_content_provider(
  5545. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5546. sink.os << "123";
  5547. sink.os << "456";
  5548. sink.os << "789";
  5549. sink.done();
  5550. return true;
  5551. });
  5552. })
  5553. .Get("/streamed-chunked-with-prohibited-trailer",
  5554. [&](const Request & /*req*/, Response &res) {
  5555. auto i = new int(0);
  5556. // Declare both a prohibited trailer (Content-Length) and an
  5557. // allowed one
  5558. res.set_header("Trailer", "Content-Length, X-Allowed");
  5559. res.set_chunked_content_provider(
  5560. "text/plain",
  5561. [i](size_t /*offset*/, DataSink &sink) {
  5562. switch (*i) {
  5563. case 0: sink.os << "123"; break;
  5564. case 1: sink.os << "456"; break;
  5565. case 2: sink.os << "789"; break;
  5566. case 3: {
  5567. sink.done_with_trailer(
  5568. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5569. } break;
  5570. }
  5571. (*i)++;
  5572. return true;
  5573. },
  5574. [i](bool success) {
  5575. EXPECT_TRUE(success);
  5576. delete i;
  5577. });
  5578. })
  5579. .Get("/streamed-chunked2",
  5580. [&](const Request & /*req*/, Response &res) {
  5581. auto i = new int(0);
  5582. res.set_chunked_content_provider(
  5583. "text/plain",
  5584. [i](size_t /*offset*/, DataSink &sink) {
  5585. switch (*i) {
  5586. case 0: sink.os << "123"; break;
  5587. case 1: sink.os << "456"; break;
  5588. case 2: sink.os << "789"; break;
  5589. case 3: sink.done(); break;
  5590. }
  5591. (*i)++;
  5592. return true;
  5593. },
  5594. [i](bool success) {
  5595. EXPECT_TRUE(success);
  5596. delete i;
  5597. });
  5598. })
  5599. .Get("/streamed-chunked-with-trailer",
  5600. [&](const Request & /*req*/, Response &res) {
  5601. auto i = new int(0);
  5602. res.set_header("Trailer", "Dummy1, Dummy2");
  5603. res.set_chunked_content_provider(
  5604. "text/plain",
  5605. [i](size_t /*offset*/, DataSink &sink) {
  5606. switch (*i) {
  5607. case 0: sink.os << "123"; break;
  5608. case 1: sink.os << "456"; break;
  5609. case 2: sink.os << "789"; break;
  5610. case 3: {
  5611. sink.done_with_trailer(
  5612. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5613. } break;
  5614. }
  5615. (*i)++;
  5616. return true;
  5617. },
  5618. [i](bool success) {
  5619. EXPECT_TRUE(success);
  5620. delete i;
  5621. });
  5622. })
  5623. .Get("/streamed",
  5624. [&](const Request & /*req*/, Response &res) {
  5625. res.set_content_provider(
  5626. 6, "text/plain",
  5627. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5628. sink.os << (offset < 3 ? "a" : "b");
  5629. return true;
  5630. });
  5631. })
  5632. .Get("/streamed-without-length",
  5633. [&](const Request & /*req*/, Response &res) {
  5634. auto data = new std::string("abcdefg");
  5635. res.set_content_provider(
  5636. "text/plain",
  5637. [data](size_t offset, DataSink &sink) {
  5638. if (offset < data->size()) {
  5639. sink.os << data->substr(offset);
  5640. }
  5641. sink.done();
  5642. return true;
  5643. },
  5644. [data](bool success) {
  5645. EXPECT_TRUE(success);
  5646. delete data;
  5647. });
  5648. })
  5649. .Get("/streamed-with-range",
  5650. [&](const Request &req, Response &res) {
  5651. auto data = new std::string("abcdefg");
  5652. // An explicit status keeps the server from picking the 206 it
  5653. // would otherwise choose for a ranged request, so the response
  5654. // is not a partial representation.
  5655. auto status = req.get_param_value("status");
  5656. if (status == "200") {
  5657. res.status = StatusCode::OK_200;
  5658. } else if (status == "403") {
  5659. res.status = StatusCode::Forbidden_403;
  5660. }
  5661. res.set_content_provider(
  5662. data->size(), "text/plain",
  5663. [data](size_t offset, size_t length, DataSink &sink) {
  5664. size_t DATA_CHUNK_SIZE = 4;
  5665. const auto &d = *data;
  5666. auto out_len =
  5667. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5668. auto ret =
  5669. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5670. EXPECT_TRUE(ret);
  5671. return true;
  5672. },
  5673. [data, &req](bool success) {
  5674. EXPECT_EQ(success, !req.has_param("error"));
  5675. delete data;
  5676. });
  5677. })
  5678. .Get("/streamed-cancel",
  5679. [&](const Request & /*req*/, Response &res) {
  5680. res.set_content_provider(
  5681. size_t(-1), "text/plain",
  5682. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5683. sink.os << "data_chunk";
  5684. return true;
  5685. });
  5686. })
  5687. .Get("/regex-with-delimiter",
  5688. [&](const Request &req, Response & /*res*/) {
  5689. ASSERT_TRUE(req.has_param("key"));
  5690. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5691. })
  5692. .Get("/with-range",
  5693. [&](const Request & /*req*/, Response &res) {
  5694. res.set_content("abcdefg", "text/plain");
  5695. })
  5696. .Get("/test-start-time",
  5697. [&](const Request &req, Response & /*res*/) {
  5698. EXPECT_NE(req.start_time_,
  5699. std::chrono::steady_clock::time_point::min());
  5700. })
  5701. .Get("/with-range-customized-response",
  5702. [&](const Request & /*req*/, Response &res) {
  5703. res.status = StatusCode::BadRequest_400;
  5704. res.set_content(JSON_DATA, "application/json");
  5705. })
  5706. .Post("/chunked",
  5707. [&](const Request &req, Response & /*res*/) {
  5708. EXPECT_EQ(req.body, "dechunked post body");
  5709. })
  5710. .Post("/large-chunked",
  5711. [&](const Request &req, Response & /*res*/) {
  5712. std::string expected(6 * 30 * 1024u, 'a');
  5713. EXPECT_EQ(req.body, expected);
  5714. })
  5715. .Post("/multipart",
  5716. [&](const Request &req, Response & /*res*/) {
  5717. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5718. req.form.get_field_count("text2") +
  5719. req.form.get_field_count("file3") +
  5720. req.form.get_field_count("file4"));
  5721. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5722. req.form.get_file_count("file2"));
  5723. ASSERT_TRUE(!req.form.has_file("???"));
  5724. ASSERT_TRUE(!req.form.has_field("???"));
  5725. ASSERT_TRUE(req.body.empty());
  5726. {
  5727. const auto &text = req.form.get_field("text1");
  5728. EXPECT_EQ("text default", text);
  5729. }
  5730. {
  5731. const auto &text = req.form.get_field("text2");
  5732. EXPECT_EQ("aωb", text);
  5733. }
  5734. {
  5735. const auto &file = req.form.get_file("file1");
  5736. EXPECT_EQ("hello.txt", file.filename);
  5737. EXPECT_EQ("text/plain", file.content_type);
  5738. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5739. }
  5740. {
  5741. const auto &file = req.form.get_file("file2");
  5742. EXPECT_EQ("world.json", file.filename);
  5743. EXPECT_EQ("application/json", file.content_type);
  5744. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5745. }
  5746. {
  5747. const auto &text = req.form.get_field("file3");
  5748. EXPECT_EQ(0u, text.size());
  5749. }
  5750. {
  5751. const auto &text = req.form.get_field("file4");
  5752. EXPECT_EQ(0u, text.size());
  5753. }
  5754. })
  5755. .Post("/multipart/multi_file_values",
  5756. [&](const Request &req, Response & /*res*/) {
  5757. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5758. req.form.get_field_count("multi_text1"));
  5759. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5760. ASSERT_TRUE(!req.form.has_file("???"));
  5761. ASSERT_TRUE(!req.form.has_field("???"));
  5762. ASSERT_TRUE(req.body.empty());
  5763. {
  5764. const auto &text = req.form.get_field("text");
  5765. EXPECT_EQ("default text", text);
  5766. }
  5767. {
  5768. const auto &text1_values = req.form.get_fields("multi_text1");
  5769. EXPECT_EQ(2u, text1_values.size());
  5770. EXPECT_EQ("aaaaa", text1_values[0]);
  5771. EXPECT_EQ("bbbbb", text1_values[1]);
  5772. }
  5773. {
  5774. const auto &file1_values = req.form.get_files("multi_file1");
  5775. EXPECT_EQ(2u, file1_values.size());
  5776. auto file1 = file1_values[0];
  5777. EXPECT_EQ(file1.filename, "hello.txt");
  5778. EXPECT_EQ(file1.content_type, "text/plain");
  5779. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5780. auto file2 = file1_values[1];
  5781. EXPECT_EQ(file2.filename, "world.json");
  5782. EXPECT_EQ(file2.content_type, "application/json");
  5783. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5784. }
  5785. })
  5786. .Post("/empty",
  5787. [&](const Request &req, Response &res) {
  5788. EXPECT_EQ(req.body, "");
  5789. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5790. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5791. res.set_content("empty", "text/plain");
  5792. })
  5793. .Post("/empty-no-content-type",
  5794. [&](const Request &req, Response &res) {
  5795. EXPECT_EQ(req.body, "");
  5796. EXPECT_FALSE(req.has_header("Content-Type"));
  5797. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5798. res.set_content("empty-no-content-type", "text/plain");
  5799. })
  5800. .Post("/path-only",
  5801. [&](const Request &req, Response &res) {
  5802. EXPECT_EQ(req.body, "");
  5803. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5804. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5805. res.set_content("path-only", "text/plain");
  5806. })
  5807. .Post("/path-headers-only",
  5808. [&](const Request &req, Response &res) {
  5809. EXPECT_EQ(req.body, "");
  5810. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5811. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5812. EXPECT_EQ("world", req.get_header_value("hello"));
  5813. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5814. res.set_content("path-headers-only", "text/plain");
  5815. })
  5816. .Post("/post-large",
  5817. [&](const Request &req, Response &res) {
  5818. EXPECT_EQ(req.body, LARGE_DATA);
  5819. res.set_content(req.body, "text/plain");
  5820. })
  5821. .Post("/post-loopback",
  5822. [&](const Request &, Response &res,
  5823. ContentReader const &content_reader) {
  5824. std::string body;
  5825. content_reader([&](const char *data, size_t data_length) {
  5826. body.append(data, data_length);
  5827. return true;
  5828. });
  5829. res.set_content(body, "text/plain");
  5830. })
  5831. .Put("/put-loopback",
  5832. [&](const Request &, Response &res,
  5833. ContentReader const &content_reader) {
  5834. std::string body;
  5835. content_reader([&](const char *data, size_t data_length) {
  5836. body.append(data, data_length);
  5837. return true;
  5838. });
  5839. res.set_content(body, "text/plain");
  5840. })
  5841. .Patch("/patch-loopback",
  5842. [&](const Request &, Response &res,
  5843. ContentReader const &content_reader) {
  5844. std::string body;
  5845. content_reader([&](const char *data, size_t data_length) {
  5846. body.append(data, data_length);
  5847. return true;
  5848. });
  5849. res.set_content(body, "text/plain");
  5850. })
  5851. .Put("/empty-no-content-type",
  5852. [&](const Request &req, Response &res) {
  5853. EXPECT_EQ(req.body, "");
  5854. EXPECT_FALSE(req.has_header("Content-Type"));
  5855. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5856. res.set_content("empty-no-content-type", "text/plain");
  5857. })
  5858. .Put("/put",
  5859. [&](const Request &req, Response &res) {
  5860. EXPECT_EQ(req.body, "PUT");
  5861. res.set_content(req.body, "text/plain");
  5862. })
  5863. .Put("/put-large",
  5864. [&](const Request &req, Response &res) {
  5865. EXPECT_EQ(req.body, LARGE_DATA);
  5866. res.set_content(req.body, "text/plain");
  5867. })
  5868. .Patch("/patch",
  5869. [&](const Request &req, Response &res) {
  5870. EXPECT_EQ(req.body, "PATCH");
  5871. res.set_content(req.body, "text/plain");
  5872. })
  5873. .Delete("/delete",
  5874. [&](const Request & /*req*/, Response &res) {
  5875. res.set_content("DELETE", "text/plain");
  5876. })
  5877. .Delete("/delete-body",
  5878. [&](const Request &req, Response &res) {
  5879. EXPECT_EQ(req.body, "content");
  5880. res.set_content(req.body, "text/plain");
  5881. })
  5882. .Options(R"(\*)",
  5883. [&](const Request & /*req*/, Response &res) {
  5884. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5885. })
  5886. .CustomRoute("PROPFIND", "/dav/:id",
  5887. [&](const Request &req, Response &res) {
  5888. res.set_header("x-body-size",
  5889. std::to_string(req.body.size()));
  5890. res.set_header("x-matched-route", req.matched_route);
  5891. res.set_header("x-dav-id", req.path_params.at("id"));
  5892. res.status = StatusCode::MultiStatus_207;
  5893. res.set_content(req.body, "application/xml");
  5894. })
  5895. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5896. [&](const Request &req, Response &res) {
  5897. res.set_header("x-dav-match", req.matches[1]);
  5898. res.status = StatusCode::MultiStatus_207;
  5899. })
  5900. .CustomRoute("MKCOL", "/dav-mkcol",
  5901. [&](const Request &req, Response &res) {
  5902. EXPECT_TRUE(req.body.empty());
  5903. res.status = StatusCode::Created_201;
  5904. })
  5905. .CustomRoute(
  5906. "REPORT", "/dav-report",
  5907. [&](const Request & /*req*/, Response &res,
  5908. const ContentReader &content_reader) {
  5909. std::string body;
  5910. content_reader([&](const char *data, size_t data_length) {
  5911. body.append(data, data_length);
  5912. return true;
  5913. });
  5914. res.set_header("x-body-size", std::to_string(body.size()));
  5915. res.status = StatusCode::MultiStatus_207;
  5916. res.set_content(body, "application/xml");
  5917. })
  5918. .Get("/request-target",
  5919. [&](const Request &req, Response & /*res*/) {
  5920. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5921. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5922. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5923. })
  5924. .Get("/long-query-value",
  5925. [&](const Request &req, Response & /*res*/) {
  5926. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5927. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5928. })
  5929. .Get("/too-long-query-value",
  5930. [&](const Request &req, Response & /*res*/) {
  5931. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5932. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5933. })
  5934. .Get("/array-param",
  5935. [&](const Request &req, Response & /*res*/) {
  5936. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5937. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5938. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5939. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5940. })
  5941. .Get("/array-param-values",
  5942. [&](const Request &req, Response & /*res*/) {
  5943. auto values = req.get_param_values("array");
  5944. EXPECT_EQ(3u, values.size());
  5945. EXPECT_EQ("value1", values[0]);
  5946. EXPECT_EQ("value2", values[1]);
  5947. EXPECT_EQ("value3", values[2]);
  5948. auto empty = req.get_param_values("nonexistent");
  5949. EXPECT_TRUE(empty.empty());
  5950. })
  5951. .Post("/validate-no-multiple-headers",
  5952. [&](const Request &req, Response & /*res*/) {
  5953. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5954. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5955. })
  5956. .Post("/content_receiver",
  5957. [&](const Request &req, Response &res,
  5958. const ContentReader &content_reader) {
  5959. if (req.is_multipart_form_data()) {
  5960. std::vector<FormData> items;
  5961. content_reader(
  5962. [&](const FormData &file) {
  5963. items.push_back(file);
  5964. return true;
  5965. },
  5966. [&](const char *data, size_t data_length) {
  5967. items.back().content.append(data, data_length);
  5968. return true;
  5969. });
  5970. EXPECT_EQ(5u, items.size());
  5971. {
  5972. const auto &file = get_file_value(items, "text1");
  5973. EXPECT_TRUE(file.filename.empty());
  5974. EXPECT_EQ("text default", file.content);
  5975. }
  5976. {
  5977. const auto &file = get_file_value(items, "text2");
  5978. EXPECT_TRUE(file.filename.empty());
  5979. EXPECT_EQ("aωb", file.content);
  5980. }
  5981. {
  5982. const auto &file = get_file_value(items, "file1");
  5983. EXPECT_EQ("hello.txt", file.filename);
  5984. EXPECT_EQ("text/plain", file.content_type);
  5985. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5986. }
  5987. {
  5988. const auto &file = get_file_value(items, "file2");
  5989. EXPECT_EQ("world.json", file.filename);
  5990. EXPECT_EQ("application/json", file.content_type);
  5991. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5992. }
  5993. {
  5994. const auto &file = get_file_value(items, "file3");
  5995. EXPECT_TRUE(file.filename.empty());
  5996. EXPECT_EQ("application/octet-stream", file.content_type);
  5997. EXPECT_EQ(0u, file.content.size());
  5998. }
  5999. } else {
  6000. std::string body;
  6001. content_reader([&](const char *data, size_t data_length) {
  6002. EXPECT_EQ(7U, data_length);
  6003. body.append(data, data_length);
  6004. return true;
  6005. });
  6006. EXPECT_EQ(body, "content");
  6007. res.set_content(body, "text/plain");
  6008. }
  6009. })
  6010. .Put("/content_receiver",
  6011. [&](const Request & /*req*/, Response &res,
  6012. const ContentReader &content_reader) {
  6013. std::string body;
  6014. content_reader([&](const char *data, size_t data_length) {
  6015. body.append(data, data_length);
  6016. return true;
  6017. });
  6018. EXPECT_EQ(body, "content");
  6019. res.set_content(body, "text/plain");
  6020. })
  6021. .Patch("/content_receiver",
  6022. [&](const Request & /*req*/, Response &res,
  6023. const ContentReader &content_reader) {
  6024. std::string body;
  6025. content_reader([&](const char *data, size_t data_length) {
  6026. body.append(data, data_length);
  6027. return true;
  6028. });
  6029. EXPECT_EQ(body, "content");
  6030. res.set_content(body, "text/plain");
  6031. })
  6032. .Post("/query-string-and-body",
  6033. [&](const Request &req, Response & /*res*/) {
  6034. ASSERT_TRUE(req.has_param("key"));
  6035. EXPECT_EQ(req.get_param_value("key"), "value");
  6036. EXPECT_EQ(req.body, "content");
  6037. })
  6038. .Get("/last-request",
  6039. [&](const Request &req, Response & /*res*/) {
  6040. EXPECT_EQ("close", req.get_header_value("Connection"));
  6041. })
  6042. .Get(R"(/redirect/(\d+))",
  6043. [&](const Request &req, Response &res) {
  6044. auto num = std::stoi(req.matches[1]) + 1;
  6045. std::string url = "/redirect/" + std::to_string(num);
  6046. res.set_redirect(url);
  6047. })
  6048. .Post("/binary",
  6049. [&](const Request &req, Response &res) {
  6050. EXPECT_EQ(4U, req.body.size());
  6051. EXPECT_EQ("application/octet-stream",
  6052. req.get_header_value("Content-Type"));
  6053. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6054. res.set_content(req.body, "application/octet-stream");
  6055. })
  6056. .Put("/binary",
  6057. [&](const Request &req, Response &res) {
  6058. EXPECT_EQ(4U, req.body.size());
  6059. EXPECT_EQ("application/octet-stream",
  6060. req.get_header_value("Content-Type"));
  6061. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6062. res.set_content(req.body, "application/octet-stream");
  6063. })
  6064. .Patch("/binary",
  6065. [&](const Request &req, Response &res) {
  6066. EXPECT_EQ(4U, req.body.size());
  6067. EXPECT_EQ("application/octet-stream",
  6068. req.get_header_value("Content-Type"));
  6069. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6070. res.set_content(req.body, "application/octet-stream");
  6071. })
  6072. .Delete("/binary",
  6073. [&](const Request &req, Response &res) {
  6074. EXPECT_EQ(4U, req.body.size());
  6075. EXPECT_EQ("application/octet-stream",
  6076. req.get_header_value("Content-Type"));
  6077. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6078. res.set_content(req.body, "application/octet-stream");
  6079. })
  6080. .Get("/issue1772",
  6081. [&](const Request & /*req*/, Response &res) {
  6082. res.status = 401;
  6083. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6084. })
  6085. .Delete("/issue609",
  6086. [](const httplib::Request &, httplib::Response &res,
  6087. const httplib::ContentReader &) {
  6088. res.set_content("ok", "text/plain");
  6089. })
  6090. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6091. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6092. .Get("/compress",
  6093. [&](const Request & /*req*/, Response &res) {
  6094. res.set_content(
  6095. "12345678901234567890123456789012345678901234567890123456789"
  6096. "01234567890123456789012345678901234567890",
  6097. "text/plain");
  6098. })
  6099. .Get("/compress-with-charset",
  6100. [&](const Request & /*req*/, Response &res) {
  6101. res.set_content(
  6102. "12345678901234567890123456789012345678901234567890123456789"
  6103. "01234567890123456789012345678901234567890",
  6104. "application/json; charset=utf-8");
  6105. })
  6106. .Get("/nocompress",
  6107. [&](const Request & /*req*/, Response &res) {
  6108. res.set_content(
  6109. "12345678901234567890123456789012345678901234567890123456789"
  6110. "01234567890123456789012345678901234567890",
  6111. "application/octet-stream");
  6112. })
  6113. .Post("/compress-multipart",
  6114. [&](const Request &req, Response & /*res*/) {
  6115. EXPECT_EQ(2u, req.form.fields.size());
  6116. ASSERT_TRUE(!req.form.has_field("???"));
  6117. {
  6118. const auto &text = req.form.get_field("key1");
  6119. EXPECT_EQ("test", text);
  6120. }
  6121. {
  6122. const auto &text = req.form.get_field("key2");
  6123. EXPECT_EQ("--abcdefg123", text);
  6124. }
  6125. })
  6126. #endif
  6127. ;
  6128. persons_["john"] = "programmer";
  6129. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6130. svr_.wait_until_ready();
  6131. }
  6132. virtual void TearDown() {
  6133. svr_.stop();
  6134. if (!request_threads_.empty()) {
  6135. std::this_thread::sleep_for(std::chrono::seconds(1));
  6136. for (auto &t : request_threads_) {
  6137. t.join();
  6138. }
  6139. }
  6140. t_.join();
  6141. }
  6142. map<string, string> persons_;
  6143. #ifdef CPPHTTPLIB_SSL_ENABLED
  6144. SSLClient cli_;
  6145. SSLServer svr_;
  6146. #else
  6147. Client cli_;
  6148. Server svr_;
  6149. #endif
  6150. thread t_;
  6151. std::vector<thread> request_threads_;
  6152. };
  6153. TEST_F(ServerTest, GetMethod200) {
  6154. auto res = cli_.Get("/hi");
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ("HTTP/1.1", res->version);
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. EXPECT_EQ("OK", res->reason);
  6159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6160. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6161. EXPECT_EQ("Hello World!", res->body);
  6162. }
  6163. TEST_F(ServerTest, GetEmptyFile) {
  6164. auto res = cli_.Get("/empty_file");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6168. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6169. EXPECT_EQ("", res->body);
  6170. }
  6171. TEST_F(ServerTest, GetFileContent) {
  6172. auto res = cli_.Get("/file_content");
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6176. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6177. EXPECT_EQ("test.html", res->body);
  6178. }
  6179. TEST_F(ServerTest, GetFileContentWithRange) {
  6180. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6183. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6184. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6185. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6186. EXPECT_EQ("est", res->body);
  6187. }
  6188. TEST_F(ServerTest, GetFileContentWithContentType) {
  6189. auto res = cli_.Get("/file_content_with_content_type");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6193. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6194. EXPECT_EQ("file\n", res->body);
  6195. }
  6196. TEST_F(ServerTest, GetInvalidFileContent) {
  6197. auto res = cli_.Get("/invalid_file_content");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6200. }
  6201. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6202. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ("HTTP/1.1", res->version);
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6207. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6208. EXPECT_EQ("Hello World!", res->body);
  6209. }
  6210. TEST_F(ServerTest, GetMethod302) {
  6211. auto res = cli_.Get("/");
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. EXPECT_EQ(StatusCode::Found_302, res->status);
  6214. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6215. }
  6216. TEST_F(ServerTest, GetMethod302Redirect) {
  6217. cli_.set_follow_location(true);
  6218. auto res = cli_.Get("/");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::OK_200, res->status);
  6221. EXPECT_EQ("Hello World!", res->body);
  6222. EXPECT_EQ("/hi", res->location);
  6223. }
  6224. TEST_F(ServerTest, GetMethod404) {
  6225. auto res = cli_.Get("/invalid");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6228. }
  6229. TEST_F(ServerTest, HeadMethod200) {
  6230. auto res = cli_.Head("/hi");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::OK_200, res->status);
  6233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6234. EXPECT_TRUE(res->body.empty());
  6235. }
  6236. TEST_F(ServerTest, HeadMethod200Static) {
  6237. auto res = cli_.Head("/mount/dir/index.html");
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6241. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6242. EXPECT_TRUE(res->body.empty());
  6243. }
  6244. TEST_F(ServerTest, HeadMethod404) {
  6245. auto res = cli_.Head("/invalid");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6248. EXPECT_TRUE(res->body.empty());
  6249. }
  6250. TEST_F(ServerTest, GetMethodPersonJohn) {
  6251. auto res = cli_.Get("/person/john");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. EXPECT_EQ(StatusCode::OK_200, res->status);
  6254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6255. EXPECT_EQ("programmer", res->body);
  6256. }
  6257. TEST_F(ServerTest, PostMethod1) {
  6258. auto res = cli_.Get("/person/john1");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6261. res = cli_.Post("/person", "name=john1&note=coder",
  6262. "application/x-www-form-urlencoded");
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. ASSERT_EQ(StatusCode::OK_200, res->status);
  6265. res = cli_.Get("/person/john1");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. ASSERT_EQ(StatusCode::OK_200, res->status);
  6268. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6269. ASSERT_EQ("coder", res->body);
  6270. }
  6271. TEST_F(ServerTest, PostMethod2) {
  6272. auto res = cli_.Get("/person/john2");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6275. Params params;
  6276. params.emplace("name", "john2");
  6277. params.emplace("note", "coder");
  6278. res = cli_.Post("/person", params);
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. ASSERT_EQ(StatusCode::OK_200, res->status);
  6281. res = cli_.Get("/person/john2");
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. ASSERT_EQ(StatusCode::OK_200, res->status);
  6284. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6285. ASSERT_EQ("coder", res->body);
  6286. }
  6287. TEST_F(ServerTest, PutMethod3) {
  6288. auto res = cli_.Get("/person/john3");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6291. Params params;
  6292. params.emplace("name", "john3");
  6293. params.emplace("note", "coder");
  6294. res = cli_.Put("/person", params);
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. ASSERT_EQ(StatusCode::OK_200, res->status);
  6297. res = cli_.Get("/person/john3");
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. ASSERT_EQ(StatusCode::OK_200, res->status);
  6300. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6301. ASSERT_EQ("coder", res->body);
  6302. }
  6303. TEST_F(ServerTest, DeleteMethod1) {
  6304. auto res = cli_.Get("/person/john4");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6307. Params params;
  6308. params.emplace("name", "john4");
  6309. params.emplace("note", "coder");
  6310. res = cli_.Post("/person", params);
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. ASSERT_EQ(StatusCode::OK_200, res->status);
  6313. res = cli_.Get("/person/john4");
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. ASSERT_EQ(StatusCode::OK_200, res->status);
  6316. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6317. ASSERT_EQ("coder", res->body);
  6318. Params delete_params;
  6319. delete_params.emplace("name", "john4");
  6320. res = cli_.Delete("/person", delete_params);
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. ASSERT_EQ(StatusCode::OK_200, res->status);
  6323. ASSERT_EQ("DELETED", res->body);
  6324. res = cli_.Get("/person/john4");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6327. }
  6328. TEST_F(ServerTest, DeleteMethod2) {
  6329. auto res = cli_.Get("/person/john5");
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6332. Params params;
  6333. params.emplace("name", "john5");
  6334. params.emplace("note", "developer");
  6335. res = cli_.Post("/person", params);
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. ASSERT_EQ(StatusCode::OK_200, res->status);
  6338. res = cli_.Get("/person/john5");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. ASSERT_EQ(StatusCode::OK_200, res->status);
  6341. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6342. ASSERT_EQ("developer", res->body);
  6343. Params delete_params;
  6344. delete_params.emplace("name", "john5");
  6345. Headers headers;
  6346. headers.emplace("Custom-Header", "test-value");
  6347. res = cli_.Delete("/person", headers, delete_params);
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. ASSERT_EQ(StatusCode::OK_200, res->status);
  6350. ASSERT_EQ("DELETED", res->body);
  6351. res = cli_.Get("/person/john5");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, DeleteMethod3) {
  6356. auto res = cli_.Get("/person/john6");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6359. Params params;
  6360. params.emplace("name", "john6");
  6361. params.emplace("note", "tester");
  6362. res = cli_.Post("/person", params);
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. ASSERT_EQ(StatusCode::OK_200, res->status);
  6365. res = cli_.Get("/person/john6");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. ASSERT_EQ(StatusCode::OK_200, res->status);
  6368. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6369. ASSERT_EQ("tester", res->body);
  6370. Params delete_params;
  6371. delete_params.emplace("name", "john6");
  6372. Headers headers;
  6373. headers.emplace("Custom-Header", "test-value");
  6374. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6376. ASSERT_EQ(StatusCode::OK_200, res->status);
  6377. ASSERT_EQ("DELETED", res->body);
  6378. res = cli_.Get("/person/john6");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6381. }
  6382. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6383. Params params;
  6384. params.emplace("json", JSON_DATA);
  6385. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. ASSERT_EQ(StatusCode::OK_200, res->status);
  6388. ASSERT_EQ(JSON_DATA, res->body);
  6389. }
  6390. TEST_F(ServerTest, PostEmptyContent) {
  6391. auto res = cli_.Post("/empty", "", "text/plain");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. ASSERT_EQ(StatusCode::OK_200, res->status);
  6394. ASSERT_EQ("empty", res->body);
  6395. }
  6396. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6397. auto res = cli_.Post("/empty-no-content-type");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. ASSERT_EQ("empty-no-content-type", res->body);
  6401. }
  6402. TEST_F(ServerTest, PostPathOnly) {
  6403. auto res = cli_.Post("/path-only");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("path-only", res->body);
  6407. }
  6408. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6409. auto res = cli_.Post("/path-headers-only",
  6410. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. ASSERT_EQ(StatusCode::OK_200, res->status);
  6413. ASSERT_EQ("path-headers-only", res->body);
  6414. }
  6415. TEST_F(ServerTest, PostLarge) {
  6416. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ(LARGE_DATA, res->body);
  6420. }
  6421. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6422. auto res = cli_.Put("/empty-no-content-type");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. ASSERT_EQ("empty-no-content-type", res->body);
  6426. }
  6427. TEST_F(ServerTest, GetMethodDir) {
  6428. auto res = cli_.Get("/dir/");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::OK_200, res->status);
  6431. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6432. auto body = R"(<html>
  6433. <head>
  6434. </head>
  6435. <body>
  6436. <a href="/dir/test.html">Test</a>
  6437. <a href="/hi">hi</a>
  6438. </body>
  6439. </html>
  6440. )";
  6441. EXPECT_EQ(body, res->body);
  6442. }
  6443. TEST_F(ServerTest, GetMethodDirTest) {
  6444. auto res = cli_.Get("/dir/test.html");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::OK_200, res->status);
  6447. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6448. EXPECT_EQ("test.html", res->body);
  6449. }
  6450. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6451. auto res = cli_.Get("/dir/../dir/test.html");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6454. }
  6455. TEST_F(ServerTest, GetMethodInvalidPath) {
  6456. auto res = cli_.Get("/dir/../test.html");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6459. }
  6460. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6461. auto res = cli_.Get("/../www/dir/test.html");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6464. }
  6465. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6466. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6469. }
  6470. TEST_F(ServerTest, GetMethodDirMountTest) {
  6471. auto res = cli_.Get("/mount/dir/test.html");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6475. EXPECT_EQ("test.html", res->body);
  6476. }
  6477. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6478. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6481. }
  6482. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6483. auto res = cli_.Get("/mount/dir/../test.html");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6486. }
  6487. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6488. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6491. }
  6492. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6493. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6496. }
  6497. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6498. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6501. }
  6502. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6503. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6506. }
  6507. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6508. auto res = cli_.Get("/mount/dir");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6511. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6512. }
  6513. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6514. auto res = cli_.Get("//dir");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6517. EXPECT_FALSE(res->has_header("Location"));
  6518. }
  6519. TEST_F(ServerTest, PostMethod303) {
  6520. auto res = cli_.Post("/1", "body", "text/plain");
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6523. EXPECT_EQ("/2", res->get_header_value("Location"));
  6524. }
  6525. TEST_F(ServerTest, PostMethod303Redirect) {
  6526. cli_.set_follow_location(true);
  6527. auto res = cli_.Post("/1", "body", "text/plain");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. EXPECT_EQ("redirected.", res->body);
  6531. EXPECT_EQ("/2", res->location);
  6532. }
  6533. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6534. auto res = cli_.Get("/dir/test.abcde");
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6538. EXPECT_EQ("abcde", res->body);
  6539. }
  6540. TEST_F(ServerTest, StaticFileRange) {
  6541. auto res =
  6542. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6545. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6546. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6547. EXPECT_EQ(true, res->has_header("Content-Range"));
  6548. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6549. EXPECT_EQ(std::string("cd"), res->body);
  6550. }
  6551. TEST_F(ServerTest, StaticFileRanges) {
  6552. auto res = cli_.Get("/dir/test.abcde",
  6553. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6556. EXPECT_TRUE(
  6557. res->get_header_value("Content-Type")
  6558. .find(
  6559. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6560. 0);
  6561. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6562. }
  6563. TEST_F(ServerTest, StaticFileRangeHead) {
  6564. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6567. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6568. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6569. EXPECT_EQ(true, res->has_header("Content-Range"));
  6570. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6571. }
  6572. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6573. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6578. EXPECT_EQ(true, res->has_header("Content-Range"));
  6579. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6580. res->get_header_value("Content-Range"));
  6581. EXPECT_EQ("LAST\n", res->body);
  6582. }
  6583. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6584. auto res =
  6585. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6589. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6590. EXPECT_EQ(true, res->has_header("Content-Range"));
  6591. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6592. }
  6593. TEST_F(ServerTest, StaticFileBigFile) {
  6594. auto res = cli_.Get("/dir/1MB.txt");
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6598. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6599. }
  6600. TEST_F(ServerTest, InvalidBaseDirMount) {
  6601. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6602. }
  6603. TEST_F(ServerTest, Binary) {
  6604. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6605. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6606. "application/octet-stream");
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. ASSERT_EQ(StatusCode::OK_200, res->status);
  6609. ASSERT_EQ(4U, res->body.size());
  6610. res = cli_.Put("/binary", binary.data(), binary.size(),
  6611. "application/octet-stream");
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. ASSERT_EQ(StatusCode::OK_200, res->status);
  6614. ASSERT_EQ(4U, res->body.size());
  6615. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6616. "application/octet-stream");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. ASSERT_EQ(StatusCode::OK_200, res->status);
  6619. ASSERT_EQ(4U, res->body.size());
  6620. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6621. "application/octet-stream");
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. ASSERT_EQ(StatusCode::OK_200, res->status);
  6624. ASSERT_EQ(4U, res->body.size());
  6625. }
  6626. TEST_F(ServerTest, BinaryString) {
  6627. auto binary = std::string("\x00\x01\x02\x03", 4);
  6628. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. ASSERT_EQ(StatusCode::OK_200, res->status);
  6631. ASSERT_EQ(4U, res->body.size());
  6632. res = cli_.Put("/binary", binary, "application/octet-stream");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. ASSERT_EQ(StatusCode::OK_200, res->status);
  6635. ASSERT_EQ(4U, res->body.size());
  6636. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. ASSERT_EQ(StatusCode::OK_200, res->status);
  6639. ASSERT_EQ(4U, res->body.size());
  6640. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. ASSERT_EQ(StatusCode::OK_200, res->status);
  6643. ASSERT_EQ(4U, res->body.size());
  6644. }
  6645. TEST_F(ServerTest, EmptyRequest) {
  6646. auto res = cli_.Get("");
  6647. ASSERT_TRUE(!res);
  6648. EXPECT_EQ(Error::Connection, res.error());
  6649. }
  6650. TEST_F(ServerTest, LongRequest) {
  6651. std::string request;
  6652. for (size_t i = 0; i < 545; i++) {
  6653. request += "/TooLongRequest";
  6654. }
  6655. request += "OK";
  6656. auto res = cli_.Get(request.c_str());
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6659. }
  6660. TEST_F(ServerTest, TooLongRequest) {
  6661. std::string request;
  6662. for (size_t i = 0; i < 546; i++) {
  6663. request += "/TooLongRequest";
  6664. }
  6665. request += "_NG";
  6666. auto start = std::chrono::high_resolution_clock::now();
  6667. cli_.set_keep_alive(true);
  6668. auto res = cli_.Get(request.c_str());
  6669. auto end = std::chrono::high_resolution_clock::now();
  6670. auto elapsed =
  6671. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6672. .count();
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6675. EXPECT_LE(elapsed, 1000);
  6676. EXPECT_EQ("close", res->get_header_value("Connection"));
  6677. EXPECT_FALSE(cli_.is_socket_open());
  6678. }
  6679. TEST_F(ServerTest, AlmostTooLongRequest) {
  6680. // test for #2046 - URI length check shouldn't include other content on req
  6681. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6682. // leading /, space, HTTP/1.1)
  6683. std::string request =
  6684. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6685. auto res = cli_.Get(request.c_str());
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6688. }
  6689. TEST_F(ServerTest, LongHeader) {
  6690. Request req;
  6691. req.method = "GET";
  6692. req.path = "/hi";
  6693. std::string host_and_port;
  6694. host_and_port += HOST;
  6695. host_and_port += ":";
  6696. host_and_port += std::to_string(PORT);
  6697. req.headers.emplace("Host", host_and_port.c_str());
  6698. req.headers.emplace("Accept", "*/*");
  6699. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6700. req.headers.emplace(
  6701. "Header-Name",
  6702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6730. "@@@@@@@@@@@@@@@@");
  6731. auto res = std::make_shared<Response>();
  6732. auto error = Error::Success;
  6733. auto ret = cli_.send(req, *res, error);
  6734. ASSERT_TRUE(ret);
  6735. EXPECT_EQ(StatusCode::OK_200, res->status);
  6736. }
  6737. TEST_F(ServerTest, LongQueryValue) {
  6738. auto start = std::chrono::high_resolution_clock::now();
  6739. cli_.set_keep_alive(true);
  6740. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6741. auto end = std::chrono::high_resolution_clock::now();
  6742. auto elapsed =
  6743. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6744. .count();
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6747. EXPECT_LE(elapsed, 1000);
  6748. EXPECT_EQ("close", res->get_header_value("Connection"));
  6749. EXPECT_FALSE(cli_.is_socket_open());
  6750. }
  6751. TEST_F(ServerTest, TooLongQueryValue) {
  6752. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6753. ASSERT_FALSE(res);
  6754. EXPECT_EQ(Error::Read, res.error());
  6755. }
  6756. TEST_F(ServerTest, TooLongHeader) {
  6757. Request req;
  6758. req.method = "GET";
  6759. req.path = "/hi";
  6760. std::string host_and_port;
  6761. host_and_port += HOST;
  6762. host_and_port += ":";
  6763. host_and_port += std::to_string(PORT);
  6764. req.headers.emplace("Host", host_and_port.c_str());
  6765. req.headers.emplace("Accept", "*/*");
  6766. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6767. req.headers.emplace(
  6768. "Header-Name",
  6769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6797. "@@@@@@@@@@@@@@@@@");
  6798. auto res = std::make_shared<Response>();
  6799. auto error = Error::Success;
  6800. auto ret = cli_.send(req, *res, error);
  6801. ASSERT_TRUE(ret);
  6802. EXPECT_EQ(StatusCode::OK_200, res->status);
  6803. }
  6804. TEST_F(ServerTest, HeaderCountAtLimit) {
  6805. // Test with headers just under the 100 limit
  6806. httplib::Headers headers;
  6807. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6808. // This should keep us just under the 100 header limit
  6809. for (int i = 0; i < 95; i++) {
  6810. std::string name = "X-Test-Header-" + std::to_string(i);
  6811. std::string value = "value" + std::to_string(i);
  6812. headers.emplace(name, value);
  6813. }
  6814. // This should work fine as we're under the limit
  6815. auto res = cli_.Get("/hi", headers);
  6816. EXPECT_TRUE(res);
  6817. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6818. }
  6819. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6820. // Test with many headers to exceed the 100 limit
  6821. httplib::Headers headers;
  6822. // Add 150 headers to definitely exceed the 100 limit
  6823. for (int i = 0; i < 150; i++) {
  6824. std::string name = "X-Test-Header-" + std::to_string(i);
  6825. std::string value = "value" + std::to_string(i);
  6826. headers.emplace(name, value);
  6827. }
  6828. // This should fail due to exceeding header count limit
  6829. cli_.set_keep_alive(true);
  6830. auto res = cli_.Get("/hi", headers);
  6831. // The server should respond with 400 Bad Request
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6834. EXPECT_EQ("close", res->get_header_value("Connection"));
  6835. EXPECT_FALSE(cli_.is_socket_open());
  6836. }
  6837. TEST_F(ServerTest, PercentEncoding) {
  6838. auto res = cli_.Get("/e%6edwith%");
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_EQ(StatusCode::OK_200, res->status);
  6841. }
  6842. TEST_F(ServerTest, PercentEncodingUnicode) {
  6843. auto res = cli_.Get("/e%u006edwith%");
  6844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6845. EXPECT_EQ(StatusCode::OK_200, res->status);
  6846. }
  6847. TEST_F(ServerTest, InvalidPercentEncoding) {
  6848. auto res = cli_.Get("/%endwith%");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6851. }
  6852. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6853. auto res = cli_.Get("/%uendwith%");
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6856. }
  6857. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6858. auto res = cli_.Get("/hello?aaa=bbb%");
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6861. }
  6862. TEST_F(ServerTest, PlusSignEncoding) {
  6863. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_EQ("a +b", res->body);
  6867. }
  6868. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6869. // This test simulates a potential DoS attack using many headers
  6870. // to verify our security fix prevents memory exhaustion
  6871. httplib::Headers attack_headers;
  6872. // Attempt to add many headers like an attacker would (200 headers to far
  6873. // exceed limit)
  6874. for (int i = 0; i < 200; i++) {
  6875. std::string name = "X-Attack-Header-" + std::to_string(i);
  6876. std::string value = "attack_payload_" + std::to_string(i);
  6877. attack_headers.emplace(name, value);
  6878. }
  6879. // Try to POST with excessive headers
  6880. cli_.set_keep_alive(true);
  6881. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6882. // Should either fail or return 400 Bad Request due to security limit
  6883. if (res) {
  6884. // If we get a response, it should be 400 Bad Request
  6885. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6886. EXPECT_EQ("close", res->get_header_value("Connection"));
  6887. }
  6888. EXPECT_FALSE(cli_.is_socket_open());
  6889. }
  6890. TEST_F(ServerTest, MultipartFormData) {
  6891. UploadFormDataItems items = {
  6892. {"text1", "text default", "", ""},
  6893. {"text2", "aωb", "", ""},
  6894. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6895. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6896. {"file3", "", "", "application/octet-stream"},
  6897. {"file4", "", "", " application/json tmp-string "}};
  6898. auto res = cli_.Post("/multipart", items);
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. }
  6902. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6903. UploadFormDataItems items = {
  6904. {"text", "default text", "", ""},
  6905. {"multi_text1", "aaaaa", "", ""},
  6906. {"multi_text1", "bbbbb", "", ""},
  6907. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6908. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6909. "application/json"},
  6910. };
  6911. auto res = cli_.Post("/multipart/multi_file_values", items);
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(StatusCode::OK_200, res->status);
  6914. }
  6915. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6916. auto res = cli_.Get("/hi");
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6920. EXPECT_EQ("Hello World!", res->body);
  6921. }
  6922. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6923. Request req;
  6924. req.method = "POST";
  6925. req.path = "/chunked";
  6926. std::string host_and_port;
  6927. host_and_port += HOST;
  6928. host_and_port += ":";
  6929. host_and_port += std::to_string(PORT);
  6930. req.headers.emplace("Host", host_and_port.c_str());
  6931. req.headers.emplace("Accept", "*/*");
  6932. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6933. req.headers.emplace("Content-Type", "text/plain");
  6934. req.headers.emplace("Content-Length", "0");
  6935. req.headers.emplace(
  6936. "Transfer-Encoding",
  6937. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6938. // Client does not chunk, so make a chunked body manually.
  6939. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6940. auto res = std::make_shared<Response>();
  6941. auto error = Error::Success;
  6942. auto ret = cli_.send(req, *res, error);
  6943. ASSERT_TRUE(ret);
  6944. EXPECT_EQ(StatusCode::OK_200, res->status);
  6945. }
  6946. template <typename ClientT>
  6947. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6948. int expected_status) {
  6949. Request req;
  6950. req.method = "POST";
  6951. req.path = "/chunked";
  6952. std::string host_and_port;
  6953. host_and_port += HOST;
  6954. host_and_port += ":";
  6955. host_and_port += std::to_string(PORT);
  6956. req.headers.emplace("Host", host_and_port.c_str());
  6957. req.headers.emplace("Content-Length", "0");
  6958. req.headers.emplace("Transfer-Encoding", "chunked");
  6959. req.body = body;
  6960. auto res = std::make_shared<Response>();
  6961. auto error = Error::Success;
  6962. ASSERT_TRUE(cli.send(req, *res, error));
  6963. EXPECT_EQ(expected_status, res->status);
  6964. }
  6965. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6966. // rather than treat them as valid lengths.
  6967. template <typename ClientT>
  6968. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6969. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6970. }
  6971. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6972. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6973. }
  6974. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6975. expect_chunked_body_rejected(
  6976. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6977. }
  6978. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6979. // chunk-size line carries no CR, LF or other control character ahead of its
  6980. // terminator. Such a line must be refused rather than read as extension text.
  6981. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6982. expect_chunked_body_rejected(
  6983. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6984. }
  6985. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6986. expect_chunked_body_rejected(
  6987. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6988. }
  6989. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6990. expect_chunked_body_rejected(
  6991. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6992. }
  6993. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6994. // The literal stays split: a hex escape consumes every hex digit that
  6995. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6996. expect_chunked_body_rejected(
  6997. cli_, "4;a\x01"
  6998. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6999. }
  7000. // The bytes around chunk data are no payload, so they cannot ride on the
  7001. // payload limit
  7002. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7003. // Small enough that the whole request is sent before the server turns it
  7004. // down, yet past the limit by the last chunks
  7005. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7006. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7007. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7008. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7009. SCOPED_TRACE(size_line.substr(0, 2));
  7010. std::string body;
  7011. for (auto c : std::string("dechunked post body")) {
  7012. body += size_line + "\r\n" + c + "\r\n";
  7013. }
  7014. body += "0\r\n\r\n";
  7015. expect_chunked_body_rejected(cli_, body.c_str());
  7016. }
  7017. }
  7018. TEST_F(ServerTest, AcceptsChunkExtension) {
  7019. expect_chunked_body_status(cli_,
  7020. "4;name=value\r\ndech\r\n"
  7021. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7022. "0;last\r\n\r\n",
  7023. StatusCode::OK_200);
  7024. }
  7025. TEST_F(ServerTest, GetStreamed2) {
  7026. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7029. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7030. EXPECT_EQ(true, res->has_header("Content-Range"));
  7031. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7032. EXPECT_EQ(std::string("ab"), res->body);
  7033. }
  7034. TEST_F(ServerTest, GetStreamed) {
  7035. auto res = cli_.Get("/streamed");
  7036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7039. EXPECT_EQ(std::string("aaabbb"), res->body);
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7042. auto res = cli_.Get("/streamed-without-length",
  7043. Headers{make_range_header({{0, -1}})});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::OK_200, res->status);
  7046. EXPECT_EQ(false, res->has_header("Content-Length"));
  7047. EXPECT_EQ(false, res->has_header("Content-Range"));
  7048. EXPECT_EQ(std::string("abcdefg"), res->body);
  7049. }
  7050. TEST_F(ServerTest, GetStreamedWithRange1) {
  7051. auto res =
  7052. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7055. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7056. EXPECT_EQ(true, res->has_header("Content-Range"));
  7057. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7058. EXPECT_EQ(std::string("def"), res->body);
  7059. }
  7060. TEST_F(ServerTest, GetStreamedWithRange2) {
  7061. auto res =
  7062. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7065. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7066. EXPECT_EQ(true, res->has_header("Content-Range"));
  7067. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7068. EXPECT_EQ(std::string("bcdefg"), res->body);
  7069. }
  7070. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7071. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7074. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7075. EXPECT_EQ(true, res->has_header("Content-Range"));
  7076. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7077. EXPECT_EQ(std::string("efg"), res->body);
  7078. }
  7079. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7080. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7081. // the entire representation.
  7082. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7083. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7086. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7087. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7088. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7089. }
  7090. }
  7091. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7092. auto res =
  7093. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7096. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7097. EXPECT_EQ(false, res->has_header("Content-Range"));
  7098. EXPECT_EQ(0U, res->body.size());
  7099. }
  7100. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7101. // Only a 206 is served as a partial representation. Under any other status
  7102. // `apply_ranges()` reported the full content length, so the body must match
  7103. // that header, and the content provider must never be asked for an offset
  7104. // outside the representation.
  7105. auto check = [&](int status, const char *range) {
  7106. auto path =
  7107. std::string("/streamed-with-range?status=") + std::to_string(status);
  7108. auto ctx = path + " Range: " + range;
  7109. auto res = cli_.Get(path, Headers{{"Range", range}});
  7110. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7111. EXPECT_EQ(status, res->status) << ctx;
  7112. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7114. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7115. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7116. };
  7117. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7118. check(403, "bytes=3-5");
  7119. // The offset is far past the representation.
  7120. check(403, "bytes=100000-100200");
  7121. // `first_pos` is still -1 here, and the bounds asserts in
  7122. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7123. check(403, "bytes=-3");
  7124. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7125. // multipart branch would have written one that is empty.
  7126. check(403, "bytes=1-2, 4-5");
  7127. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7128. // covers the whole representation.
  7129. check(200, "bytes=3-5");
  7130. check(200, "bytes=1-2, 4-5");
  7131. }
  7132. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7133. auto res =
  7134. cli_.Get("/streamed-with-range",
  7135. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7136. "92233720368547758079223372036854775807"}});
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7140. EXPECT_EQ(false, res->has_header("Content-Range"));
  7141. EXPECT_EQ(0U, res->body.size());
  7142. }
  7143. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7144. auto res = cli_.Get(
  7145. "/with-range",
  7146. Headers{{"Range",
  7147. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7148. {"Accept-Encoding", ""}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("abcdefg"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. {"Range", "bytes=0-"},
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("abcdefg"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7169. auto res = cli_.Get("/streamed-with-range",
  7170. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7173. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7174. EXPECT_EQ(false, res->has_header("Content-Range"));
  7175. EXPECT_EQ(267U, res->body.size());
  7176. // Check that both range contents are present
  7177. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7178. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7179. // Check that Content-Range headers are present for both ranges
  7180. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7181. std::string::npos);
  7182. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7183. std::string::npos);
  7184. }
  7185. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7186. Ranges ranges;
  7187. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7188. ranges.emplace_back(0, -1);
  7189. }
  7190. auto res = cli_.Get("/streamed-with-range?error",
  7191. Headers{{make_range_header(ranges)}});
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7194. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7195. EXPECT_EQ(false, res->has_header("Content-Range"));
  7196. EXPECT_EQ(0U, res->body.size());
  7197. }
  7198. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7199. auto res = cli_.Get("/streamed-with-range",
  7200. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ(5U, res->body.size());
  7204. // Check that overlapping ranges are coalesced into a single range
  7205. EXPECT_EQ("bcdef", res->body);
  7206. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7207. // Should be single range, not multipart
  7208. EXPECT_TRUE(res->has_header("Content-Range"));
  7209. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7210. }
  7211. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7212. auto res = cli_.Get("/streamed-with-range",
  7213. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7216. EXPECT_EQ(268U, res->body.size());
  7217. // Check that both range contents are present
  7218. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7219. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7220. // Check that Content-Range headers are present for both ranges
  7221. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7222. std::string::npos);
  7223. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7224. std::string::npos);
  7225. }
  7226. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7227. auto res = cli_.Get("/streamed-with-range",
  7228. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7231. EXPECT_EQ(269U, res->body.size());
  7232. // Check that both duplicate range contents are present
  7233. size_t first_abc = res->body.find("abc\r\n");
  7234. EXPECT_TRUE(first_abc != std::string::npos);
  7235. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7236. EXPECT_TRUE(second_abc != std::string::npos);
  7237. // Check that Content-Range headers are present for both ranges
  7238. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7239. EXPECT_TRUE(first_range != std::string::npos);
  7240. size_t second_range =
  7241. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7242. EXPECT_TRUE(second_range != std::string::npos);
  7243. }
  7244. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7245. auto res =
  7246. cli_.Get("/streamed-with-range?error",
  7247. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7250. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7251. EXPECT_EQ(false, res->has_header("Content-Range"));
  7252. EXPECT_EQ(0U, res->body.size());
  7253. }
  7254. TEST_F(ServerTest, GetStreamedEndless) {
  7255. uint64_t offset = 0;
  7256. auto res = cli_.Get("/streamed-cancel",
  7257. [&](const char * /*data*/, uint64_t data_length) {
  7258. if (offset < 100) {
  7259. offset += data_length;
  7260. return true;
  7261. }
  7262. return false;
  7263. });
  7264. ASSERT_TRUE(!res);
  7265. EXPECT_EQ(Error::Canceled, res.error());
  7266. }
  7267. TEST_F(ServerTest, ClientStop) {
  7268. std::atomic_size_t count{4};
  7269. std::vector<std::thread> threads;
  7270. for (auto i = count.load(); i != 0; --i) {
  7271. threads.emplace_back([&]() {
  7272. auto res = cli_.Get("/streamed-cancel",
  7273. [&](const char *, uint64_t) { return true; });
  7274. --count;
  7275. ASSERT_TRUE(!res);
  7276. EXPECT_TRUE(res.error() == Error::Canceled ||
  7277. res.error() == Error::Read || res.error() == Error::Write);
  7278. });
  7279. }
  7280. std::this_thread::sleep_for(std::chrono::seconds(2));
  7281. while (count != 0) {
  7282. cli_.stop();
  7283. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7284. }
  7285. for (auto &t : threads) {
  7286. t.join();
  7287. }
  7288. }
  7289. TEST_F(ServerTest, GetWithRange1) {
  7290. auto res = cli_.Get("/with-range", Headers{
  7291. make_range_header({{3, 5}}),
  7292. {"Accept-Encoding", ""},
  7293. });
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7296. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7297. EXPECT_EQ(true, res->has_header("Content-Range"));
  7298. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7299. EXPECT_EQ(std::string("def"), res->body);
  7300. }
  7301. TEST_F(ServerTest, GetWithRange2) {
  7302. auto res = cli_.Get("/with-range", Headers{
  7303. make_range_header({{1, -1}}),
  7304. {"Accept-Encoding", ""},
  7305. });
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7308. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7309. EXPECT_EQ(true, res->has_header("Content-Range"));
  7310. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7311. EXPECT_EQ(std::string("bcdefg"), res->body);
  7312. }
  7313. TEST_F(ServerTest, GetWithRange3) {
  7314. auto res = cli_.Get("/with-range", Headers{
  7315. make_range_header({{0, 0}}),
  7316. {"Accept-Encoding", ""},
  7317. });
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7320. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7321. EXPECT_EQ(true, res->has_header("Content-Range"));
  7322. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7323. EXPECT_EQ(std::string("a"), res->body);
  7324. }
  7325. TEST_F(ServerTest, GetWithRange4) {
  7326. auto res = cli_.Get("/with-range", Headers{
  7327. make_range_header({{-1, 2}}),
  7328. {"Accept-Encoding", ""},
  7329. });
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7332. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7333. EXPECT_EQ(true, res->has_header("Content-Range"));
  7334. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7335. EXPECT_EQ(std::string("fg"), res->body);
  7336. }
  7337. TEST_F(ServerTest, GetWithRange5) {
  7338. auto res = cli_.Get("/with-range", Headers{
  7339. make_range_header({{0, 5}}),
  7340. {"Accept-Encoding", ""},
  7341. });
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7344. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7345. EXPECT_EQ(true, res->has_header("Content-Range"));
  7346. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7347. EXPECT_EQ(std::string("abcdef"), res->body);
  7348. }
  7349. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7350. auto res =
  7351. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7354. }
  7355. TEST_F(ServerTest, GetWithRangeMultipart) {
  7356. auto res =
  7357. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7360. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7361. EXPECT_EQ(false, res->has_header("Content-Range"));
  7362. EXPECT_EQ(267U, res->body.size());
  7363. }
  7364. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7365. auto res = cli_.Get("/with-range",
  7366. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7369. }
  7370. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7371. auto res = cli_.Get("/with-range-customized-response",
  7372. Headers{{make_range_header({{1, 2}})}});
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7375. EXPECT_EQ(true, res->has_header("Content-Length"));
  7376. EXPECT_EQ(false, res->has_header("Content-Range"));
  7377. EXPECT_EQ(JSON_DATA, res->body);
  7378. }
  7379. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7380. auto res = cli_.Get("/with-range-customized-response",
  7381. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7383. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7384. EXPECT_EQ(true, res->has_header("Content-Length"));
  7385. EXPECT_EQ(false, res->has_header("Content-Range"));
  7386. EXPECT_EQ(JSON_DATA, res->body);
  7387. }
  7388. TEST_F(ServerTest, Issue1772) {
  7389. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7392. }
  7393. TEST_F(ServerTest, Issue609) {
  7394. auto res = cli_.Delete("/issue609");
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. EXPECT_EQ(std::string("ok"), res->body);
  7398. }
  7399. TEST_F(ServerTest, GetStreamedChunked) {
  7400. auto res = cli_.Get("/streamed-chunked");
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ(std::string("123456789"), res->body);
  7404. }
  7405. TEST_F(ServerTest, GetStreamedChunked2) {
  7406. auto res = cli_.Get("/streamed-chunked2");
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ(std::string("123456789"), res->body);
  7410. }
  7411. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7412. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::OK_200, res->status);
  7415. EXPECT_EQ(std::string("123456789"), res->body);
  7416. EXPECT_TRUE(res->has_header("Trailer"));
  7417. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7418. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7419. // Trailers are now stored separately from headers (security fix)
  7420. EXPECT_EQ(2U, res->trailers.size());
  7421. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7422. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7423. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7424. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7425. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7426. // Verify trailers are NOT in headers (security verification)
  7427. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7428. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7429. }
  7430. TEST_F(ServerTest, LargeChunkedPost) {
  7431. Request req;
  7432. req.method = "POST";
  7433. req.path = "/large-chunked";
  7434. std::string host_and_port;
  7435. host_and_port += HOST;
  7436. host_and_port += ":";
  7437. host_and_port += std::to_string(PORT);
  7438. req.headers.emplace("Host", host_and_port.c_str());
  7439. req.headers.emplace("Accept", "*/*");
  7440. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7441. req.headers.emplace("Content-Type", "text/plain");
  7442. req.headers.emplace("Content-Length", "0");
  7443. req.headers.emplace("Transfer-Encoding", "chunked");
  7444. std::string long_string(30 * 1024u, 'a');
  7445. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7446. // Attempt to make a large enough post to exceed OS buffers, to test that
  7447. // the server handles short reads if the full chunk data isn't available.
  7448. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7449. auto res = std::make_shared<Response>();
  7450. auto error = Error::Success;
  7451. auto ret = cli_.send(req, *res, error);
  7452. ASSERT_TRUE(ret);
  7453. EXPECT_EQ(StatusCode::OK_200, res->status);
  7454. }
  7455. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7456. auto res = cli_.Get("/remote_addr");
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7460. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7461. }
  7462. TEST_F(ServerTest, GetMethodLocalAddr) {
  7463. auto res = cli_.Get("/local_addr");
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7467. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7468. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7469. }
  7470. TEST_F(ServerTest, HTTPResponseSplitting) {
  7471. auto res = cli_.Get("/http_response_splitting");
  7472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. }
  7475. TEST_F(ServerTest, SlowRequest) {
  7476. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7477. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7478. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7479. }
  7480. #if 0
  7481. TEST_F(ServerTest, SlowPost) {
  7482. char buffer[64 * 1024];
  7483. memset(buffer, 0x42, sizeof(buffer));
  7484. auto res = cli_.Post(
  7485. "/slowpost", 64 * 1024 * 1024,
  7486. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7487. auto ret = sink.write(buffer, sizeof(buffer));
  7488. EXPECT_TRUE(ret);
  7489. return true;
  7490. },
  7491. "text/plain");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. }
  7495. TEST_F(ServerTest, SlowPostFail) {
  7496. char buffer[64 * 1024];
  7497. memset(buffer, 0x42, sizeof(buffer));
  7498. cli_.set_write_timeout(std::chrono::seconds(0));
  7499. auto res = cli_.Post(
  7500. "/slowpost", 64 * 1024 * 1024,
  7501. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7502. sink.write(buffer, sizeof(buffer));
  7503. return true;
  7504. },
  7505. "text/plain");
  7506. ASSERT_TRUE(!res);
  7507. EXPECT_EQ(Error::Write, res.error());
  7508. }
  7509. #endif
  7510. TEST_F(ServerTest, Put) {
  7511. auto res = cli_.Put("/put", "PUT", "text/plain");
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::OK_200, res->status);
  7514. EXPECT_EQ("PUT", res->body);
  7515. }
  7516. TEST_F(ServerTest, PutWithContentProvider) {
  7517. auto res = cli_.Put(
  7518. "/put", 3,
  7519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7520. sink.os << "PUT";
  7521. return true;
  7522. },
  7523. "text/plain");
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ(StatusCode::OK_200, res->status);
  7526. EXPECT_EQ("PUT", res->body);
  7527. }
  7528. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7529. auto res = cli_.Post(
  7530. "/post", 42,
  7531. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7532. return false;
  7533. },
  7534. "text/plain");
  7535. ASSERT_TRUE(!res);
  7536. EXPECT_EQ(Error::Canceled, res.error());
  7537. }
  7538. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7539. auto res = cli_.Put(
  7540. "/put",
  7541. [](size_t /*offset*/, DataSink &sink) {
  7542. sink.os << "PUT";
  7543. sink.done();
  7544. return true;
  7545. },
  7546. "text/plain");
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. EXPECT_EQ("PUT", res->body);
  7550. }
  7551. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7552. auto res = cli_.Post(
  7553. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7554. "text/plain");
  7555. ASSERT_TRUE(!res);
  7556. EXPECT_EQ(Error::Canceled, res.error());
  7557. }
  7558. TEST_F(ServerTest, PostLoopBack) {
  7559. std::string body;
  7560. auto res = cli_.Post(
  7561. "/post-loopback", 9,
  7562. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7563. EXPECT_EQ(9u, length);
  7564. sink.write("123", 3);
  7565. sink.write("456", 3);
  7566. sink.write("789", 3);
  7567. return true;
  7568. },
  7569. "text/plain",
  7570. [&body](const char *data, size_t data_length) {
  7571. body.append(data, data_length);
  7572. return true;
  7573. });
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. EXPECT_EQ("123456789", body);
  7577. }
  7578. TEST_F(ServerTest, PutLoopBack) {
  7579. std::string body;
  7580. auto res = cli_.Put(
  7581. "/put-loopback", 9,
  7582. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7583. EXPECT_EQ(9u, length);
  7584. sink.write("123", 3);
  7585. sink.write("456", 3);
  7586. sink.write("789", 3);
  7587. return true;
  7588. },
  7589. "text/plain",
  7590. [&body](const char *data, size_t data_length) {
  7591. body.append(data, data_length);
  7592. return true;
  7593. });
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. EXPECT_EQ("123456789", body);
  7597. }
  7598. TEST_F(ServerTest, PatchLoopBack) {
  7599. std::string body;
  7600. auto res = cli_.Patch(
  7601. "/patch-loopback", 9,
  7602. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7603. EXPECT_EQ(9u, length);
  7604. sink.write("123", 3);
  7605. sink.write("456", 3);
  7606. sink.write("789", 3);
  7607. return true;
  7608. },
  7609. "text/plain",
  7610. [&body](const char *data, size_t data_length) {
  7611. body.append(data, data_length);
  7612. return true;
  7613. });
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. EXPECT_EQ("123456789", body);
  7617. }
  7618. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7619. std::string body;
  7620. auto res = cli_.Post(
  7621. "/post-loopback",
  7622. [](size_t /*offset*/, DataSink &sink) {
  7623. sink.write("123", 3);
  7624. sink.write("456", 3);
  7625. sink.write("789", 3);
  7626. sink.done();
  7627. return true;
  7628. },
  7629. "text/plain",
  7630. [&body](const char *data, size_t data_length) {
  7631. body.append(data, data_length);
  7632. return true;
  7633. });
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ("123456789", body);
  7637. }
  7638. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7639. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7640. cli_.set_compress(true);
  7641. auto res = cli_.Put(
  7642. "/put", 3,
  7643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7644. sink.os << "PUT";
  7645. return true;
  7646. },
  7647. "text/plain");
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. EXPECT_EQ("PUT", res->body);
  7651. }
  7652. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7653. cli_.set_compress(true);
  7654. auto res = cli_.Post(
  7655. "/post", 42,
  7656. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7657. return false;
  7658. },
  7659. "text/plain");
  7660. ASSERT_TRUE(!res);
  7661. EXPECT_EQ(Error::Canceled, res.error());
  7662. }
  7663. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7664. cli_.set_compress(true);
  7665. auto res = cli_.Put(
  7666. "/put",
  7667. [](size_t /*offset*/, DataSink &sink) {
  7668. sink.os << "PUT";
  7669. sink.done();
  7670. return true;
  7671. },
  7672. "text/plain");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("PUT", res->body);
  7676. }
  7677. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7678. cli_.set_compress(true);
  7679. auto res = cli_.Post(
  7680. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7681. "text/plain");
  7682. ASSERT_TRUE(!res);
  7683. EXPECT_EQ(Error::Canceled, res.error());
  7684. }
  7685. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7686. cli_.set_compress(true);
  7687. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ(LARGE_DATA, res->body);
  7691. }
  7692. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7693. #ifdef CPPHTTPLIB_SSL_ENABLED
  7694. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7695. Client cli(s.c_str());
  7696. cli.enable_server_certificate_verification(false);
  7697. #else
  7698. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7699. Client cli(s.c_str());
  7700. #endif
  7701. cli.set_compress(true);
  7702. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. EXPECT_EQ(LARGE_DATA, res->body);
  7706. // The compressed size should be less than a 10th of the original. May vary
  7707. // depending on the zlib library.
  7708. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7709. static_cast<uint64_t>(10 * 1024 * 1024));
  7710. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7711. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7712. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7713. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7714. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7715. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7716. #endif
  7717. }
  7718. TEST_F(ServerTest, PutContentWithDeflate) {
  7719. cli_.set_compress(false);
  7720. Headers headers;
  7721. headers.emplace("Content-Encoding", "deflate");
  7722. // PUT in deflate format:
  7723. auto res = cli_.Put("/put", headers,
  7724. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PUT", res->body);
  7728. }
  7729. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7730. Headers headers;
  7731. headers.emplace("Accept-Encoding", "gzip, deflate");
  7732. auto res = cli_.Get("/streamed-chunked", headers);
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ(std::string("123456789"), res->body);
  7736. }
  7737. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7738. Headers headers;
  7739. headers.emplace("Accept-Encoding", "gzip, deflate");
  7740. auto res = cli_.Get("/streamed-chunked2", headers);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ(std::string("123456789"), res->body);
  7744. }
  7745. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7746. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST(GzipDecompressor, ChunkedDecompression) {
  7751. std::string data;
  7752. for (size_t i = 0; i < 32 * 1024; ++i) {
  7753. data.push_back(static_cast<char>('a' + i % 26));
  7754. }
  7755. std::string compressed_data;
  7756. {
  7757. httplib::detail::gzip_compressor compressor;
  7758. bool result = compressor.compress(
  7759. data.data(), data.size(),
  7760. /*last=*/true,
  7761. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7762. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7763. compressed_data_size);
  7764. return true;
  7765. });
  7766. ASSERT_TRUE(result);
  7767. }
  7768. std::string decompressed_data;
  7769. {
  7770. httplib::detail::gzip_decompressor decompressor;
  7771. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7772. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7773. size_t chunk_size = 130;
  7774. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7775. chunk_begin += chunk_size) {
  7776. size_t current_chunk_size =
  7777. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7778. bool result = decompressor.decompress(
  7779. compressed_data.data() + chunk_begin, current_chunk_size,
  7780. [&](const char *decompressed_data_chunk,
  7781. size_t decompressed_data_chunk_size) {
  7782. decompressed_data.insert(decompressed_data.size(),
  7783. decompressed_data_chunk,
  7784. decompressed_data_chunk_size);
  7785. return true;
  7786. });
  7787. ASSERT_TRUE(result);
  7788. }
  7789. }
  7790. ASSERT_EQ(data, decompressed_data);
  7791. }
  7792. TEST(GzipDecompressor, DeflateDecompression) {
  7793. std::string original_text = "Raw deflate without gzip";
  7794. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7795. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7796. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7797. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7798. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7799. std::string decompressed_data;
  7800. {
  7801. httplib::detail::gzip_decompressor decompressor;
  7802. bool result = decompressor.decompress(
  7803. compressed_data.data(), compressed_data.size(),
  7804. [&](const char *decompressed_data_chunk,
  7805. size_t decompressed_data_chunk_size) {
  7806. decompressed_data.insert(decompressed_data.size(),
  7807. decompressed_data_chunk,
  7808. decompressed_data_chunk_size);
  7809. return true;
  7810. });
  7811. ASSERT_TRUE(result);
  7812. }
  7813. ASSERT_EQ(original_text, decompressed_data);
  7814. }
  7815. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7816. std::string original_text = "Raw deflate without gzip";
  7817. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7818. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7819. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7820. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7821. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7822. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7823. std::string decompressed_data;
  7824. {
  7825. httplib::detail::gzip_decompressor decompressor;
  7826. bool result = decompressor.decompress(
  7827. compressed_data.data(), compressed_data.size(),
  7828. [&](const char *decompressed_data_chunk,
  7829. size_t decompressed_data_chunk_size) {
  7830. decompressed_data.insert(decompressed_data.size(),
  7831. decompressed_data_chunk,
  7832. decompressed_data_chunk_size);
  7833. return true;
  7834. });
  7835. ASSERT_TRUE(result);
  7836. }
  7837. ASSERT_EQ(original_text, decompressed_data);
  7838. }
  7839. #endif
  7840. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7841. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7842. Headers headers;
  7843. headers.emplace("Accept-Encoding", "br");
  7844. auto res = cli_.Get("/streamed-chunked", headers);
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::OK_200, res->status);
  7847. EXPECT_EQ(std::string("123456789"), res->body);
  7848. }
  7849. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7850. Headers headers;
  7851. headers.emplace("Accept-Encoding", "br");
  7852. auto res = cli_.Get("/streamed-chunked2", headers);
  7853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7854. EXPECT_EQ(StatusCode::OK_200, res->status);
  7855. EXPECT_EQ(std::string("123456789"), res->body);
  7856. }
  7857. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7858. cli_.set_compress(true);
  7859. auto res = cli_.Put(
  7860. "/put", 3,
  7861. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7862. sink.os << "PUT";
  7863. return true;
  7864. },
  7865. "text/plain");
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::OK_200, res->status);
  7868. EXPECT_EQ("PUT", res->body);
  7869. }
  7870. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7871. cli_.set_compress(true);
  7872. auto res = cli_.Put(
  7873. "/put",
  7874. [](size_t /*offset*/, DataSink &sink) {
  7875. sink.os << "PUT";
  7876. sink.done();
  7877. return true;
  7878. },
  7879. "text/plain");
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ("PUT", res->body);
  7883. }
  7884. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7885. cli_.set_compress(true);
  7886. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. EXPECT_EQ(LARGE_DATA, res->body);
  7890. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7891. }
  7892. #endif
  7893. TEST_F(ServerTest, Patch) {
  7894. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. EXPECT_EQ("PATCH", res->body);
  7898. }
  7899. TEST_F(ServerTest, Delete) {
  7900. auto res = cli_.Delete("/delete");
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. EXPECT_EQ("DELETE", res->body);
  7904. }
  7905. TEST_F(ServerTest, DeleteContentReceiver) {
  7906. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. EXPECT_EQ("content", res->body);
  7910. }
  7911. TEST_F(ServerTest, Options) {
  7912. auto res = cli_.Options("*");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7916. EXPECT_TRUE(res->body.empty());
  7917. }
  7918. TEST_F(ServerTest, URL) {
  7919. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. }
  7923. TEST_F(ServerTest, ArrayParam) {
  7924. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. }
  7928. TEST_F(ServerTest, ArrayParamValues) {
  7929. auto res =
  7930. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7932. EXPECT_EQ(StatusCode::OK_200, res->status);
  7933. }
  7934. TEST_F(ServerTest, NoMultipleHeaders) {
  7935. Headers headers = {{"Content-Length", "5"}};
  7936. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7937. "text/plain");
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. }
  7941. TEST_F(ServerTest, PostContentReceiver) {
  7942. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. ASSERT_EQ(StatusCode::OK_200, res->status);
  7945. ASSERT_EQ("content", res->body);
  7946. }
  7947. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7948. UploadFormDataItems items = {
  7949. {"text1", "text default", "", ""},
  7950. {"text2", "aωb", "", ""},
  7951. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7952. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7953. {"file3", "", "", "application/octet-stream"},
  7954. };
  7955. auto res = cli_.Post("/content_receiver", items);
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7960. UploadFormDataItems items = {
  7961. {"text1", "text default", "", ""},
  7962. {"text2", "aωb", "", ""},
  7963. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7964. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7965. {"file3", "", "", "application/octet-stream"},
  7966. };
  7967. auto boundary = std::string("+++++");
  7968. std::string body;
  7969. for (const auto &item : items) {
  7970. body += "--" + boundary + "\r\n";
  7971. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7972. if (!item.filename.empty()) {
  7973. body += "; filename=\"" + item.filename + "\"";
  7974. }
  7975. body += "\r\n";
  7976. if (!item.content_type.empty()) {
  7977. body += "Content-Type: " + item.content_type + "\r\n";
  7978. }
  7979. body += "\r\n";
  7980. body += item.content + "\r\n";
  7981. }
  7982. body += "--" + boundary + "--\r\n";
  7983. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7984. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. }
  7988. TEST(MultipartFormDataTest, FieldEscaping) {
  7989. Server svr;
  7990. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7991. const ContentReader &content_reader) {
  7992. ASSERT_TRUE(req.is_multipart_form_data());
  7993. std::vector<FormData> received;
  7994. content_reader(
  7995. [&](const FormData &file) {
  7996. received.push_back(file);
  7997. return true;
  7998. },
  7999. [&](const char *data, size_t data_length) {
  8000. received.back().content.append(data, data_length);
  8001. return true;
  8002. });
  8003. // '"', CR and LF in names and filenames are escaped following the
  8004. // WHATWG HTML standard, so each part still parses as a single part
  8005. // with no injected headers. Content types get CR/LF escaped too,
  8006. // while '"' (legal there, e.g. quoted charset) is preserved.
  8007. ASSERT_EQ(4U, received.size());
  8008. EXPECT_EQ("na%22me", received[0].name);
  8009. EXPECT_EQ("quoted name", received[0].content);
  8010. EXPECT_EQ("file", received[1].name);
  8011. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8012. received[1].filename);
  8013. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8014. EXPECT_EQ("injected", received[1].content);
  8015. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8016. EXPECT_EQ("my%22file.txt", received[2].filename);
  8017. EXPECT_EQ("cr lf name", received[2].content);
  8018. EXPECT_EQ("typed", received[3].name);
  8019. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8020. received[3].content_type);
  8021. EXPECT_EQ("typed content", received[3].content);
  8022. });
  8023. auto port = svr.bind_to_any_port("localhost");
  8024. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8025. auto se = detail::scope_exit([&] {
  8026. svr.stop();
  8027. t.join();
  8028. ASSERT_FALSE(svr.is_running());
  8029. });
  8030. svr.wait_until_ready();
  8031. Client cli("localhost", port);
  8032. UploadFormDataItems items = {
  8033. {"na\"me", "quoted name", "", ""},
  8034. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8035. "application/octet-stream"},
  8036. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8037. {"typed", "typed content", "",
  8038. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8039. };
  8040. auto res = cli.Post("/post", items);
  8041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8042. EXPECT_EQ(StatusCode::OK_200, res->status);
  8043. }
  8044. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8045. const UploadFormDataItems items = {
  8046. {"name1", "Content 1", "", ""},
  8047. {"name2", "Content 2", "file2.txt", "text/plain"},
  8048. };
  8049. Server svr;
  8050. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8051. const ContentReader &content_reader) {
  8052. ASSERT_TRUE(req.is_multipart_form_data());
  8053. std::vector<FormData> received;
  8054. content_reader(
  8055. [&](const FormData &file) {
  8056. received.push_back(file);
  8057. return true;
  8058. },
  8059. [&](const char *data, size_t data_length) {
  8060. received.back().content.append(data, data_length);
  8061. return true;
  8062. });
  8063. ASSERT_EQ(2U, received.size());
  8064. EXPECT_EQ("name1", received[0].name);
  8065. EXPECT_EQ("Content 1", received[0].content);
  8066. EXPECT_EQ("name2", received[1].name);
  8067. EXPECT_EQ("Content 2", received[1].content);
  8068. EXPECT_EQ("file2.txt", received[1].filename);
  8069. EXPECT_EQ("text/plain", received[1].content_type);
  8070. });
  8071. auto port = svr.bind_to_any_port("localhost");
  8072. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8073. auto se = detail::scope_exit([&] {
  8074. svr.stop();
  8075. t.join();
  8076. ASSERT_FALSE(svr.is_running());
  8077. });
  8078. svr.wait_until_ready();
  8079. Client cli("localhost", port);
  8080. // Whole-body serialization with a generated boundary
  8081. {
  8082. MultipartFormDataWriter writer;
  8083. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8084. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8085. writer.content_type());
  8086. auto body = writer.serialize(items);
  8087. EXPECT_EQ(body.size(), writer.content_length(items));
  8088. auto res = cli.Post("/post", body, writer.content_type());
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. }
  8092. // Per-part framing with a custom boundary via a content provider
  8093. {
  8094. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8095. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8096. MultipartFormDataWriter writer("custom-boundary_123");
  8097. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8098. std::string body;
  8099. for (const auto &item : items) {
  8100. body += writer.item_begin(item);
  8101. body += item.content;
  8102. body += MultipartFormDataWriter::item_end();
  8103. }
  8104. body += writer.finish();
  8105. EXPECT_EQ(body.size(), writer.content_length(items));
  8106. auto res = cli.Post(
  8107. "/post", body.size(),
  8108. [&](size_t offset, size_t length, DataSink &sink) {
  8109. sink.write(body.data() + offset, length);
  8110. return true;
  8111. },
  8112. writer.content_type());
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. }
  8117. TEST_F(ServerTest, PostContentReceiverGzip) {
  8118. cli_.set_compress(true);
  8119. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. ASSERT_EQ(StatusCode::OK_200, res->status);
  8122. ASSERT_EQ("content", res->body);
  8123. }
  8124. TEST_F(ServerTest, PutContentReceiver) {
  8125. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. ASSERT_EQ(StatusCode::OK_200, res->status);
  8128. ASSERT_EQ("content", res->body);
  8129. }
  8130. TEST_F(ServerTest, PatchContentReceiver) {
  8131. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. ASSERT_EQ(StatusCode::OK_200, res->status);
  8134. ASSERT_EQ("content", res->body);
  8135. }
  8136. template <typename ClientType>
  8137. void TestWithHeadersAndContentReceiver(
  8138. ClientType &cli,
  8139. std::function<Result(ClientType &, const std::string &, const Headers &,
  8140. const std::string &, const std::string &,
  8141. ContentReceiver, DownloadProgress)>
  8142. request_func) {
  8143. Headers headers;
  8144. headers.emplace("X-Custom-Header", "test-value");
  8145. std::string received_body;
  8146. auto res = request_func(
  8147. cli, "/content_receiver", headers, "content", "application/json",
  8148. [&](const char *data, size_t data_length) {
  8149. received_body.append(data, data_length);
  8150. return true;
  8151. },
  8152. nullptr);
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. EXPECT_EQ(StatusCode::OK_200, res->status);
  8155. EXPECT_EQ("content", received_body);
  8156. }
  8157. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8158. #ifdef CPPHTTPLIB_SSL_ENABLED
  8159. using ClientT = SSLClient;
  8160. #else
  8161. using ClientT = Client;
  8162. #endif
  8163. TestWithHeadersAndContentReceiver<ClientT>(
  8164. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8165. const std::string &body, const std::string &content_type,
  8166. ContentReceiver receiver, DownloadProgress progress) {
  8167. return cli.Post(path, headers, body, content_type, receiver, progress);
  8168. });
  8169. }
  8170. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8171. #ifdef CPPHTTPLIB_SSL_ENABLED
  8172. using ClientT = SSLClient;
  8173. #else
  8174. using ClientT = Client;
  8175. #endif
  8176. TestWithHeadersAndContentReceiver<ClientT>(
  8177. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8178. const std::string &body, const std::string &content_type,
  8179. ContentReceiver receiver, DownloadProgress progress) {
  8180. return cli.Put(path, headers, body, content_type, receiver, progress);
  8181. });
  8182. }
  8183. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8184. #ifdef CPPHTTPLIB_SSL_ENABLED
  8185. using ClientT = SSLClient;
  8186. #else
  8187. using ClientT = Client;
  8188. #endif
  8189. TestWithHeadersAndContentReceiver<ClientT>(
  8190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8191. const std::string &body, const std::string &content_type,
  8192. ContentReceiver receiver, DownloadProgress progress) {
  8193. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8194. });
  8195. }
  8196. template <typename ClientType>
  8197. void TestWithHeadersAndContentReceiverWithProgress(
  8198. ClientType &cli,
  8199. std::function<Result(ClientType &, const std::string &, const Headers &,
  8200. const std::string &, const std::string &,
  8201. ContentReceiver, DownloadProgress)>
  8202. request_func) {
  8203. Headers headers;
  8204. headers.emplace("X-Test-Header", "progress-test");
  8205. std::string received_body;
  8206. auto progress_called = false;
  8207. auto res = request_func(
  8208. cli, "/content_receiver", headers, "content", "text/plain",
  8209. [&](const char *data, size_t data_length) {
  8210. received_body.append(data, data_length);
  8211. return true;
  8212. },
  8213. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8214. progress_called = true;
  8215. return true;
  8216. });
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. EXPECT_EQ("content", received_body);
  8220. EXPECT_TRUE(progress_called);
  8221. }
  8222. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8223. #ifdef CPPHTTPLIB_SSL_ENABLED
  8224. using ClientT = SSLClient;
  8225. #else
  8226. using ClientT = Client;
  8227. #endif
  8228. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8229. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8230. const std::string &body, const std::string &content_type,
  8231. ContentReceiver receiver, DownloadProgress progress) {
  8232. return cli.Post(path, headers, body, content_type, receiver, progress);
  8233. });
  8234. }
  8235. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8236. #ifdef CPPHTTPLIB_SSL_ENABLED
  8237. using ClientT = SSLClient;
  8238. #else
  8239. using ClientT = Client;
  8240. #endif
  8241. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8242. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8243. const std::string &body, const std::string &content_type,
  8244. ContentReceiver receiver, DownloadProgress progress) {
  8245. return cli.Put(path, headers, body, content_type, receiver, progress);
  8246. });
  8247. }
  8248. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8249. #ifdef CPPHTTPLIB_SSL_ENABLED
  8250. using ClientT = SSLClient;
  8251. #else
  8252. using ClientT = Client;
  8253. #endif
  8254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8256. const std::string &body, const std::string &content_type,
  8257. ContentReceiver receiver, DownloadProgress progress) {
  8258. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8259. });
  8260. }
  8261. template <typename ClientType>
  8262. void TestWithHeadersAndContentReceiverError(
  8263. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8264. const Headers &, const std::string &,
  8265. const std::string &, ContentReceiver)>
  8266. request_func) {
  8267. Headers headers;
  8268. headers.emplace("X-Error-Test", "true");
  8269. std::string received_body;
  8270. auto receiver_failed = false;
  8271. auto res =
  8272. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8273. [&](const char *data, size_t data_length) {
  8274. received_body.append(data, data_length);
  8275. receiver_failed = true;
  8276. return false;
  8277. });
  8278. ASSERT_FALSE(res);
  8279. EXPECT_TRUE(receiver_failed);
  8280. }
  8281. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8282. #ifdef CPPHTTPLIB_SSL_ENABLED
  8283. using ClientT = SSLClient;
  8284. #else
  8285. using ClientT = Client;
  8286. #endif
  8287. TestWithHeadersAndContentReceiverError<ClientT>(
  8288. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8289. const std::string &body, const std::string &content_type,
  8290. ContentReceiver receiver) {
  8291. return cli.Post(path, headers, body, content_type, receiver);
  8292. });
  8293. }
  8294. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8295. #ifdef CPPHTTPLIB_SSL_ENABLED
  8296. using ClientT = SSLClient;
  8297. #else
  8298. using ClientT = Client;
  8299. #endif
  8300. TestWithHeadersAndContentReceiverError<ClientT>(
  8301. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8302. const std::string &body, const std::string &content_type,
  8303. ContentReceiver receiver) {
  8304. return cli.Put(path, headers, body, content_type, receiver);
  8305. });
  8306. }
  8307. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8308. #ifdef CPPHTTPLIB_SSL_ENABLED
  8309. using ClientT = SSLClient;
  8310. #else
  8311. using ClientT = Client;
  8312. #endif
  8313. TestWithHeadersAndContentReceiverError<ClientT>(
  8314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8315. const std::string &body, const std::string &content_type,
  8316. ContentReceiver receiver) {
  8317. return cli.Patch(path, headers, body, content_type, receiver);
  8318. });
  8319. }
  8320. TEST_F(ServerTest, PostQueryStringAndBody) {
  8321. auto res =
  8322. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8324. ASSERT_EQ(StatusCode::OK_200, res->status);
  8325. }
  8326. TEST_F(ServerTest, HTTP2Magic) {
  8327. Request req;
  8328. req.method = "PRI";
  8329. req.path = "*";
  8330. req.body = "SM";
  8331. auto res = std::make_shared<Response>();
  8332. auto error = Error::Success;
  8333. auto ret = cli_.send(req, *res, error);
  8334. ASSERT_TRUE(ret);
  8335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8336. }
  8337. TEST_F(ServerTest, KeepAlive) {
  8338. auto res = cli_.Get("/hi");
  8339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8342. EXPECT_EQ("Hello World!", res->body);
  8343. res = cli_.Get("/hi");
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::OK_200, res->status);
  8346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8347. EXPECT_EQ("Hello World!", res->body);
  8348. res = cli_.Get("/hi");
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_EQ(StatusCode::OK_200, res->status);
  8351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8352. EXPECT_EQ("Hello World!", res->body);
  8353. res = cli_.Get("/not-exist");
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8356. res = cli_.Post("/empty", "", "text/plain");
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ(StatusCode::OK_200, res->status);
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("empty", res->body);
  8361. EXPECT_EQ("close", res->get_header_value("Connection"));
  8362. res = cli_.Post(
  8363. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8364. "text/plain");
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ(StatusCode::OK_200, res->status);
  8367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8368. EXPECT_EQ("empty", res->body);
  8369. cli_.set_keep_alive(false);
  8370. res = cli_.Get("/last-request");
  8371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8372. EXPECT_EQ(StatusCode::OK_200, res->status);
  8373. EXPECT_EQ("close", res->get_header_value("Connection"));
  8374. }
  8375. TEST_F(ServerTest, TooManyRedirect) {
  8376. cli_.set_follow_location(true);
  8377. auto res = cli_.Get("/redirect/0");
  8378. ASSERT_TRUE(!res);
  8379. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8380. }
  8381. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8382. Request req;
  8383. req.method = "FOOBAR";
  8384. req.path = "/hi";
  8385. cli_.set_keep_alive(true);
  8386. auto res = cli_.send(req);
  8387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8388. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8389. EXPECT_EQ("close", res->get_header_value("Connection"));
  8390. EXPECT_FALSE(cli_.is_socket_open());
  8391. }
  8392. TEST_F(ServerTest, CustomRouteReadsBody) {
  8393. const std::string xml =
  8394. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8395. Request req;
  8396. req.method = "PROPFIND";
  8397. req.path = "/dav/dir";
  8398. req.set_header("Depth", "1");
  8399. req.body = xml;
  8400. auto res = cli_.send(req);
  8401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8402. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8403. EXPECT_EQ(xml, res->body);
  8404. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8405. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8406. }
  8407. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8408. Request req;
  8409. req.method = "PROPFIND";
  8410. req.path = "/dav/42";
  8411. auto res = cli_.send(req);
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8414. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8415. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8416. }
  8417. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8418. Request req;
  8419. req.method = "PROPFIND";
  8420. req.path = "/dav-re/123";
  8421. auto res = cli_.send(req);
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8424. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8425. }
  8426. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8427. Request req;
  8428. req.method = "MKCOL";
  8429. req.path = "/dav-mkcol";
  8430. auto res = cli_.send(req);
  8431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8432. EXPECT_EQ(StatusCode::Created_201, res->status);
  8433. }
  8434. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8435. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8436. Request req;
  8437. req.method = "REPORT";
  8438. req.path = "/dav-report";
  8439. req.body = xml;
  8440. auto res = cli_.send(req);
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8443. EXPECT_EQ(xml, res->body);
  8444. }
  8445. // A content reader route must fire even when the request carries no body,
  8446. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8447. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8448. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8449. Request req;
  8450. req.method = "REPORT";
  8451. req.path = "/dav-report";
  8452. auto res = cli_.send(req);
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8455. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8456. }
  8457. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8458. Request req;
  8459. req.method = "PROPFIND";
  8460. req.path = "/not-dav";
  8461. auto res = cli_.send(req);
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8464. }
  8465. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8466. Request req;
  8467. req.method = "UNLOCK";
  8468. req.path = "/dav/dir";
  8469. cli_.set_keep_alive(true);
  8470. auto res = cli_.send(req);
  8471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8472. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8473. EXPECT_EQ("close", res->get_header_value("Connection"));
  8474. EXPECT_FALSE(cli_.is_socket_open());
  8475. }
  8476. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8477. // The mount point serves this path, but only for GET and HEAD.
  8478. auto get_res = cli_.Get("/dir/index.html");
  8479. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8480. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8481. Request req;
  8482. req.method = "PROPFIND";
  8483. req.path = "/dir/index.html";
  8484. auto res = cli_.send(req);
  8485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8487. }
  8488. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8489. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8490. cli_.set_keep_alive(true);
  8491. for (auto i = 0; i < 2; i++) {
  8492. Request req;
  8493. req.method = "PROPFIND";
  8494. req.path = "/dav/dir";
  8495. req.body = xml;
  8496. auto res = cli_.send(req);
  8497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8498. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8499. EXPECT_EQ(xml, res->body);
  8500. EXPECT_TRUE(cli_.is_socket_open());
  8501. }
  8502. // A built-in method must still be served on the same connection.
  8503. cli_.set_keep_alive(false);
  8504. auto res = cli_.Get("/hi");
  8505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8506. EXPECT_EQ(StatusCode::OK_200, res->status);
  8507. EXPECT_EQ("close", res->get_header_value("Connection"));
  8508. }
  8509. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8510. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8511. Request req;
  8512. req.method = "PROPFIND";
  8513. req.path = "/dav/dir";
  8514. req.set_header("Expect", "100-continue");
  8515. req.body = xml;
  8516. auto res = cli_.send(req);
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8519. EXPECT_EQ(xml, res->body);
  8520. }
  8521. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8523. TEST_F(ServerTest, Gzip) {
  8524. Headers headers;
  8525. headers.emplace("Accept-Encoding", "gzip, deflate");
  8526. auto res = cli_.Get("/compress", headers);
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8529. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8530. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8531. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8532. "7890123456789012345678901234567890",
  8533. res->body);
  8534. EXPECT_EQ(StatusCode::OK_200, res->status);
  8535. }
  8536. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8537. Headers headers;
  8538. headers.emplace("Accept-Encoding", "gzip, deflate");
  8539. auto res = cli_.Get("/compress-with-charset", headers);
  8540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8542. EXPECT_EQ("application/json; charset=utf-8",
  8543. res->get_header_value("Content-Type"));
  8544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8545. "7890123456789012345678901234567890",
  8546. res->body);
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8550. Headers headers;
  8551. headers.emplace("Accept-Encoding", "");
  8552. auto res = cli_.Get("/compress", headers);
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8556. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8558. "7890123456789012345678901234567890",
  8559. res->body);
  8560. EXPECT_EQ(StatusCode::OK_200, res->status);
  8561. }
  8562. TEST_F(ServerTest, GzipWithContentReceiver) {
  8563. Headers headers;
  8564. headers.emplace("Accept-Encoding", "gzip, deflate");
  8565. std::string body;
  8566. auto res =
  8567. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8568. EXPECT_EQ(100U, data_length);
  8569. body.append(data, data_length);
  8570. return true;
  8571. });
  8572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8573. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8575. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8576. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8577. "7890123456789012345678901234567890",
  8578. body);
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8582. Headers headers;
  8583. headers.emplace("Accept-Encoding", "gzip, deflate");
  8584. cli_.set_decompress(false);
  8585. auto res = cli_.Get("/compress", headers);
  8586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8587. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8589. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8590. EXPECT_EQ(33U, res->body.size());
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. }
  8593. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8594. Headers headers;
  8595. headers.emplace("Accept-Encoding", "");
  8596. std::string body;
  8597. auto res =
  8598. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8599. EXPECT_EQ(100U, data_length);
  8600. body.append(data, data_length);
  8601. return true;
  8602. });
  8603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8604. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8605. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8606. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8607. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8608. "7890123456789012345678901234567890",
  8609. body);
  8610. EXPECT_EQ(StatusCode::OK_200, res->status);
  8611. }
  8612. TEST_F(ServerTest, NoGzip) {
  8613. Headers headers;
  8614. headers.emplace("Accept-Encoding", "gzip, deflate");
  8615. auto res = cli_.Get("/nocompress", headers);
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8618. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8621. "7890123456789012345678901234567890",
  8622. res->body);
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. }
  8625. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8626. Headers headers;
  8627. headers.emplace("Accept-Encoding", "gzip, deflate");
  8628. std::string body;
  8629. auto res = cli_.Get("/nocompress", headers,
  8630. [&](const char *data, size_t data_length) {
  8631. EXPECT_EQ(100U, data_length);
  8632. body.append(data, data_length);
  8633. return true;
  8634. });
  8635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8636. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8637. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8638. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8639. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8640. "7890123456789012345678901234567890",
  8641. body);
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. }
  8644. TEST_F(ServerTest, MultipartFormDataGzip) {
  8645. UploadFormDataItems items = {
  8646. {"key1", "test", "", ""},
  8647. {"key2", "--abcdefg123", "", ""},
  8648. };
  8649. cli_.set_compress(true);
  8650. auto res = cli_.Post("/compress-multipart", items);
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_EQ(StatusCode::OK_200, res->status);
  8653. }
  8654. #endif
  8655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8656. // Static file compression is opt-in, so these run their own server rather than
  8657. // flipping it on for the shared ServerTest fixture, which would silently
  8658. // rewrite what every other static file test is asserting.
  8659. class StaticFileCompressionTest : public ::testing::Test {
  8660. protected:
  8661. void TearDown() override {
  8662. if (t_.joinable()) {
  8663. svr_.stop();
  8664. t_.join();
  8665. }
  8666. }
  8667. int start(const std::function<void(Server &)> &configure = nullptr) {
  8668. // Serves the same tree as a directory of build-time compressed assets
  8669. // would be served: the mount point names the coding the files are already
  8670. // stored in. Registered before "/" so it is the one that matches.
  8671. svr_.set_mount_point("/pre-encoded", "./www",
  8672. {{"Content-Encoding", "gzip"}});
  8673. svr_.set_mount_point("/", "./www");
  8674. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8675. res.set_file_content("./www/dir/index.html", "text/html");
  8676. });
  8677. svr_.Get("/pre-encoded-file-content",
  8678. [](const Request & /*req*/, Response &res) {
  8679. res.set_header("Content-Encoding", "gzip");
  8680. res.set_file_content("./www/dir/index.html", "text/html");
  8681. });
  8682. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8683. res.set_content_provider(
  8684. 6, "text/plain",
  8685. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8686. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8687. return true;
  8688. });
  8689. });
  8690. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8691. res.set_content_provider(
  8692. 1000, "text/plain",
  8693. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8694. if (offset < 100) {
  8695. std::string data(100, 'A');
  8696. sink.write(data.data(), data.size());
  8697. return true;
  8698. }
  8699. std::this_thread::sleep_for(std::chrono::seconds(2));
  8700. std::string data(900, 'B');
  8701. sink.write(data.data(), data.size());
  8702. return true;
  8703. });
  8704. });
  8705. if (configure) { configure(svr_); }
  8706. auto port = svr_.bind_to_any_port(HOST);
  8707. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8708. svr_.wait_until_ready();
  8709. return port;
  8710. }
  8711. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8712. // Every file under ./www except 1MB.txt is smaller than the default
  8713. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8714. // it out of the way.
  8715. static void enable_without_floor(Server &svr) {
  8716. svr.set_static_file_compression(true);
  8717. svr.set_static_file_compression_min_length(0);
  8718. }
  8719. Server svr_;
  8720. std::thread t_;
  8721. };
  8722. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8723. auto port = start();
  8724. Client cli(HOST, port);
  8725. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8727. EXPECT_EQ(StatusCode::OK_200, res->status);
  8728. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8729. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8730. EXPECT_EQ(1048576U, res->body.size());
  8731. }
  8732. TEST_F(StaticFileCompressionTest, MountPoint) {
  8733. auto port = start(enable);
  8734. Client cli(HOST, port);
  8735. cli.set_decompress(false);
  8736. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8738. EXPECT_EQ(StatusCode::OK_200, res->status);
  8739. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8740. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8741. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8742. // The response stays self-delimiting: a length, not a chunked body.
  8743. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8744. EXPECT_EQ(std::to_string(res->body.size()),
  8745. res->get_header_value("Content-Length"));
  8746. EXPECT_LT(res->body.size(), 1048576U);
  8747. EXPECT_FALSE(res->body.empty());
  8748. }
  8749. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8750. auto port = start(enable);
  8751. Client cli(HOST, port);
  8752. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8754. EXPECT_EQ(StatusCode::OK_200, res->status);
  8755. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8756. EXPECT_EQ(1048576U, res->body.size());
  8757. }
  8758. TEST_F(StaticFileCompressionTest, FileContent) {
  8759. auto port = start(enable_without_floor);
  8760. Client cli(HOST, port);
  8761. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8763. EXPECT_EQ(StatusCode::OK_200, res->status);
  8764. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8765. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8766. EXPECT_EQ(104U, res->body.size());
  8767. }
  8768. // A handler that serves an already-encoded file names the coding itself. The
  8769. // file-backed path decided its coding from Accept-Encoding and the content
  8770. // type alone, so it compressed the stored bytes a second time and appended a
  8771. // second Content-Encoding field line.
  8772. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8773. auto port = start(enable_without_floor);
  8774. Client cli(HOST, port);
  8775. cli.set_decompress(false);
  8776. auto res = cli.Get("/pre-encoded-file-content",
  8777. Headers{{"Accept-Encoding", "gzip"}});
  8778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8779. EXPECT_EQ(StatusCode::OK_200, res->status);
  8780. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8782. // Vary belongs to a coding the server chose, and it chose none here.
  8783. EXPECT_FALSE(res->has_header("Vary"));
  8784. // The file travels exactly as it is stored on disk.
  8785. EXPECT_EQ(104U, res->body.size());
  8786. }
  8787. // The 1MB file clears the default floor, so this one runs the configuration a
  8788. // deployment would actually have.
  8789. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8790. auto port = start(enable);
  8791. Client cli(HOST, port);
  8792. cli.set_decompress(false);
  8793. auto res =
  8794. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ(StatusCode::OK_200, res->status);
  8797. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8798. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8799. EXPECT_FALSE(res->has_header("Vary"));
  8800. EXPECT_EQ(1048576U, res->body.size());
  8801. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8802. }
  8803. TEST_F(StaticFileCompressionTest, Head) {
  8804. auto port = start(enable);
  8805. Client cli(HOST, port);
  8806. cli.set_decompress(false);
  8807. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8808. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8809. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ(StatusCode::OK_200, res->status);
  8812. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8813. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8814. // HEAD still reports the size a GET would return.
  8815. EXPECT_EQ(get->get_header_value("Content-Length"),
  8816. res->get_header_value("Content-Length"));
  8817. EXPECT_TRUE(res->body.empty());
  8818. }
  8819. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8820. auto port = start(enable);
  8821. Client cli(HOST, port);
  8822. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8823. {"Accept-Encoding", "gzip"}});
  8824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8825. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8826. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8827. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8828. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8829. EXPECT_EQ("cd", res->body);
  8830. }
  8831. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8832. auto port = start(enable);
  8833. Client cli(HOST, port);
  8834. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8838. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8839. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8840. }
  8841. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8842. auto port = start(enable);
  8843. Client cli(HOST, port);
  8844. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8848. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8849. EXPECT_TRUE(res->body.empty());
  8850. }
  8851. TEST_F(StaticFileCompressionTest, MinLength) {
  8852. auto port = start(enable);
  8853. Client cli(HOST, port);
  8854. // 104 bytes, well under the default floor. Compressing it would add the
  8855. // gzip header and trailer to a body that already fits in one packet.
  8856. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ(StatusCode::OK_200, res->status);
  8859. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8860. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8861. }
  8862. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8863. auto port = start([](Server &svr) {
  8864. svr.set_static_file_compression(true);
  8865. svr.set_static_file_compression_min_length(1);
  8866. });
  8867. Client cli(HOST, port);
  8868. cli.set_decompress(false);
  8869. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8871. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8872. // A 9-byte file comes back larger than it went in, because gzip's header and
  8873. // trailer outweigh anything deflate can save. That is the end of the range
  8874. // the floor exists to keep out.
  8875. EXPECT_GT(res->body.size(), 9U);
  8876. }
  8877. TEST_F(StaticFileCompressionTest, MaxLength) {
  8878. auto port = start([](Server &svr) {
  8879. svr.set_static_file_compression(true);
  8880. svr.set_static_file_compression_min_length(0);
  8881. svr.set_static_file_compression_max_length(1024);
  8882. });
  8883. Client cli(HOST, port);
  8884. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8885. // defines `small` as a macro on Windows.
  8886. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8887. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8888. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8889. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8890. // Under it: compressed.
  8891. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8892. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8893. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8894. }
  8895. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8896. auto port = start(enable_without_floor);
  8897. Client cli(HOST, port);
  8898. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8899. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8900. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8901. auto identity_etag = identity->get_header_value("ETag");
  8902. ASSERT_FALSE(identity_etag.empty());
  8903. auto gzipped =
  8904. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8905. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8906. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8907. auto gzip_etag = gzipped->get_header_value("ETag");
  8908. ASSERT_FALSE(gzip_etag.empty());
  8909. // Two representations, two validators.
  8910. EXPECT_NE(identity_etag, gzip_etag);
  8911. // Each one revalidates against the request that would produce it...
  8912. auto fresh =
  8913. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8914. {"If-None-Match", gzip_etag}});
  8915. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8916. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8917. auto fresh_identity =
  8918. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8919. {"If-None-Match", identity_etag}});
  8920. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8921. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8922. // ...and not against the other representation.
  8923. auto crossed =
  8924. cli.Get("/dir/index.html",
  8925. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8926. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8927. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8928. }
  8929. // The opt-in covers responses the server reads off disk itself. A caller's own
  8930. // known-length provider keeps its Content-Length and, more importantly, keeps
  8931. // delivering incrementally: routing it through a compressor would hold every
  8932. // write back until zlib's window filled.
  8933. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8934. auto port = start(enable);
  8935. Client cli(HOST, port);
  8936. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8938. EXPECT_EQ(StatusCode::OK_200, res->status);
  8939. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8940. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8941. EXPECT_EQ("aaabbb", res->body);
  8942. }
  8943. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8944. auto port = start(enable);
  8945. Client cli(HOST, port);
  8946. cli.set_read_timeout(1, 0);
  8947. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8948. Headers{{"Accept-Encoding", "gzip"}});
  8949. ASSERT_TRUE(handle.is_valid());
  8950. // The provider writes 100 bytes and then stalls for longer than the read
  8951. // timeout. Those first bytes have to arrive anyway: run the response through
  8952. // a compressor and zlib holds them until its window fills, so the read would
  8953. // come back empty instead.
  8954. char buf[256];
  8955. auto n = handle.read(buf, sizeof(buf));
  8956. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8957. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8958. }
  8959. #endif
  8960. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8961. TEST_F(ServerTest, Brotli) {
  8962. Headers headers;
  8963. headers.emplace("Accept-Encoding", "br");
  8964. auto res = cli_.Get("/compress", headers);
  8965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8966. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8968. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8969. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8970. "7890123456789012345678901234567890",
  8971. res->body);
  8972. EXPECT_EQ(StatusCode::OK_200, res->status);
  8973. }
  8974. #endif
  8975. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8976. TEST_F(ServerTest, Zstd) {
  8977. Headers headers;
  8978. headers.emplace("Accept-Encoding", "zstd");
  8979. auto res = cli_.Get("/compress", headers);
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8983. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8984. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8985. "7890123456789012345678901234567890",
  8986. res->body);
  8987. EXPECT_EQ(StatusCode::OK_200, res->status);
  8988. }
  8989. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8990. Headers headers;
  8991. headers.emplace("Accept-Encoding", "");
  8992. auto res = cli_.Get("/compress", headers);
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8996. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8998. "7890123456789012345678901234567890",
  8999. res->body);
  9000. EXPECT_EQ(StatusCode::OK_200, res->status);
  9001. }
  9002. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9003. Headers headers;
  9004. headers.emplace("Accept-Encoding", "zstd");
  9005. std::string body;
  9006. auto res =
  9007. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9008. EXPECT_EQ(100U, data_length);
  9009. body.append(data, data_length);
  9010. return true;
  9011. });
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9015. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9017. "7890123456789012345678901234567890",
  9018. body);
  9019. EXPECT_EQ(StatusCode::OK_200, res->status);
  9020. }
  9021. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9022. Headers headers;
  9023. headers.emplace("Accept-Encoding", "zstd");
  9024. cli_.set_decompress(false);
  9025. auto res = cli_.Get("/compress", headers);
  9026. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9027. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9028. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9029. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9031. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9033. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9034. EXPECT_EQ(StatusCode::OK_200, res->status);
  9035. ASSERT_EQ(26U, res->body.size());
  9036. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9037. 0);
  9038. }
  9039. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9040. Headers headers;
  9041. headers.emplace("Accept-Encoding", "");
  9042. std::string body;
  9043. auto res =
  9044. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9045. EXPECT_EQ(100U, data_length);
  9046. body.append(data, data_length);
  9047. return true;
  9048. });
  9049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9050. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9052. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9053. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9054. "7890123456789012345678901234567890",
  9055. body);
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST_F(ServerTest, NoZstd) {
  9059. Headers headers;
  9060. headers.emplace("Accept-Encoding", "zstd");
  9061. auto res = cli_.Get("/nocompress", headers);
  9062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9063. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9064. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9065. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9066. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9067. "7890123456789012345678901234567890",
  9068. res->body);
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. }
  9071. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9072. Headers headers;
  9073. headers.emplace("Accept-Encoding", "zstd");
  9074. std::string body;
  9075. auto res = cli_.Get("/nocompress", headers,
  9076. [&](const char *data, size_t data_length) {
  9077. EXPECT_EQ(100U, data_length);
  9078. body.append(data, data_length);
  9079. return true;
  9080. });
  9081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9082. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9083. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9084. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9085. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9086. "7890123456789012345678901234567890",
  9087. body);
  9088. EXPECT_EQ(StatusCode::OK_200, res->status);
  9089. }
  9090. // TODO: How to enable zstd ??
  9091. TEST_F(ServerTest, MultipartFormDataZstd) {
  9092. UploadFormDataItems items = {
  9093. {"key1", "test", "", ""},
  9094. {"key2", "--abcdefg123", "", ""},
  9095. };
  9096. Headers headers;
  9097. headers.emplace("Accept-Encoding", "zstd");
  9098. cli_.set_compress(true);
  9099. auto res = cli_.Post("/compress-multipart", headers, items);
  9100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9101. EXPECT_EQ(StatusCode::OK_200, res->status);
  9102. }
  9103. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9104. Headers headers;
  9105. headers.emplace("Accept-Encoding", "zstd");
  9106. cli_.set_compress(true);
  9107. auto res = cli_.Put(
  9108. "/put", headers, 3,
  9109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9110. sink.os << "PUT";
  9111. return true;
  9112. },
  9113. "text/plain");
  9114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9115. EXPECT_EQ(StatusCode::OK_200, res->status);
  9116. EXPECT_EQ("PUT", res->body);
  9117. }
  9118. // Pre-compression logging tests
  9119. TEST_F(ServerTest, PreCompressionLogging) {
  9120. // Test data for compression (matches the actual /compress endpoint content)
  9121. const std::string test_content =
  9122. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9123. "3456789012345678901234567890";
  9124. // Variables to capture logging data
  9125. std::string pre_compression_body;
  9126. std::string pre_compression_content_type;
  9127. std::string pre_compression_content_encoding;
  9128. std::string post_compression_body;
  9129. std::string post_compression_content_type;
  9130. std::string post_compression_content_encoding;
  9131. // Set up pre-compression logger
  9132. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9133. const Response &res) {
  9134. pre_compression_body = res.body;
  9135. pre_compression_content_type = res.get_header_value("Content-Type");
  9136. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9137. });
  9138. // Set up post-compression logger
  9139. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9140. post_compression_body = res.body;
  9141. post_compression_content_type = res.get_header_value("Content-Type");
  9142. post_compression_content_encoding =
  9143. res.get_header_value("Content-Encoding");
  9144. });
  9145. // Test with gzip compression
  9146. Headers headers;
  9147. headers.emplace("Accept-Encoding", "gzip");
  9148. auto res = cli_.Get("/compress", headers);
  9149. // Verify response was compressed
  9150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9153. // Verify pre-compression logger captured uncompressed content
  9154. EXPECT_EQ(test_content, pre_compression_body);
  9155. EXPECT_EQ("text/plain", pre_compression_content_type);
  9156. EXPECT_TRUE(pre_compression_content_encoding
  9157. .empty()); // No encoding header before compression
  9158. // Verify post-compression logger captured compressed content
  9159. EXPECT_NE(test_content,
  9160. post_compression_body); // Should be different after compression
  9161. EXPECT_EQ("text/plain", post_compression_content_type);
  9162. EXPECT_EQ("gzip", post_compression_content_encoding);
  9163. // Verify compressed content is smaller
  9164. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9165. }
  9166. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9167. const std::string test_content =
  9168. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9169. "3456789012345678901234567890";
  9170. std::string pre_compression_body;
  9171. std::string post_compression_body;
  9172. svr_.set_pre_compression_logger(
  9173. [&](const Request & /*req*/, const Response &res) {
  9174. pre_compression_body = res.body;
  9175. });
  9176. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9177. post_compression_body = res.body;
  9178. });
  9179. Headers headers;
  9180. headers.emplace("Accept-Encoding", "br");
  9181. auto res = cli_.Get("/compress", headers);
  9182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9183. EXPECT_EQ(StatusCode::OK_200, res->status);
  9184. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9185. // Verify pre-compression content is uncompressed
  9186. EXPECT_EQ(test_content, pre_compression_body);
  9187. // Verify post-compression content is compressed
  9188. EXPECT_NE(test_content, post_compression_body);
  9189. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9190. }
  9191. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9192. const std::string test_content =
  9193. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9194. "3456789012345678901234567890";
  9195. std::string pre_compression_body;
  9196. std::string post_compression_body;
  9197. svr_.set_pre_compression_logger(
  9198. [&](const Request & /*req*/, const Response &res) {
  9199. pre_compression_body = res.body;
  9200. });
  9201. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9202. post_compression_body = res.body;
  9203. });
  9204. // Request without compression (use /nocompress endpoint)
  9205. Headers headers;
  9206. auto res = cli_.Get("/nocompress", headers);
  9207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9208. EXPECT_EQ(StatusCode::OK_200, res->status);
  9209. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9210. // Pre-compression logger should not be called when no compression is applied
  9211. EXPECT_TRUE(
  9212. pre_compression_body.empty()); // Pre-compression logger not called
  9213. EXPECT_EQ(
  9214. test_content,
  9215. post_compression_body); // Post-compression logger captures final content
  9216. }
  9217. TEST_F(ServerTest, LoggerSeesContentLength) {
  9218. size_t logged_content_length = 0;
  9219. std::string logged_content_length_header;
  9220. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9221. logged_content_length = res.content_length_;
  9222. logged_content_length_header = res.get_header_value("Content-Length");
  9223. });
  9224. auto res = cli_.Get("/nocompress");
  9225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9226. EXPECT_EQ(StatusCode::OK_200, res->status);
  9227. EXPECT_EQ(res->body.size(), logged_content_length);
  9228. EXPECT_EQ(std::to_string(logged_content_length),
  9229. logged_content_length_header);
  9230. }
  9231. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9232. const std::string test_content =
  9233. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9234. "3456789012345678901234567890";
  9235. std::string pre_compression_body;
  9236. bool pre_logger_called = false;
  9237. // Set only pre-compression logger
  9238. svr_.set_pre_compression_logger(
  9239. [&](const Request & /*req*/, const Response &res) {
  9240. pre_compression_body = res.body;
  9241. pre_logger_called = true;
  9242. });
  9243. Headers headers;
  9244. headers.emplace("Accept-Encoding", "gzip");
  9245. auto res = cli_.Get("/compress", headers);
  9246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9247. EXPECT_EQ(StatusCode::OK_200, res->status);
  9248. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9249. // Verify pre-compression logger was called
  9250. EXPECT_TRUE(pre_logger_called);
  9251. EXPECT_EQ(test_content, pre_compression_body);
  9252. }
  9253. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9254. {
  9255. // Test with Expect: 100-continue header - success case
  9256. // Server returns 100 Continue, client sends body, server returns 200 OK
  9257. Request req;
  9258. req.method = "POST";
  9259. req.path = "/post-large";
  9260. req.set_header("Expect", "100-continue");
  9261. req.body = LARGE_DATA;
  9262. Response res;
  9263. auto error = Error::Success;
  9264. cli_.set_keep_alive(true);
  9265. auto ret = cli_.send(req, res, error);
  9266. EXPECT_TRUE(ret);
  9267. EXPECT_EQ(StatusCode::OK_200, res.status);
  9268. EXPECT_EQ(LARGE_DATA, res.body);
  9269. }
  9270. {
  9271. // Test with Expect: 100-continue header - error case
  9272. // Client should not send the body when server returns an error
  9273. Request req;
  9274. req.method = "POST";
  9275. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9276. req.set_header("Expect", "100-continue");
  9277. req.body = LARGE_DATA;
  9278. Response res;
  9279. auto error = Error::Success;
  9280. auto start = std::chrono::high_resolution_clock::now();
  9281. cli_.set_keep_alive(true);
  9282. auto ret = cli_.send(req, res, error);
  9283. auto end = std::chrono::high_resolution_clock::now();
  9284. auto elapsed =
  9285. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9286. .count();
  9287. // With Expect: 100-continue, request completes successfully but with error
  9288. EXPECT_TRUE(ret);
  9289. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9290. EXPECT_EQ("close", res.get_header_value("Connection"));
  9291. EXPECT_FALSE(cli_.is_socket_open());
  9292. EXPECT_LE(elapsed, 2000);
  9293. }
  9294. {
  9295. // Send an extra GET request to ensure error recovery without hanging
  9296. Request req;
  9297. req.method = "GET";
  9298. req.path = "/hi";
  9299. auto start = std::chrono::high_resolution_clock::now();
  9300. auto res = cli_.send(req);
  9301. auto end = std::chrono::high_resolution_clock::now();
  9302. auto elapsed =
  9303. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9304. .count();
  9305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9306. EXPECT_EQ(StatusCode::OK_200, res->status);
  9307. EXPECT_EQ("Hello World!", res->body);
  9308. EXPECT_LE(elapsed, 500);
  9309. }
  9310. }
  9311. TEST(ZstdDecompressor, ChunkedDecompression) {
  9312. std::string data;
  9313. for (size_t i = 0; i < 32 * 1024; ++i) {
  9314. data.push_back(static_cast<char>('a' + i % 26));
  9315. }
  9316. std::string compressed_data;
  9317. {
  9318. httplib::detail::zstd_compressor compressor;
  9319. bool result = compressor.compress(
  9320. data.data(), data.size(),
  9321. /*last=*/true,
  9322. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9323. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9324. compressed_data_size);
  9325. return true;
  9326. });
  9327. ASSERT_TRUE(result);
  9328. }
  9329. std::string decompressed_data;
  9330. {
  9331. httplib::detail::zstd_decompressor decompressor;
  9332. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9333. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9334. size_t chunk_size = 130;
  9335. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9336. chunk_begin += chunk_size) {
  9337. size_t current_chunk_size =
  9338. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9339. bool result = decompressor.decompress(
  9340. compressed_data.data() + chunk_begin, current_chunk_size,
  9341. [&](const char *decompressed_data_chunk,
  9342. size_t decompressed_data_chunk_size) {
  9343. decompressed_data.insert(decompressed_data.size(),
  9344. decompressed_data_chunk,
  9345. decompressed_data_chunk_size);
  9346. return true;
  9347. });
  9348. ASSERT_TRUE(result);
  9349. }
  9350. }
  9351. ASSERT_EQ(data, decompressed_data);
  9352. }
  9353. TEST(ZstdDecompressor, Decompress) {
  9354. std::string original_text = "Compressed with ZSTD";
  9355. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9356. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9357. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9358. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9359. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9360. std::string decompressed_data;
  9361. {
  9362. httplib::detail::zstd_decompressor decompressor;
  9363. bool result = decompressor.decompress(
  9364. compressed_data.data(), compressed_data.size(),
  9365. [&](const char *decompressed_data_chunk,
  9366. size_t decompressed_data_chunk_size) {
  9367. decompressed_data.insert(decompressed_data.size(),
  9368. decompressed_data_chunk,
  9369. decompressed_data_chunk_size);
  9370. return true;
  9371. });
  9372. ASSERT_TRUE(result);
  9373. }
  9374. ASSERT_EQ(original_text, decompressed_data);
  9375. }
  9376. #endif
  9377. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9378. // separate chunks so that the server sees each part in its own read(). Used to
  9379. // place a read boundary at a specific offset of a request body.
  9380. static bool send_request_in_parts(time_t read_timeout_sec,
  9381. const std::vector<std::string> &parts,
  9382. std::string *resp = nullptr,
  9383. int port = PORT) {
  9384. auto error = Error::Success;
  9385. auto client_sock = detail::create_client_socket(
  9386. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9387. /*connection_timeout_sec=*/5, 0,
  9388. /*read_timeout_sec=*/5, 0,
  9389. /*write_timeout_sec=*/5, 0, std::string(), error);
  9390. if (client_sock == INVALID_SOCKET) { return false; }
  9391. auto ret = detail::process_client_socket(
  9392. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9393. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9394. for (size_t i = 0; i < parts.size(); i++) {
  9395. const auto &part = parts[i];
  9396. if (part.size() !=
  9397. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9398. return false;
  9399. }
  9400. if (i + 1 < parts.size()) {
  9401. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9402. }
  9403. }
  9404. char buf[512];
  9405. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9406. while (line_reader.getline()) {
  9407. if (resp) { *resp += line_reader.ptr(); }
  9408. }
  9409. return true;
  9410. });
  9411. detail::close_socket(client_sock);
  9412. return ret;
  9413. }
  9414. // Sends a raw request to a server listening at HOST:PORT.
  9415. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9416. std::string *resp = nullptr, int port = PORT) {
  9417. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9418. }
  9419. #ifdef CPPHTTPLIB_SSL_ENABLED
  9420. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9422. ASSERT_TRUE(svr.is_valid());
  9423. svr.set_read_timeout(1, 0);
  9424. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9425. auto se = detail::scope_exit([&] {
  9426. svr.stop();
  9427. t.join();
  9428. ASSERT_FALSE(svr.is_running());
  9429. });
  9430. svr.wait_until_ready();
  9431. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9432. // keeps each wait well within the read timeout. The server gives up a
  9433. // second in, so the bytes sent after that fail.
  9434. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9435. parts.resize(26, std::string(1, '\0'));
  9436. EXPECT_FALSE(send_request_in_parts(5, parts));
  9437. }
  9438. #endif
  9439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9440. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9441. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9442. const std::vector<std::string> &parts,
  9443. std::string *resp = nullptr,
  9444. int port = PORT) {
  9445. auto error = Error::Success;
  9446. auto sock = detail::create_client_socket(
  9447. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9448. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9449. /*write_timeout_sec=*/5, 0, std::string(), error);
  9450. if (sock == INVALID_SOCKET) { return false; }
  9451. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9452. auto ctx = SSL_CTX_new(TLS_client_method());
  9453. auto ssl = SSL_new(ctx);
  9454. auto ssl_se = detail::scope_exit([&] {
  9455. SSL_free(ssl);
  9456. SSL_CTX_free(ctx);
  9457. });
  9458. SSL_set_fd(ssl, static_cast<int>(sock));
  9459. if (SSL_connect(ssl) != 1) { return false; }
  9460. for (size_t i = 0; i < parts.size(); i++) {
  9461. const auto &part = parts[i];
  9462. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9463. static_cast<int>(part.size())) {
  9464. return false;
  9465. }
  9466. if (i + 1 < parts.size()) {
  9467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9468. }
  9469. }
  9470. char buf[512];
  9471. int n;
  9472. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9473. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9474. }
  9475. return true;
  9476. }
  9477. #endif
  9478. // The request line, then a header value a byte at a time.
  9479. static std::vector<std::string> slow_request_head_parts() {
  9480. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9481. parts.resize(26, "a");
  9482. parts.emplace_back("\r\n\r\n");
  9483. return parts;
  9484. }
  9485. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9486. // within the one-second read timeout. The server gives up a second in, before
  9487. // the head is complete.
  9488. static void
  9489. expect_slow_request_head_dropped(Server &svr,
  9490. const std::function<std::string()> &send) {
  9491. std::atomic<bool> handled(false);
  9492. svr.Get("/", [&](const Request &, Response &res) {
  9493. handled = true;
  9494. res.set_content("ok", "text/plain");
  9495. });
  9496. svr.set_read_timeout(1, 0);
  9497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9498. auto se = detail::scope_exit([&] {
  9499. svr.stop();
  9500. t.join();
  9501. ASSERT_FALSE(svr.is_running());
  9502. });
  9503. svr.wait_until_ready();
  9504. auto resp = send();
  9505. EXPECT_FALSE(handled);
  9506. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9507. }
  9508. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9509. Server svr;
  9510. expect_slow_request_head_dropped(svr, [] {
  9511. std::string resp;
  9512. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9513. return resp;
  9514. });
  9515. }
  9516. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9517. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9519. ASSERT_TRUE(svr.is_valid());
  9520. expect_slow_request_head_dropped(svr, [] {
  9521. std::string resp;
  9522. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9523. return resp;
  9524. });
  9525. }
  9526. #endif
  9527. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9528. Server svr;
  9529. std::string header_value;
  9530. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9531. header_value = req.get_header_value("foo");
  9532. res.set_content("ok", "text/plain");
  9533. });
  9534. thread t = thread([&] { svr.listen(HOST, PORT); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9542. // like characters are not treated the same - use vertical tab and escape.
  9543. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9544. "foo: \t \v bar \x1B\t \r\n"
  9545. "Connection: close\r\n"
  9546. "\r\n";
  9547. std::string res;
  9548. ASSERT_TRUE(send_request(5, req, &res));
  9549. EXPECT_EQ(header_value, "");
  9550. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9551. }
  9552. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9553. Server svr;
  9554. std::string received;
  9555. svr.Get("/order", [&](const Request &req, Response &res) {
  9556. received = entries_to_string(req.headers);
  9557. res.set_content("ok", "text/plain");
  9558. });
  9559. auto port = svr.bind_to_any_port(HOST);
  9560. thread t = thread([&] { svr.listen_after_bind(); });
  9561. auto se = detail::scope_exit([&] {
  9562. svr.stop();
  9563. t.join();
  9564. ASSERT_FALSE(svr.is_running());
  9565. });
  9566. svr.wait_until_ready();
  9567. const std::string req = "GET /order HTTP/1.1\r\n"
  9568. "Host: localhost\r\n"
  9569. "X-First: 1\r\n"
  9570. "X-Dup: a\r\n"
  9571. "X-Second: 2\r\n"
  9572. "X-Dup: b\r\n"
  9573. "Connection: close\r\n"
  9574. "\r\n";
  9575. std::string res;
  9576. ASSERT_TRUE(send_request(5, req, &res, port));
  9577. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9578. EXPECT_EQ(
  9579. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9580. received);
  9581. }
  9582. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9583. Server svr;
  9584. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9585. res.set_header("Set-Cookie", "first=1");
  9586. res.set_header("X-Between", "y");
  9587. res.set_header("Set-Cookie", "second=2");
  9588. res.set_content("ok", "text/plain");
  9589. });
  9590. auto port = svr.bind_to_any_port(HOST);
  9591. thread t = thread([&] { svr.listen_after_bind(); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. t.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. Client cli(HOST, port);
  9599. auto res = cli.Get("/cookies");
  9600. ASSERT_TRUE(res);
  9601. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9602. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9603. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9604. }
  9605. // A stream may send a byte at a time with a small extension on each chunk,
  9606. // however long it runs
  9607. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9608. Server svr;
  9609. svr.Post("/count", [](const Request &req, Response &res) {
  9610. res.set_content(std::to_string(req.body.size()), "text/plain");
  9611. });
  9612. auto port = svr.bind_to_any_port(HOST);
  9613. ASSERT_LT(0, port);
  9614. thread t = thread([&] { svr.listen_after_bind(); });
  9615. auto se = detail::scope_exit([&] {
  9616. svr.stop();
  9617. t.join();
  9618. ASSERT_FALSE(svr.is_running());
  9619. });
  9620. svr.wait_until_ready();
  9621. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9622. "\r\nTransfer-Encoding: chunked\r\n"
  9623. "Connection: close\r\n\r\n";
  9624. for (auto i = 0; i < 4096; i++) {
  9625. req += "1;a=b\r\nx\r\n";
  9626. }
  9627. req += "0\r\n\r\n";
  9628. std::string res;
  9629. ASSERT_TRUE(send_request(5, req, &res, port));
  9630. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9631. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9632. }
  9633. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9634. Server svr;
  9635. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9636. auto i = new int(0);
  9637. res.set_header("Trailer", "X-Safe, X-Reflected");
  9638. res.set_chunked_content_provider(
  9639. "text/plain",
  9640. [i](size_t /*offset*/, DataSink &sink) {
  9641. if (*i == 0) {
  9642. sink.os << "body";
  9643. } else {
  9644. Headers trailer;
  9645. // A valid trailer that must survive.
  9646. trailer.emplace("X-Safe", "safe");
  9647. // Attacker-controlled value carrying CR/LF (response splitting).
  9648. trailer.emplace("X-Reflected",
  9649. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9650. // Attacker-controlled name carrying CR/LF.
  9651. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9652. sink.done_with_trailer(trailer);
  9653. }
  9654. (*i)++;
  9655. return true;
  9656. },
  9657. [i](bool /*success*/) { delete i; });
  9658. });
  9659. thread t = thread([&] { svr.listen(HOST, PORT); });
  9660. auto se = detail::scope_exit([&] {
  9661. svr.stop();
  9662. t.join();
  9663. ASSERT_FALSE(svr.is_running());
  9664. });
  9665. svr.wait_until_ready();
  9666. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9667. "Host: " + HOST +
  9668. "\r\n"
  9669. "Connection: close\r\n"
  9670. "\r\n";
  9671. std::string res;
  9672. ASSERT_TRUE(send_request(5, req, &res));
  9673. // The injected fields must not appear anywhere in the raw response.
  9674. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9675. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9676. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9677. // Invalid trailers are dropped entirely, matching set_header().
  9678. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9679. // The valid trailer still passes through.
  9680. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9681. }
  9682. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9683. // A custom header writer gets only the fields the default one writes
  9684. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9685. std::string s;
  9686. for (const auto &h : hdrs) {
  9687. s += h.first + ": " + h.second + "\r\n";
  9688. }
  9689. s += "\r\n";
  9690. return strm.write(s.data(), s.size());
  9691. };
  9692. for (auto custom_writer : {false, true}) {
  9693. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9694. Server svr;
  9695. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9696. svr.set_post_routing_handler([](const Request &, Response &res) {
  9697. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9698. });
  9699. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9700. // res.headers is a public field an application can populate directly,
  9701. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9702. // A valid header that must survive.
  9703. res.headers.emplace("X-Safe", "safe");
  9704. // Attacker-controlled value carrying CR/LF (response splitting).
  9705. res.headers.emplace("X-Reflected",
  9706. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9707. // Attacker-controlled name carrying CR/LF.
  9708. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9709. res.set_content("body", "text/plain");
  9710. });
  9711. thread t = thread([&] { svr.listen(HOST, PORT); });
  9712. auto se = detail::scope_exit([&] {
  9713. svr.stop();
  9714. t.join();
  9715. ASSERT_FALSE(svr.is_running());
  9716. });
  9717. svr.wait_until_ready();
  9718. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9719. "Host: " + HOST +
  9720. "\r\n"
  9721. "Connection: close\r\n"
  9722. "\r\n";
  9723. std::string res;
  9724. ASSERT_TRUE(send_request(5, req, &res));
  9725. // The injected fields must not appear anywhere in the raw response.
  9726. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9727. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9728. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9729. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9730. // Invalid headers are dropped entirely, matching set_header().
  9731. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9732. // The valid header still passes through.
  9733. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9734. }
  9735. }
  9736. // Forward declaration: in split builds split.py strips `inline` and moves the
  9737. // definition into httplib.cc, so detail::write_request_line is not visible from
  9738. // the public httplib.h. Re-declaring it here lets the tests link against the
  9739. // symbol in both header-only and split builds.
  9740. namespace httplib {
  9741. namespace detail {
  9742. ssize_t write_request_line(Stream &strm, const std::string &method,
  9743. const std::string &path);
  9744. } // namespace detail
  9745. } // namespace httplib
  9746. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9747. // A well-formed target is written verbatim.
  9748. {
  9749. detail::BufferStream strm;
  9750. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9751. EXPECT_GT(n, 0);
  9752. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9753. }
  9754. // A target carrying CR/LF, SP or other control octets must be rejected
  9755. // before anything reaches the wire, otherwise it splits the request line and
  9756. // injects a header or a whole request.
  9757. const std::string evil_targets[] = {
  9758. "/a\r\nInjected: pwned",
  9759. "/a\rInjected",
  9760. "/a\nInjected",
  9761. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9762. "/a b",
  9763. "/a\tb",
  9764. "/a\x7f",
  9765. };
  9766. for (const auto &evil : evil_targets) {
  9767. detail::BufferStream strm;
  9768. auto n = detail::write_request_line(strm, "GET", evil);
  9769. EXPECT_LT(n, 0);
  9770. EXPECT_TRUE(strm.get_buffer().empty());
  9771. }
  9772. }
  9773. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9774. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9775. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9776. // target reaches write_request. The client must fail cleanly with
  9777. // Error::Write instead of putting a request-line-less, header-injecting
  9778. // request on the wire.
  9779. Server svr;
  9780. svr.Get("/a", [](const Request &, Response &res) {
  9781. res.set_content("ok", "text/plain");
  9782. });
  9783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9784. auto se = detail::scope_exit([&] {
  9785. svr.stop();
  9786. thread.join();
  9787. ASSERT_FALSE(svr.is_running());
  9788. });
  9789. svr.wait_until_ready();
  9790. {
  9791. Client cli(HOST, PORT);
  9792. cli.set_path_encode(false);
  9793. // The request is rejected before anything is written, so the connection
  9794. // stays silent and the subsequent response read would otherwise block for
  9795. // the full default read timeout. Shorten it -- the assertion is on the
  9796. // error, not the timeout.
  9797. cli.set_read_timeout(1, 0);
  9798. auto res = cli.Get("/a\r\nInjected: pwned");
  9799. EXPECT_FALSE(res);
  9800. EXPECT_EQ(Error::Write, res.error());
  9801. }
  9802. }
  9803. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9804. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9805. // including extension methods.
  9806. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9807. for (const auto &method : good_methods) {
  9808. detail::BufferStream strm;
  9809. auto n = detail::write_request_line(strm, method, "/");
  9810. EXPECT_GT(n, 0);
  9811. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9812. }
  9813. // A method carrying CR/LF would split the request line and smuggle a whole
  9814. // request ahead of the real one. A space or an empty method corrupts the
  9815. // request line. All must be rejected before anything reaches the wire.
  9816. const std::string evil_methods[] = {
  9817. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9818. "GET\r\nInjected: pwned",
  9819. "GET\r",
  9820. "GET\n",
  9821. "GE T",
  9822. "",
  9823. };
  9824. for (const auto &evil : evil_methods) {
  9825. detail::BufferStream strm;
  9826. auto n = detail::write_request_line(strm, evil, "/");
  9827. EXPECT_LT(n, 0);
  9828. EXPECT_TRUE(strm.get_buffer().empty());
  9829. }
  9830. }
  9831. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9832. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9833. // through Client::send must fail with Error::Write and no request, neither
  9834. // the smuggled one nor the real one, may reach the server.
  9835. Server svr;
  9836. std::atomic<int> request_count(0);
  9837. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9838. request_count++;
  9839. res.status = StatusCode::OK_200;
  9840. return Server::HandlerResponse::Handled;
  9841. });
  9842. auto port = svr.bind_to_any_port(HOST);
  9843. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9844. auto se = detail::scope_exit([&] {
  9845. svr.stop();
  9846. thread.join();
  9847. ASSERT_FALSE(svr.is_running());
  9848. });
  9849. svr.wait_until_ready();
  9850. {
  9851. Client cli(HOST, port);
  9852. const std::string evil_methods[] = {
  9853. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9854. "GE T",
  9855. "",
  9856. };
  9857. for (const auto &evil : evil_methods) {
  9858. Request req;
  9859. req.method = evil;
  9860. req.path = "/";
  9861. auto res = cli.send(req);
  9862. EXPECT_FALSE(res);
  9863. EXPECT_EQ(Error::Write, res.error());
  9864. }
  9865. auto handle =
  9866. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9867. EXPECT_FALSE(handle.is_valid());
  9868. EXPECT_EQ(Error::Write, handle.error);
  9869. // A valid request on the same client still goes through.
  9870. auto res = cli.Get("/");
  9871. ASSERT_TRUE(res);
  9872. EXPECT_EQ(StatusCode::OK_200, res->status);
  9873. }
  9874. EXPECT_EQ(1, request_count.load());
  9875. }
  9876. // Sends a raw request and verifies that there isn't a crash or exception.
  9877. static void test_raw_request(const std::string &req,
  9878. std::string *out = nullptr) {
  9879. Server svr;
  9880. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9881. res.set_content("ok", "text/plain");
  9882. });
  9883. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9884. res.set_content("ok", "text/plain");
  9885. });
  9886. svr.Get("/header_field_value_check",
  9887. [&](const Request & /*req*/, Response &res) {
  9888. res.set_content("ok", "text/plain");
  9889. });
  9890. svr.CustomRoute("PROPFIND", "/dav",
  9891. [&](const Request & /*req*/, Response &res) {
  9892. res.status = StatusCode::MultiStatus_207;
  9893. });
  9894. // Server read timeout must be longer than the client read timeout for the
  9895. // bug to reproduce, probably to force the server to process a request
  9896. // without a trailing blank line.
  9897. const time_t client_read_timeout_sec = 1;
  9898. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9899. bool listen_thread_ok = false;
  9900. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9901. auto se = detail::scope_exit([&] {
  9902. svr.stop();
  9903. t.join();
  9904. ASSERT_FALSE(svr.is_running());
  9905. EXPECT_TRUE(listen_thread_ok);
  9906. });
  9907. svr.wait_until_ready();
  9908. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9909. }
  9910. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9911. // A certain header line causes an exception if the header property is parsed
  9912. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9913. test_raw_request(
  9914. "GET /hi HTTP/1.1\r\n"
  9915. " : "
  9916. " "
  9917. " ");
  9918. }
  9919. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9920. // A certain header line causes an exception if the header property *name* is
  9921. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9922. // greedy matcher and requires backtracking when there are a lot of ":"
  9923. // characters.
  9924. // This occurs with libc++ but not libstdc++.
  9925. test_raw_request(
  9926. "GET /hi HTTP/1.1\r\n"
  9927. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9928. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9929. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9930. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9931. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9932. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9933. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9934. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9935. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9936. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9937. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9938. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9939. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9940. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9941. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9942. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9943. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9944. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9945. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9946. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9947. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9948. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9949. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9950. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9951. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9952. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9953. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9954. "&&&%%%");
  9955. }
  9956. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9957. // Make sure this doesn't crash the server.
  9958. // In a previous version of the header line regex, the "\r" rendered the line
  9959. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9960. // a new position where the leading white space ended and the field value
  9961. // began.
  9962. // The crash occurs with libc++ but not libstdc++.
  9963. test_raw_request("GET /hi HTTP/1.1\r\n"
  9964. "a:" +
  9965. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9966. "\r\n"
  9967. "\r\n");
  9968. }
  9969. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9970. const char *rejected[] = {
  9971. // RFC 9112 §3: one SP between the parts, and nothing else
  9972. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9973. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9974. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9975. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9976. // A request-target has no fragment
  9977. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9978. // An HTTP/1.1 request needs a Host
  9979. "GET /hi HTTP/1.1\r\n\r\n",
  9980. };
  9981. for (auto request : rejected) {
  9982. std::string out;
  9983. test_raw_request(request, &out);
  9984. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9985. }
  9986. std::string out;
  9987. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9988. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9989. }
  9990. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9991. // RFC 9112 §6.1
  9992. const char *requests[] = {
  9993. "PUT /put_hi HTTP/1.1\r\n"
  9994. "Host: localhost\r\n"
  9995. "Content-Length: 0\r\n"
  9996. "Transfer-Encoding: chunked\r\n"
  9997. "\r\n"
  9998. "0\r\n\r\n",
  9999. "PUT /put_hi HTTP/1.0\r\n"
  10000. "Connection: keep-alive\r\n"
  10001. "Transfer-Encoding: chunked\r\n"
  10002. "\r\n"
  10003. "0\r\n\r\n",
  10004. };
  10005. for (auto request : requests) {
  10006. std::string out;
  10007. test_raw_request(request, &out);
  10008. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10009. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10010. }
  10011. }
  10012. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10013. std::string out;
  10014. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10015. "Content-Type: text/plain\r\n"
  10016. "Transfer-Encoding: chunked\r\n"
  10017. "\r\n"
  10018. "nothex\r\n",
  10019. &out);
  10020. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10021. }
  10022. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10023. std::string out;
  10024. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10025. "Content-Type: text/plain\r\n"
  10026. "Transfer-Encoding: chunked\r\n"
  10027. "\r\n"
  10028. "3\r\n"
  10029. "xyz\r\n"
  10030. "NaN\r\n",
  10031. &out);
  10032. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10033. }
  10034. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10035. std::string out;
  10036. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10037. "Content-Type: text/plain\r\n"
  10038. "Transfer-Encoding: chunked\r\n"
  10039. "\r\n"
  10040. // Length is too large for 64 bits.
  10041. "1ffffffffffffffff\r\n"
  10042. "xyz\r\n",
  10043. &out);
  10044. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10045. }
  10046. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10047. test_raw_request("GET /hi HTTP/1.1\r\n"
  10048. "Content-Type: text/plain\r\n\r");
  10049. }
  10050. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10051. std::string out;
  10052. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10054. }
  10055. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10056. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10057. std::string out;
  10058. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10060. }
  10061. }
  10062. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10063. std::string out;
  10064. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10065. "Host: localhost\r\n"
  10066. "Connection: close\r\n\r\n",
  10067. &out);
  10068. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10069. }
  10070. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10071. Server svr;
  10072. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10073. EXPECT_TRUE(!req.remote_addr.empty());
  10074. });
  10075. thread t = thread([&] { svr.listen(HOST, PORT); });
  10076. auto se = detail::scope_exit([&] {
  10077. svr.stop();
  10078. t.join();
  10079. ASSERT_FALSE(svr.is_running());
  10080. });
  10081. svr.wait_until_ready();
  10082. // Send an invalid request line to trigger Bad Request
  10083. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10084. std::string out;
  10085. ASSERT_TRUE(send_request(5, bad_req, &out));
  10086. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10087. }
  10088. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10089. // answered right away rather than blocking on a read that waits for EOF.
  10090. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10091. std::string out;
  10092. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10093. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10094. }
  10095. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10096. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10097. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10098. for (const auto *method : methods) {
  10099. Server svr;
  10100. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10101. EXPECT_FALSE(svr.is_valid()) << method;
  10102. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10103. }
  10104. }
  10105. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10106. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10107. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10108. for (const auto *method : methods) {
  10109. Server svr;
  10110. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10111. EXPECT_FALSE(svr.is_valid()) << method;
  10112. }
  10113. }
  10114. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10115. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10116. "COPY", "MOVE", "LOCK",
  10117. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10118. Server svr;
  10119. for (const auto *method : methods) {
  10120. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10121. }
  10122. EXPECT_TRUE(svr.is_valid());
  10123. }
  10124. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10125. Server svr;
  10126. svr.CustomRoute("POST", "/x",
  10127. [](const Request &, Response &, const ContentReader &) {});
  10128. EXPECT_FALSE(svr.is_valid());
  10129. }
  10130. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10131. Server svr;
  10132. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10133. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10134. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10135. EXPECT_FALSE(svr.is_valid());
  10136. }
  10137. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10138. Server svr;
  10139. auto captured = Error::Success;
  10140. svr.set_error_logger(
  10141. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10142. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10143. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10144. }
  10145. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10146. std::string out;
  10147. std::string request(
  10148. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10149. test_raw_request(request, &out);
  10150. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10151. }
  10152. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10153. std::string out;
  10154. std::string request(
  10155. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10156. test_raw_request(request, &out);
  10157. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10158. }
  10159. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10160. std::string out;
  10161. std::string request(
  10162. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10163. test_raw_request(request, &out);
  10164. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10165. }
  10166. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10167. std::string out;
  10168. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10169. "Host: localhost\r\n"
  10170. "Test: \r\n\r\n",
  10171. &out);
  10172. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10173. }
  10174. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10175. Server svr;
  10176. std::string x_custom;
  10177. std::string cookie;
  10178. std::string xff;
  10179. std::string x_unicode;
  10180. std::string x_iis;
  10181. svr.Get("/check", [&](const Request &req, Response &res) {
  10182. x_custom = req.get_header_value("X-Custom");
  10183. cookie = req.get_header_value("Cookie");
  10184. xff = req.get_header_value("X-Forwarded-For");
  10185. x_unicode = req.get_header_value("X-Unicode");
  10186. x_iis = req.get_header_value("X-IIS");
  10187. res.set_content("ok", "text/plain");
  10188. });
  10189. thread t = thread([&] { svr.listen(HOST, PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. t.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. const std::string req = "GET /check HTTP/1.1\r\n"
  10197. "Host: localhost\r\n"
  10198. "X-Custom: a%0D%0AInjected: b\r\n"
  10199. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10200. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10201. "X-Unicode: %E3%81%82\r\n"
  10202. "X-IIS: %u00E9\r\n"
  10203. "Connection: close\r\n"
  10204. "\r\n";
  10205. std::string res;
  10206. ASSERT_TRUE(send_request(5, req, &res));
  10207. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10208. // Every value must be returned verbatim (wire form), with no decoding.
  10209. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10210. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10211. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10212. EXPECT_EQ("%E3%81%82", x_unicode);
  10213. EXPECT_EQ("%u00E9", x_iis);
  10214. }
  10215. // Applications that previously relied on automatic percent-decoding can
  10216. // reproduce the old behavior by explicitly calling decode_path_component()
  10217. // or, for RFC 3986 conformance, decode_uri_component().
  10218. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10219. Server svr;
  10220. std::string decoded;
  10221. svr.Get("/check", [&](const Request &req, Response &res) {
  10222. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10223. res.set_content("ok", "text/plain");
  10224. });
  10225. thread t = thread([&] { svr.listen(HOST, PORT); });
  10226. auto se = detail::scope_exit([&] {
  10227. svr.stop();
  10228. t.join();
  10229. ASSERT_FALSE(svr.is_running());
  10230. });
  10231. svr.wait_until_ready();
  10232. const std::string req = "GET /check HTTP/1.1\r\n"
  10233. "Host: localhost\r\n"
  10234. "X-Custom: hello%20world\r\n"
  10235. "Connection: close\r\n"
  10236. "\r\n";
  10237. std::string res;
  10238. ASSERT_TRUE(send_request(5, req, &res));
  10239. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10240. EXPECT_EQ("hello world", decoded);
  10241. }
  10242. // Regression test for #2033. Browsers send Referer values that include
  10243. // percent-encoded characters such as %0A inside the URL. Decoding the
  10244. // header value would either trip the post-decode CR/LF/NUL guard (the
  10245. // original bug, returning 400) or, after that guard was relaxed, silently
  10246. // store a literal LF — both unacceptable. The wire form must round-trip.
  10247. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10248. Server svr;
  10249. std::string referer;
  10250. svr.Get("/check", [&](const Request &req, Response &res) {
  10251. referer = req.get_header_value("Referer");
  10252. res.set_content("ok", "text/plain");
  10253. });
  10254. thread t = thread([&] { svr.listen(HOST, PORT); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. t.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. const std::string req = "GET /check HTTP/1.1\r\n"
  10262. "Host: localhost\r\n"
  10263. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10264. "Connection: close\r\n"
  10265. "\r\n";
  10266. std::string res;
  10267. ASSERT_TRUE(send_request(5, req, &res));
  10268. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10269. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10270. }
  10271. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10272. Server svr;
  10273. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10274. res.set_header("Cache-Control", "no-cache");
  10275. res.set_chunked_content_provider(
  10276. "text/event-stream", [](size_t offset, DataSink &sink) {
  10277. std::string s = "data:";
  10278. s += std::to_string(offset);
  10279. s += "\n\n";
  10280. auto ret = sink.write(s.data(), s.size());
  10281. EXPECT_TRUE(ret);
  10282. std::this_thread::sleep_for(std::chrono::seconds(1));
  10283. return true;
  10284. });
  10285. });
  10286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10287. svr.wait_until_ready();
  10288. Client client(HOST, PORT);
  10289. const Headers headers = {{"Accept", "text/event-stream"}};
  10290. auto get_thread = std::thread([&client, &headers]() {
  10291. auto res = client.Get(
  10292. "/events", headers,
  10293. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10294. });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. get_thread.join();
  10298. listen_thread.join();
  10299. ASSERT_FALSE(svr.is_running());
  10300. });
  10301. // Give GET time to get a few messages.
  10302. std::this_thread::sleep_for(std::chrono::seconds(2));
  10303. }
  10304. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10305. httplib::Server svr;
  10306. svr.Post("/hi",
  10307. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10308. res.status = StatusCode::OK_200;
  10309. });
  10310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10311. svr.wait_until_ready();
  10312. Client cli(HOST, PORT);
  10313. auto res = cli.Post("/hi", "data", "text/plain");
  10314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10315. EXPECT_EQ(StatusCode::OK_200, res->status);
  10316. svr.stop();
  10317. thread.join();
  10318. ASSERT_FALSE(svr.is_running());
  10319. res = cli.Post("/hi", "data", "text/plain");
  10320. ASSERT_FALSE(res);
  10321. }
  10322. TEST(ServerStopTest, ListenFailure) {
  10323. Server svr;
  10324. auto t = thread([&]() {
  10325. auto ret = svr.listen("????", PORT);
  10326. EXPECT_FALSE(ret);
  10327. });
  10328. svr.wait_until_ready();
  10329. svr.stop();
  10330. t.join();
  10331. }
  10332. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10333. TEST(ServerStopTest, Decommision) {
  10334. Server svr;
  10335. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10336. for (int i = 0; i < 4; i++) {
  10337. auto is_even = !(i % 2);
  10338. std::thread t{[&] {
  10339. try {
  10340. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10341. if (is_even) {
  10342. throw std::runtime_error("Some thing that happens to go wrong.");
  10343. }
  10344. svr.listen(HOST, PORT);
  10345. } catch (...) { svr.decommission(); }
  10346. }};
  10347. svr.wait_until_ready();
  10348. // Server is up
  10349. {
  10350. Client cli(HOST, PORT);
  10351. auto res = cli.Get("/hi");
  10352. if (is_even) {
  10353. EXPECT_FALSE(res);
  10354. } else {
  10355. EXPECT_TRUE(res);
  10356. EXPECT_EQ("hi...", res->body);
  10357. }
  10358. }
  10359. svr.stop();
  10360. t.join();
  10361. // Server is down...
  10362. {
  10363. Client cli(HOST, PORT);
  10364. auto res = cli.Get("/hi");
  10365. EXPECT_FALSE(res);
  10366. }
  10367. }
  10368. }
  10369. #endif
  10370. // Helper function for string body upload progress tests
  10371. template <typename SetupHandler, typename ClientCall>
  10372. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10373. ClientCall &&client_call,
  10374. const string &body) {
  10375. Server svr;
  10376. setup_handler(svr);
  10377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. });
  10382. svr.wait_until_ready();
  10383. Client cli(HOST, PORT);
  10384. vector<uint64_t> progress_values;
  10385. bool progress_called = false;
  10386. auto res =
  10387. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10388. progress_values.push_back(current);
  10389. progress_called = true;
  10390. return true;
  10391. });
  10392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10393. EXPECT_EQ(200, res->status);
  10394. EXPECT_TRUE(progress_called);
  10395. }
  10396. TEST(UploadProgressTest, PostStringBodyBasic) {
  10397. TestStringBodyUploadProgress(
  10398. [](Server &svr) {
  10399. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10400. res.set_content("received", "text/plain");
  10401. });
  10402. },
  10403. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10404. return cli.Post("/test", body, "text/plain", progress_callback);
  10405. },
  10406. "test data for upload progress");
  10407. }
  10408. TEST(UploadProgressTest, PutStringBodyBasic) {
  10409. TestStringBodyUploadProgress(
  10410. [](Server &svr) {
  10411. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10412. res.set_content("put received", "text/plain");
  10413. });
  10414. },
  10415. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10416. return cli.Put("/test", body, "text/plain", progress_callback);
  10417. },
  10418. "put test data for upload progress");
  10419. }
  10420. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10421. TestStringBodyUploadProgress(
  10422. [](Server &svr) {
  10423. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10424. res.set_content("patch received", "text/plain");
  10425. });
  10426. },
  10427. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10428. return cli.Patch("/test", body, "text/plain", progress_callback);
  10429. },
  10430. "patch test data for upload progress");
  10431. }
  10432. // Helper function for content provider upload progress tests
  10433. template <typename SetupHandler, typename ClientCall>
  10434. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10435. ClientCall &&client_call) {
  10436. Server svr;
  10437. setup_handler(svr);
  10438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10439. auto se = detail::scope_exit([&] {
  10440. svr.stop();
  10441. t.join();
  10442. });
  10443. svr.wait_until_ready();
  10444. Client cli(HOST, PORT);
  10445. vector<uint64_t> progress_values;
  10446. auto res =
  10447. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10448. progress_values.push_back(current);
  10449. return true;
  10450. });
  10451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10452. EXPECT_EQ(200, res->status);
  10453. EXPECT_FALSE(progress_values.empty());
  10454. }
  10455. TEST(UploadProgressTest, PostContentProviderProgress) {
  10456. TestContentProviderUploadProgress(
  10457. [](Server &svr) {
  10458. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10459. res.set_content("provider received", "text/plain");
  10460. });
  10461. },
  10462. [](Client &cli, UploadProgress progress_callback) {
  10463. return cli.Post(
  10464. "/test", 9,
  10465. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10466. sink.os << "test data";
  10467. return true;
  10468. },
  10469. "text/plain", progress_callback);
  10470. });
  10471. }
  10472. // Helper function for multipart upload progress tests
  10473. template <typename SetupHandler, typename ClientCall>
  10474. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10475. ClientCall &&client_call,
  10476. const string &endpoint) {
  10477. Server svr;
  10478. setup_handler(svr);
  10479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10480. auto se = detail::scope_exit([&] {
  10481. svr.stop();
  10482. t.join();
  10483. });
  10484. svr.wait_until_ready();
  10485. Client cli(HOST, PORT);
  10486. vector<uint64_t> progress_values;
  10487. UploadFormDataItems items = {
  10488. {"field1", "value1", "", ""},
  10489. {"field2", "longer value for progress tracking test", "", ""},
  10490. {"file1", "file content data for upload progress", "test.txt",
  10491. "text/plain"}};
  10492. auto res = client_call(cli, endpoint, items,
  10493. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10494. progress_values.push_back(current);
  10495. return true;
  10496. });
  10497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10498. EXPECT_EQ(200, res->status);
  10499. EXPECT_FALSE(progress_values.empty());
  10500. }
  10501. TEST(UploadProgressTest, PostMultipartProgress) {
  10502. TestMultipartUploadProgress(
  10503. [](Server &svr) {
  10504. svr.Post("/multipart", [](const Request &req, Response &res) {
  10505. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10506. res.set_content("multipart received", "text/plain");
  10507. });
  10508. },
  10509. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10510. UploadProgress progress_callback) {
  10511. return cli.Post(endpoint, items, progress_callback);
  10512. },
  10513. "/multipart");
  10514. }
  10515. // Helper function for basic download progress tests
  10516. template <typename SetupHandler, typename ClientCall>
  10517. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10518. ClientCall &&client_call, const string &endpoint,
  10519. size_t expected_content_size) {
  10520. Server svr;
  10521. setup_handler(svr);
  10522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10523. auto se = detail::scope_exit([&] {
  10524. svr.stop();
  10525. t.join();
  10526. });
  10527. svr.wait_until_ready();
  10528. Client cli(HOST, PORT);
  10529. vector<uint64_t> progress_values;
  10530. auto res = client_call(cli, endpoint,
  10531. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10532. progress_values.push_back(current);
  10533. return true;
  10534. });
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(200, res->status);
  10537. EXPECT_FALSE(progress_values.empty());
  10538. EXPECT_EQ(expected_content_size, res->body.size());
  10539. }
  10540. TEST(DownloadProgressTest, GetBasic) {
  10541. TestBasicDownloadProgress(
  10542. [](Server &svr) {
  10543. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10544. string content(1000, 'D');
  10545. res.set_content(content, "text/plain");
  10546. });
  10547. },
  10548. [](Client &cli, const string &endpoint,
  10549. DownloadProgress progress_callback) {
  10550. return cli.Get(endpoint, progress_callback);
  10551. },
  10552. "/download", 1000u);
  10553. }
  10554. // Helper function for content receiver download progress tests
  10555. template <typename SetupHandler, typename ClientCall>
  10556. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10557. ClientCall &&client_call,
  10558. const string &endpoint,
  10559. size_t expected_content_size) {
  10560. Server svr;
  10561. setup_handler(svr);
  10562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. t.join();
  10566. });
  10567. svr.wait_until_ready();
  10568. Client cli(HOST, PORT);
  10569. vector<uint64_t> progress_values;
  10570. string received_body;
  10571. auto res = client_call(
  10572. cli, endpoint,
  10573. [&](const char *data, size_t data_length) -> bool {
  10574. received_body.append(data, data_length);
  10575. return true;
  10576. },
  10577. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10578. progress_values.push_back(current);
  10579. return true;
  10580. });
  10581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10582. EXPECT_EQ(200, res->status);
  10583. EXPECT_FALSE(progress_values.empty());
  10584. EXPECT_EQ(expected_content_size, received_body.size());
  10585. EXPECT_TRUE(res->body.empty());
  10586. }
  10587. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10588. TestContentReceiverDownloadProgress(
  10589. [](Server &svr) {
  10590. svr.Get("/download-receiver",
  10591. [](const Request & /*req*/, Response &res) {
  10592. string content(2000, 'R');
  10593. res.set_content(content, "text/plain");
  10594. });
  10595. },
  10596. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10597. DownloadProgress progress_callback) {
  10598. return cli.Get(endpoint, content_receiver, progress_callback);
  10599. },
  10600. "/download-receiver", 2000u);
  10601. }
  10602. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10603. // A provider reaching a pass with nothing to hand over - an empty buffer
  10604. // popped off a queue, say - must not be taken to mean the body is finished.
  10605. // It used to end the loop with the terminating chunk unwritten while the
  10606. // server still considered the response complete, so the peer waited for an
  10607. // end that never arrived.
  10608. Server svr;
  10609. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10610. auto step = std::make_shared<int>(0);
  10611. res.set_chunked_content_provider("text/plain",
  10612. [step](size_t /*offset*/, DataSink &sink) {
  10613. switch ((*step)++) {
  10614. case 0: sink.write("", 0); break;
  10615. case 1: sink.write("hello", 5); break;
  10616. default: sink.done(); break;
  10617. }
  10618. return true;
  10619. });
  10620. });
  10621. auto port = svr.bind_to_any_port(HOST);
  10622. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10623. auto listen_se = detail::scope_exit([&] {
  10624. svr.stop();
  10625. listen_thread.join();
  10626. ASSERT_FALSE(svr.is_running());
  10627. });
  10628. svr.wait_until_ready();
  10629. Client cli(HOST, port);
  10630. // Without the fix the body is never terminated, so bound the wait rather
  10631. // than letting the test hang on the default read timeout.
  10632. cli.set_read_timeout(5, 0);
  10633. auto res = cli.Get("/stream");
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::OK_200, res->status);
  10636. EXPECT_EQ("hello", res->body);
  10637. }
  10638. TEST(StreamingTest, NoContentLengthStreaming) {
  10639. Server svr;
  10640. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10641. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10642. if (offset < 6) {
  10643. sink.os << (offset < 3 ? "a" : "b");
  10644. } else {
  10645. sink.done();
  10646. }
  10647. return true;
  10648. });
  10649. });
  10650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10651. auto listen_se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. listen_thread.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client client(HOST, PORT);
  10658. auto get_thread = std::thread([&client]() {
  10659. std::string s;
  10660. auto res =
  10661. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10662. s += std::string(data, len);
  10663. return true;
  10664. });
  10665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10666. EXPECT_EQ(StatusCode::OK_200, res->status);
  10667. EXPECT_EQ("aaabbb", s);
  10668. });
  10669. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10670. // Give GET time to get a few messages.
  10671. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10672. }
  10673. TEST(MountTest, Unmount) {
  10674. Server svr;
  10675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. listen_thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli("localhost", PORT);
  10683. svr.set_mount_point("/mount2", "./www2");
  10684. auto res = cli.Get("/");
  10685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10687. res = cli.Get("/mount2/dir/test.html");
  10688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10689. EXPECT_EQ(StatusCode::OK_200, res->status);
  10690. svr.set_mount_point("/", "./www");
  10691. res = cli.Get("/dir/");
  10692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10693. EXPECT_EQ(StatusCode::OK_200, res->status);
  10694. svr.remove_mount_point("/");
  10695. res = cli.Get("/dir/");
  10696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10698. svr.remove_mount_point("/mount2");
  10699. res = cli.Get("/mount2/dir/test.html");
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10702. }
  10703. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10704. Server svr;
  10705. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10706. svr.Get("/api/hello", [](const Request &, Response &res) {
  10707. res.set_content("api", "text/plain");
  10708. });
  10709. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. listen_thread.join();
  10713. ASSERT_FALSE(svr.is_running());
  10714. });
  10715. svr.wait_until_ready();
  10716. Client cli(HOST, PORT);
  10717. auto res = cli.Get("/dir/test.html");
  10718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10719. EXPECT_EQ(StatusCode::OK_200, res->status);
  10720. res = cli.Get("/api/hello");
  10721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10722. EXPECT_EQ(StatusCode::OK_200, res->status);
  10723. EXPECT_EQ("api", res->body);
  10724. }
  10725. TEST(MountTest, PathSegmentBoundary) {
  10726. Server svr;
  10727. svr.set_mount_point("/mount2", "./www2");
  10728. svr.set_mount_point("/", "./www");
  10729. auto port = svr.bind_to_any_port(HOST);
  10730. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10731. auto se = detail::scope_exit([&] {
  10732. svr.stop();
  10733. listen_thread.join();
  10734. ASSERT_FALSE(svr.is_running());
  10735. });
  10736. svr.wait_until_ready();
  10737. Client cli(HOST, port);
  10738. auto res = cli.Get("/mount2/dir/test.html");
  10739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10740. EXPECT_EQ(StatusCode::OK_200, res->status);
  10741. // "/mount2" must not match part-way through a path segment.
  10742. res = cli.Get("/mount2dir/test.html");
  10743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10745. // A mount point ending in '/' keeps matching every path below it.
  10746. res = cli.Get("/dir/test.html");
  10747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10748. EXPECT_EQ(StatusCode::OK_200, res->status);
  10749. }
  10750. TEST(MountTest, Redicect) {
  10751. Server svr;
  10752. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10753. auto se = detail::scope_exit([&] {
  10754. svr.stop();
  10755. listen_thread.join();
  10756. ASSERT_FALSE(svr.is_running());
  10757. });
  10758. svr.set_mount_point("/", "./www");
  10759. svr.wait_until_ready();
  10760. Client cli("localhost", PORT);
  10761. auto res = cli.Get("/dir/");
  10762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10763. EXPECT_EQ(StatusCode::OK_200, res->status);
  10764. res = cli.Get("/dir");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10767. res = cli.Get("/file");
  10768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10769. EXPECT_EQ(StatusCode::OK_200, res->status);
  10770. res = cli.Get("/file/");
  10771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10773. cli.set_follow_location(true);
  10774. res = cli.Get("/dir");
  10775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10776. EXPECT_EQ(StatusCode::OK_200, res->status);
  10777. }
  10778. TEST(MountTest, MultibytesPathName) {
  10779. Server svr;
  10780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10781. auto se = detail::scope_exit([&] {
  10782. svr.stop();
  10783. listen_thread.join();
  10784. ASSERT_FALSE(svr.is_running());
  10785. });
  10786. svr.set_mount_point("/", "./www");
  10787. svr.wait_until_ready();
  10788. Client cli("localhost", PORT);
  10789. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10791. EXPECT_EQ(StatusCode::OK_200, res->status);
  10792. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10793. }
  10794. // A mount point serves no path with an empty segment or one ending in '.' or
  10795. // a space, so a guard in the pre-routing handler sees the path of every file
  10796. // that is served
  10797. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10798. Server svr;
  10799. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10800. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10801. if (req.path == "/dir/test.html") {
  10802. res.status = StatusCode::Unauthorized_401;
  10803. return Server::HandlerResponse::Handled;
  10804. }
  10805. return Server::HandlerResponse::Unhandled;
  10806. });
  10807. auto port = svr.bind_to_any_port(HOST);
  10808. ASSERT_LT(0, port);
  10809. thread t = thread([&] { svr.listen_after_bind(); });
  10810. auto se = detail::scope_exit([&] {
  10811. svr.stop();
  10812. t.join();
  10813. ASSERT_FALSE(svr.is_running());
  10814. });
  10815. svr.wait_until_ready();
  10816. Client cli(HOST, port);
  10817. for (auto path :
  10818. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10819. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10820. "/dir/test.html.", "/dir/test.html%20"}) {
  10821. SCOPED_TRACE(path);
  10822. auto res = cli.Get(path);
  10823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10825. }
  10826. }
  10827. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10828. Server svr;
  10829. svr.set_mount_point("/", "./www");
  10830. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10831. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10832. auto port = svr.bind_to_any_port(HOST);
  10833. ASSERT_GT(port, 0);
  10834. thread t = thread([&] { svr.listen_after_bind(); });
  10835. auto se = detail::scope_exit([&] {
  10836. svr.stop();
  10837. t.join();
  10838. ASSERT_FALSE(svr.is_running());
  10839. });
  10840. svr.wait_until_ready();
  10841. Client cli(HOST, port);
  10842. auto res = cli.Get("/dir/test.abcde");
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10845. res = cli.Get("/dir/test.html");
  10846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10847. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10848. }
  10849. #ifdef _WIN32
  10850. // Issue #2435: mmap::open() must succeed even when another handle holds
  10851. // the file open for writing (e.g. an active log file).
  10852. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10853. const char *path = "mmap_concurrent_writer_test.txt";
  10854. const char *content = "hello";
  10855. {
  10856. std::ofstream f(path, std::ios::binary);
  10857. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10858. }
  10859. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10860. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10861. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10862. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10863. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10864. detail::mmap m(path);
  10865. ASSERT_TRUE(m.is_open());
  10866. EXPECT_EQ(strlen(content), m.size());
  10867. char buf[8];
  10868. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10869. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10870. }
  10871. #endif
  10872. #ifndef _WIN32
  10873. // A directory or a device has no size to serve.
  10874. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10875. const char *path = "./mmap_not_regular_test_dir";
  10876. ASSERT_EQ(0, ::mkdir(path, 0755));
  10877. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10878. for (auto p : {path, "/dev/null"}) {
  10879. detail::mmap m(p);
  10880. EXPECT_FALSE(m.is_open()) << p;
  10881. EXPECT_EQ(0U, m.size()) << p;
  10882. }
  10883. Server svr;
  10884. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10885. res.set_file_content("/dev/null");
  10886. });
  10887. auto port = svr.bind_to_any_port(HOST);
  10888. thread t = thread([&] { svr.listen_after_bind(); });
  10889. auto se = detail::scope_exit([&] {
  10890. svr.stop();
  10891. t.join();
  10892. });
  10893. svr.wait_until_ready();
  10894. auto res = Client(HOST, port).Get("/null");
  10895. ASSERT_TRUE(res);
  10896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10897. }
  10898. #endif
  10899. #ifdef __linux__
  10900. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10901. TEST(MmapTest, FileIsNotMapped) {
  10902. const char *path = "mmap_not_mapped_test.txt";
  10903. {
  10904. std::ofstream f(path, std::ios::binary);
  10905. f << "hello";
  10906. }
  10907. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10908. detail::mmap m(path);
  10909. ASSERT_TRUE(m.is_open());
  10910. std::ifstream maps("/proc/self/maps");
  10911. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10912. std::istreambuf_iterator<char>());
  10913. EXPECT_EQ(std::string::npos, mappings.find(path));
  10914. }
  10915. #endif
  10916. TEST(KeepAliveTest, ReadTimeout) {
  10917. Server svr;
  10918. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10919. std::this_thread::sleep_for(std::chrono::seconds(2));
  10920. res.set_content("a", "text/plain");
  10921. });
  10922. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10923. res.set_content("b", "text/plain");
  10924. });
  10925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10926. auto se = detail::scope_exit([&] {
  10927. svr.stop();
  10928. listen_thread.join();
  10929. ASSERT_FALSE(svr.is_running());
  10930. });
  10931. svr.wait_until_ready();
  10932. Client cli("localhost", PORT);
  10933. cli.set_keep_alive(true);
  10934. cli.set_read_timeout(std::chrono::seconds(1));
  10935. auto resa = cli.Get("/a");
  10936. ASSERT_FALSE(resa);
  10937. EXPECT_EQ(Error::Read, resa.error());
  10938. auto resb = cli.Get("/b");
  10939. ASSERT_TRUE(resb);
  10940. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10941. EXPECT_EQ("b", resb->body);
  10942. }
  10943. TEST(KeepAliveTest, MaxCount) {
  10944. size_t keep_alive_max_count = 3;
  10945. Server svr;
  10946. svr.set_keep_alive_max_count(keep_alive_max_count);
  10947. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10948. res.set_content("Hello World!", "text/plain");
  10949. });
  10950. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10951. auto se = detail::scope_exit([&] {
  10952. svr.stop();
  10953. listen_thread.join();
  10954. ASSERT_FALSE(svr.is_running());
  10955. });
  10956. svr.wait_until_ready();
  10957. Client cli(HOST, PORT);
  10958. cli.set_keep_alive(true);
  10959. for (size_t i = 0; i < 5; i++) {
  10960. auto result = cli.Get("/hi");
  10961. ASSERT_TRUE(result);
  10962. EXPECT_EQ(StatusCode::OK_200, result->status);
  10963. if (i == keep_alive_max_count - 1) {
  10964. EXPECT_EQ("close", result->get_header_value("Connection"));
  10965. } else {
  10966. EXPECT_FALSE(result->has_header("Connection"));
  10967. }
  10968. }
  10969. }
  10970. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10971. // can pull the next one into the server's buffer. The server must serve it
  10972. // without waiting for the socket to become readable again. The keep-alive
  10973. // timeout outlasts the client's read timeout, so a request left waiting for it
  10974. // shows up as a missing response.
  10975. static void serve_pipelining_routes(Server &svr,
  10976. const std::function<void(int)> &client) {
  10977. svr.set_keep_alive_timeout(5);
  10978. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10979. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10980. });
  10981. svr.Post("/echo", [](const Request &req, Response &res) {
  10982. res.set_content("echo " + req.body, "text/plain");
  10983. });
  10984. auto port = svr.bind_to_any_port(HOST);
  10985. thread t = thread([&] { svr.listen_after_bind(); });
  10986. auto se = detail::scope_exit([&] {
  10987. svr.stop();
  10988. t.join();
  10989. });
  10990. svr.wait_until_ready();
  10991. client(port);
  10992. }
  10993. static std::string
  10994. send_pipelined_requests(const std::vector<std::string> &parts) {
  10995. Server svr;
  10996. std::string res;
  10997. serve_pipelining_routes(svr, [&](int port) {
  10998. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10999. });
  11000. return res;
  11001. }
  11002. static void expect_in_order(const std::string &res,
  11003. const std::vector<std::string> &bodies) {
  11004. size_t pos = 0;
  11005. for (const auto &body : bodies) {
  11006. pos = res.find(body, pos);
  11007. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11008. pos += body.size();
  11009. }
  11010. }
  11011. TEST(KeepAliveTest, PipelinedRequests) {
  11012. auto res = send_pipelined_requests(
  11013. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11014. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11015. "Content-Length: 4\r\n\r\nbody"
  11016. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11017. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11018. }
  11019. // The second request starts in the server's buffer and ends on the socket.
  11020. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11021. auto res =
  11022. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11023. "GET /hi/2 HTTP/1.1\r\nHo",
  11024. "st: localhost\r\nConnection: close\r\n\r\n"});
  11025. expect_in_order(res, {"hi 1", "hi 2"});
  11026. }
  11027. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11028. // CRLF after a body does not turn into a 400 for the next request.
  11029. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11030. auto res = send_pipelined_requests(
  11031. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11032. "Content-Length: 4\r\n\r\nbody\r\n"
  11033. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11034. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11035. expect_in_order(res, {"echo body", "hi 2"});
  11036. }
  11037. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11038. // must not be served as the next request.
  11039. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11040. auto res = send_pipelined_requests(
  11041. {"INVALID REQUEST LINE\r\n\r\n"
  11042. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11043. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11044. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11045. }
  11046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11047. // Over TLS, the next request is held by the TLS library as already decrypted
  11048. // data rather than on the socket.
  11049. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11051. std::string res;
  11052. serve_pipelining_routes(svr, [&](int port) {
  11053. // One part, so all three requests arrive in one TLS record
  11054. EXPECT_TRUE(send_ssl_request_in_parts(
  11055. 2,
  11056. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11057. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11058. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11059. &res, port));
  11060. });
  11061. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11062. }
  11063. #endif
  11064. TEST(KeepAliveTest, Issue1041) {
  11065. Server svr;
  11066. svr.set_keep_alive_timeout(3);
  11067. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11068. res.set_content("Hello World!", "text/plain");
  11069. });
  11070. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11071. auto se = detail::scope_exit([&] {
  11072. svr.stop();
  11073. listen_thread.join();
  11074. ASSERT_FALSE(svr.is_running());
  11075. });
  11076. svr.wait_until_ready();
  11077. Client cli(HOST, PORT);
  11078. cli.set_keep_alive(true);
  11079. auto result = cli.Get("/hi");
  11080. ASSERT_TRUE(result);
  11081. EXPECT_EQ(StatusCode::OK_200, result->status);
  11082. std::this_thread::sleep_for(std::chrono::seconds(5));
  11083. result = cli.Get("/hi");
  11084. ASSERT_TRUE(result);
  11085. EXPECT_EQ(StatusCode::OK_200, result->status);
  11086. }
  11087. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11088. Server svr;
  11089. svr.set_keep_alive_max_count(0);
  11090. std::set<int> remote_ports;
  11091. svr.Get("/hi", [&](const Request &req, Response &res) {
  11092. remote_ports.insert(req.remote_port);
  11093. res.set_content("hi", "text/plain");
  11094. });
  11095. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11096. auto se = detail::scope_exit([&] {
  11097. svr.stop();
  11098. listen_thread.join();
  11099. ASSERT_FALSE(svr.is_running());
  11100. });
  11101. svr.wait_until_ready();
  11102. Client cli(HOST, PORT);
  11103. cli.set_keep_alive(true);
  11104. for (int i = 0; i < 3; i++) {
  11105. auto res = cli.Get("/hi");
  11106. ASSERT_TRUE(res);
  11107. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11108. }
  11109. // All three over one connection
  11110. EXPECT_EQ(1u, remote_ports.size());
  11111. }
  11112. TEST(KeepAliveTest, Issue1959) {
  11113. Server svr;
  11114. svr.set_keep_alive_timeout(5);
  11115. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11116. res.set_content("a", "text/plain");
  11117. });
  11118. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. if (!svr.is_running()) return;
  11121. svr.stop();
  11122. listen_thread.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. });
  11125. svr.wait_until_ready();
  11126. Client cli("localhost", PORT);
  11127. cli.set_keep_alive(true);
  11128. using namespace std::chrono;
  11129. auto start = steady_clock::now();
  11130. cli.Get("/a");
  11131. svr.stop();
  11132. listen_thread.join();
  11133. auto end = steady_clock::now();
  11134. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11135. EXPECT_LT(elapsed, 5000);
  11136. }
  11137. #ifdef CPPHTTPLIB_SSL_ENABLED
  11138. TEST(KeepAliveTest, SSLClientReconnection) {
  11139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11140. ASSERT_TRUE(svr.is_valid());
  11141. svr.set_keep_alive_timeout(1);
  11142. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11143. res.set_content("Hello World!", "text/plain");
  11144. });
  11145. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. listen_thread.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. SSLClient cli(HOST, PORT);
  11153. cli.enable_server_certificate_verification(false);
  11154. cli.set_keep_alive(true);
  11155. auto result = cli.Get("/hi");
  11156. ASSERT_TRUE(result);
  11157. EXPECT_EQ(StatusCode::OK_200, result->status);
  11158. result = cli.Get("/hi");
  11159. ASSERT_TRUE(result);
  11160. EXPECT_EQ(StatusCode::OK_200, result->status);
  11161. std::this_thread::sleep_for(std::chrono::seconds(2));
  11162. // Recoonect
  11163. result = cli.Get("/hi");
  11164. ASSERT_TRUE(result);
  11165. EXPECT_EQ(StatusCode::OK_200, result->status);
  11166. result = cli.Get("/hi");
  11167. ASSERT_TRUE(result);
  11168. EXPECT_EQ(StatusCode::OK_200, result->status);
  11169. }
  11170. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11172. ASSERT_TRUE(svr.is_valid());
  11173. svr.set_keep_alive_timeout(1);
  11174. std::string content = "reconnect";
  11175. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11176. res.set_content("Hello World!", "text/plain");
  11177. });
  11178. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. listen_thread.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. SSLClient cli(HOST, PORT);
  11186. cli.enable_server_certificate_verification(false);
  11187. cli.set_keep_alive(true);
  11188. auto result = cli.Post(
  11189. "/hi", content.size(),
  11190. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11191. sink.write(content.c_str(), content.size());
  11192. return true;
  11193. },
  11194. "text/plain");
  11195. ASSERT_TRUE(result);
  11196. EXPECT_EQ(200, result->status);
  11197. std::this_thread::sleep_for(std::chrono::seconds(2));
  11198. // Recoonect
  11199. result = cli.Post(
  11200. "/hi", content.size(),
  11201. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11202. sink.write(content.c_str(), content.size());
  11203. return true;
  11204. },
  11205. "text/plain");
  11206. ASSERT_TRUE(result);
  11207. EXPECT_EQ(200, result->status);
  11208. result = cli.Post(
  11209. "/hi", content.size(),
  11210. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11211. sink.write(content.c_str(), content.size());
  11212. return true;
  11213. },
  11214. "text/plain");
  11215. ASSERT_TRUE(result);
  11216. EXPECT_EQ(200, result->status);
  11217. }
  11218. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11219. using namespace httplib::tls;
  11220. {
  11221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11222. ASSERT_TRUE(svr.is_valid());
  11223. svr.Get("/sni", [&](const Request &req, Response &res) {
  11224. std::string expected = req.sni();
  11225. EXPECT_EQ(expected, req.get_param_value("expected"));
  11226. res.set_content("ok", "text/plain");
  11227. });
  11228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11229. auto se = detail::scope_exit([&] {
  11230. svr.stop();
  11231. listen_thread.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. {
  11236. SSLClient cli("localhost", PORT);
  11237. cli.enable_server_certificate_verification(false);
  11238. auto res = cli.Get("/sni?expected=localhost");
  11239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11240. }
  11241. {
  11242. SSLClient cli("::1", PORT);
  11243. cli.enable_server_certificate_verification(false);
  11244. auto res = cli.Get("/sni?expected=");
  11245. // NOTE: This may fail if the server is listening on IPv4 only
  11246. // (e.g., when localhost resolves to 127.0.0.1 only)
  11247. if (res) {
  11248. EXPECT_EQ(StatusCode::OK_200, res->status);
  11249. } else {
  11250. EXPECT_EQ(Error::Connection, res.error());
  11251. }
  11252. }
  11253. }
  11254. }
  11255. // The SNI of a failed handshake does not reach the next connection that the
  11256. // same worker thread serves
  11257. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11258. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11259. ASSERT_TRUE(svr.is_valid());
  11260. svr.new_task_queue = [] { return new ThreadPool(1); };
  11261. svr.Get("/sni", [](const Request &req, Response &res) {
  11262. res.set_content(req.sni(), "text/plain");
  11263. });
  11264. auto port = svr.bind_to_any_port("127.0.0.1");
  11265. ASSERT_LT(0, port);
  11266. thread t = thread([&] { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. t.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. {
  11274. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11275. SSLClient cli("localhost", port);
  11276. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11277. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11278. auto res = cli.Get("/sni");
  11279. ASSERT_FALSE(res);
  11280. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11281. }
  11282. // An IP host sends no SNI (RFC 6066)
  11283. SSLClient cli("127.0.0.1", port);
  11284. cli.enable_server_certificate_verification(false);
  11285. auto res = cli.Get("/sni");
  11286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11287. EXPECT_EQ("", res->body);
  11288. }
  11289. #endif
  11290. TEST(ClientProblemDetectionTest, ContentProvider) {
  11291. Server svr;
  11292. size_t content_length = 1024 * 1024;
  11293. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11294. res.set_content_provider(
  11295. content_length, "text/plain",
  11296. [&](size_t offset, size_t length, DataSink &sink) {
  11297. auto out_len = std::min(length, static_cast<size_t>(1024));
  11298. std::string out(out_len, '@');
  11299. sink.write(out.data(), out_len);
  11300. return offset < 4096;
  11301. },
  11302. [](bool success) { ASSERT_FALSE(success); });
  11303. });
  11304. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11305. res.set_content_provider(
  11306. 0, "text/plain",
  11307. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11308. EXPECT_TRUE(false);
  11309. return true;
  11310. },
  11311. [](bool success) { ASSERT_FALSE(success); });
  11312. });
  11313. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11314. auto se = detail::scope_exit([&] {
  11315. svr.stop();
  11316. listen_thread.join();
  11317. ASSERT_FALSE(svr.is_running());
  11318. });
  11319. svr.wait_until_ready();
  11320. Client cli("localhost", PORT);
  11321. {
  11322. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11323. size_t /*data_length*/) { return false; });
  11324. ASSERT_FALSE(res);
  11325. }
  11326. {
  11327. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11328. size_t /*data_length*/) { return false; });
  11329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11330. }
  11331. }
  11332. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11333. // A provider that reports success without writing anything and without
  11334. // calling done() used to be handed the same offset and length again on every
  11335. // pass, so it spun for as long as the peer stayed connected.
  11336. Server svr;
  11337. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11338. res.set_content("ok", "text/plain");
  11339. });
  11340. auto port = svr.bind_to_any_port(HOST);
  11341. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11342. auto se = detail::scope_exit([&] {
  11343. svr.stop();
  11344. listen_thread.join();
  11345. ASSERT_FALSE(svr.is_running());
  11346. });
  11347. svr.wait_until_ready();
  11348. std::atomic<int> call_count{0};
  11349. Client cli(HOST, port);
  11350. auto res = cli.Post(
  11351. "/", 1024,
  11352. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11353. // Give up after enough passes to show the spin, so that losing the
  11354. // check below fails this test instead of hanging it.
  11355. return ++call_count < 100;
  11356. },
  11357. "text/plain");
  11358. ASSERT_FALSE(res);
  11359. EXPECT_EQ(Error::Write, res.error());
  11360. EXPECT_EQ(1, call_count.load());
  11361. }
  11362. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11363. // A writer only has to assign `write`. The other three used to be left as
  11364. // empty std::functions, so a provider calling one threw
  11365. // std::bad_function_call out of the thread running it and took the whole
  11366. // process down.
  11367. DataSink sink;
  11368. std::string written;
  11369. sink.write = [&](const char *data, size_t data_len) {
  11370. written.append(data, data_len);
  11371. return true;
  11372. };
  11373. EXPECT_TRUE(sink.is_writable());
  11374. sink.done();
  11375. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11376. EXPECT_TRUE(written.empty());
  11377. }
  11378. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11379. // A sink that cannot carry trailers still has to finish.
  11380. DataSink sink;
  11381. auto done_count = 0;
  11382. sink.done = [&]() { done_count++; };
  11383. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11384. EXPECT_EQ(1, done_count);
  11385. }
  11386. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11387. Server svr;
  11388. const std::string body(4096, 'x');
  11389. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11390. res.set_content_provider(body.size(), "text/plain",
  11391. [&](size_t offset, size_t length, DataSink &sink) {
  11392. sink.write(body.data() + offset, length);
  11393. sink.done();
  11394. return true;
  11395. });
  11396. });
  11397. auto port = svr.bind_to_any_port(HOST);
  11398. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11399. auto se = detail::scope_exit([&] {
  11400. svr.stop();
  11401. listen_thread.join();
  11402. ASSERT_FALSE(svr.is_running());
  11403. });
  11404. svr.wait_until_ready();
  11405. Client cli(HOST, port);
  11406. auto res = cli.Get("/");
  11407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11408. EXPECT_EQ(StatusCode::OK_200, res->status);
  11409. EXPECT_EQ(body, res->body);
  11410. }
  11411. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11412. Server svr;
  11413. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11414. res.set_content_provider(
  11415. 1024, "text/plain",
  11416. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11417. sink.write("hello", 5);
  11418. sink.done(); // short of the 1024 bytes the response promised
  11419. return true;
  11420. });
  11421. });
  11422. auto port = svr.bind_to_any_port(HOST);
  11423. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. listen_thread.join();
  11427. ASSERT_FALSE(svr.is_running());
  11428. });
  11429. svr.wait_until_ready();
  11430. Client cli(HOST, port);
  11431. cli.set_read_timeout(5, 0);
  11432. // The response is short of its Content-Length, so the client cannot read a
  11433. // complete body. What matters is that this returns at all: a no-op done()
  11434. // would leave the writer looping over a provider that never makes progress.
  11435. auto res = cli.Get("/");
  11436. EXPECT_FALSE(res);
  11437. }
  11438. // Read as the next response by a peer that sees it after a framed body.
  11439. static const std::string smuggled_response =
  11440. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11441. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11442. Server svr;
  11443. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11444. res.set_content_provider(
  11445. 5, "text/plain",
  11446. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11447. auto data = "AAAAA" + smuggled_response;
  11448. sink.write(data.data(), data.size());
  11449. return true;
  11450. });
  11451. });
  11452. thread t = thread([&] { svr.listen(HOST, PORT); });
  11453. auto se = detail::scope_exit([&] {
  11454. svr.stop();
  11455. t.join();
  11456. ASSERT_FALSE(svr.is_running());
  11457. });
  11458. svr.wait_until_ready();
  11459. std::string resp;
  11460. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11461. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11462. resp.clear();
  11463. ASSERT_TRUE(send_request(
  11464. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11465. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11466. }
  11467. TEST(NoContentTest, BodyIsNotSent) {
  11468. Server svr;
  11469. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11470. res.status = StatusCode::NoContent_204;
  11471. res.set_content(smuggled_response, "text/plain");
  11472. });
  11473. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11474. res.status = StatusCode::NotModified_304;
  11475. res.set_chunked_content_provider(
  11476. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11477. sink.write(smuggled_response.data(), smuggled_response.size());
  11478. sink.done();
  11479. return true;
  11480. });
  11481. });
  11482. thread t = thread([&] { svr.listen(HOST, PORT); });
  11483. auto se = detail::scope_exit([&] {
  11484. svr.stop();
  11485. t.join();
  11486. ASSERT_FALSE(svr.is_running());
  11487. });
  11488. svr.wait_until_ready();
  11489. for (auto path : {"/204", "/304"}) {
  11490. std::string resp;
  11491. ASSERT_TRUE(send_request(
  11492. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11493. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11494. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11495. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11496. }
  11497. }
  11498. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11499. Server svr;
  11500. std::atomic<bool> smuggled(false);
  11501. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11502. res.set_content("ok", "text/plain");
  11503. });
  11504. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11505. smuggled = true;
  11506. });
  11507. auto port = svr.bind_to_any_port(HOST);
  11508. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. listen_thread.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. // What follows the body would be read as the next request.
  11516. Client cli(HOST, port);
  11517. auto res = cli.Post(
  11518. "/", 5,
  11519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11520. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11521. sink.write(data.data(), data.size());
  11522. return true;
  11523. },
  11524. "text/plain");
  11525. ASSERT_FALSE(res);
  11526. EXPECT_EQ(Error::Write, res.error());
  11527. EXPECT_FALSE(smuggled);
  11528. }
  11529. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11530. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11531. // The compressed path builds the whole body before connecting, so this
  11532. // fails client-side and never reaches a server.
  11533. Client cli(HOST, PORT);
  11534. cli.set_compress(true);
  11535. auto res = cli.Post(
  11536. "/", 1024,
  11537. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11538. sink.write("hello", 5);
  11539. sink.done(); // short of the 1024 bytes the request announced
  11540. return true;
  11541. },
  11542. "text/plain");
  11543. ASSERT_FALSE(res);
  11544. EXPECT_EQ(Error::Write, res.error());
  11545. }
  11546. #endif
  11547. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11548. Server svr;
  11549. svr.set_error_handler([](Request const &, Response &res) -> void {
  11550. res.set_chunked_content_provider(
  11551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11552. sink.os << "hello";
  11553. sink.os << "world";
  11554. sink.done();
  11555. return true;
  11556. });
  11557. });
  11558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11559. auto se = detail::scope_exit([&] {
  11560. svr.stop();
  11561. listen_thread.join();
  11562. ASSERT_FALSE(svr.is_running());
  11563. });
  11564. svr.wait_until_ready();
  11565. Client cli("localhost", PORT);
  11566. auto res = cli.Get("/");
  11567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11569. EXPECT_EQ("helloworld", res->body);
  11570. }
  11571. // A body set after a content provider must replace it, not be sent through it.
  11572. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11573. Server svr;
  11574. svr.set_mount_point("/", "./www");
  11575. svr.set_file_request_handler([](const Request &req, Response &res) {
  11576. if (req.path == "/dir/test.html") {
  11577. res.status = StatusCode::Forbidden_403;
  11578. res.set_content(std::string(5000, 'D'), "text/plain");
  11579. } else if (req.path == "/file") {
  11580. res.status = StatusCode::Forbidden_403;
  11581. res.body = "Denied";
  11582. }
  11583. });
  11584. auto port = svr.bind_to_any_port(HOST);
  11585. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11586. auto se = detail::scope_exit([&] {
  11587. svr.stop();
  11588. t.join();
  11589. ASSERT_FALSE(svr.is_running());
  11590. });
  11591. svr.wait_until_ready();
  11592. Client cli(HOST, port);
  11593. {
  11594. auto res = cli.Get("/dir/test.html");
  11595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11596. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11597. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11598. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11599. }
  11600. {
  11601. auto res = cli.Get("/file");
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11604. EXPECT_EQ("Denied", res->body);
  11605. }
  11606. {
  11607. auto res = cli.Get("/dir/index.html");
  11608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11609. EXPECT_EQ(StatusCode::OK_200, res->status);
  11610. EXPECT_EQ(0U, res->body.find("<html>"));
  11611. }
  11612. }
  11613. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11614. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11615. Server svr;
  11616. std::vector<bool> released;
  11617. std::mutex released_mutex;
  11618. auto releaser = [&](bool success) {
  11619. std::lock_guard<std::mutex> guard(released_mutex);
  11620. released.push_back(success);
  11621. };
  11622. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11623. return sink.write(&"hello"[offset], length);
  11624. };
  11625. svr.Get("/sized", [&](const Request &, Response &res) {
  11626. res.status = StatusCode::NotFound_404;
  11627. res.set_content_provider(5, "text/plain", provider, releaser);
  11628. });
  11629. svr.Get("/chunked", [&](const Request &, Response &res) {
  11630. res.status = StatusCode::ServiceUnavailable_503;
  11631. res.set_chunked_content_provider(
  11632. "text/plain",
  11633. [](size_t, DataSink &sink) {
  11634. sink.os << "chunk";
  11635. sink.done();
  11636. return true;
  11637. },
  11638. releaser);
  11639. });
  11640. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11641. res.set_content_provider(5, "text/plain", provider, releaser);
  11642. throw std::runtime_error("after the provider");
  11643. });
  11644. svr.set_error_handler([](const Request &req, Response &res) {
  11645. // Leave the exception handler's content to it.
  11646. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11647. res.set_content(std::string(1000, 'E'), "text/html");
  11648. return Server::HandlerResponse::Handled;
  11649. });
  11650. svr.set_exception_handler(
  11651. [](const Request &, Response &res, std::exception_ptr) {
  11652. res.status = StatusCode::InternalServerError_500;
  11653. res.set_content(std::string(1000, 'X'), "text/html");
  11654. });
  11655. auto port = svr.bind_to_any_port(HOST);
  11656. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11657. auto se = detail::scope_exit([&] {
  11658. svr.stop();
  11659. t.join();
  11660. ASSERT_FALSE(svr.is_running());
  11661. });
  11662. svr.wait_until_ready();
  11663. Client cli(HOST, port);
  11664. {
  11665. auto res = cli.Get("/sized");
  11666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11668. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11670. }
  11671. {
  11672. auto res = cli.Get("/chunked");
  11673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11674. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11675. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11676. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11677. }
  11678. {
  11679. auto res = cli.Get("/throw");
  11680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11681. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11682. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11683. }
  11684. std::lock_guard<std::mutex> guard(released_mutex);
  11685. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11686. }
  11687. #endif
  11688. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11689. Server svr;
  11690. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11691. return sink.write(&"abc"[offset], length);
  11692. };
  11693. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11694. res.set_file_content("./www/dir/test.html");
  11695. res.set_content("body", "text/plain");
  11696. });
  11697. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11698. res.set_content(std::string(100, 'B'), "text/plain");
  11699. res.set_file_content("./www/dir/test.html");
  11700. });
  11701. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11702. res.set_content(std::string(100, 'B'), "text/plain");
  11703. res.set_content_provider(3, "text/x-provider", abc);
  11704. });
  11705. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11706. res.set_content_provider(3, "text/x-provider", abc);
  11707. res.set_content(std::string(100, 'B'), "text/plain");
  11708. });
  11709. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11710. res.set_content_provider(3, "text/x-provider", abc);
  11711. res.set_file_content("./www/dir/test.html", "text/x-file");
  11712. });
  11713. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11714. res.set_file_content("./www/dir/test.html");
  11715. res.set_header("Content-Type", "text/x-handler");
  11716. });
  11717. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11718. res.set_content_provider(3, "text/plain", abc);
  11719. res.body = "direct";
  11720. });
  11721. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11722. res.set_file_content("./www/dir/test.html");
  11723. res.body = "direct";
  11724. });
  11725. auto port = svr.bind_to_any_port(HOST);
  11726. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11727. auto se = detail::scope_exit([&] {
  11728. svr.stop();
  11729. t.join();
  11730. ASSERT_FALSE(svr.is_running());
  11731. });
  11732. svr.wait_until_ready();
  11733. Client cli(HOST, port);
  11734. auto expect_body = [&](const char *path, const std::string &body,
  11735. const std::string &type) {
  11736. // Uncompressed, so Content-Length can be compared with the body.
  11737. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11738. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11739. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11740. EXPECT_EQ(body, res->body) << path;
  11741. EXPECT_EQ(std::to_string(body.size()),
  11742. res->get_header_value("Content-Length"))
  11743. << path;
  11744. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11745. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11746. };
  11747. expect_body("/file-then-body", "body", "text/plain");
  11748. expect_body("/body-then-file", "test.html", "text/html");
  11749. expect_body("/body-then-provider", "abc", "text/x-provider");
  11750. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11751. expect_body("/provider-then-file", "test.html", "text/x-file");
  11752. expect_body("/file-then-header", "test.html", "text/x-handler");
  11753. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11754. expect_body("/file-then-direct-body", "direct", "text/plain");
  11755. // Ranges are checked against the body, not the dropped provider.
  11756. {
  11757. auto res = cli.Get("/provider-then-direct-body",
  11758. Headers{{make_range_header({{1, 2}})}});
  11759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11761. EXPECT_EQ("ir", res->body);
  11762. }
  11763. {
  11764. auto res = cli.Get("/file-then-direct-body",
  11765. Headers{{make_range_header({{7, 8}})}});
  11766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11767. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11768. }
  11769. }
  11770. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11771. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11772. const char *path = "./truncated_while_served.txt";
  11773. const size_t size = 32 * 1024 * 1024;
  11774. {
  11775. std::ofstream f(path, std::ios::binary);
  11776. f << std::string(size, 'x');
  11777. }
  11778. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11779. // Over TLS, where the bytes are encrypted in this process rather than
  11780. // copied by send().
  11781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11782. svr.Get("/file", [&](const Request &, Response &res) {
  11783. res.set_file_content(path, "text/plain");
  11784. });
  11785. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11786. auto se = detail::scope_exit([&] {
  11787. svr.stop();
  11788. thread.join();
  11789. ASSERT_FALSE(svr.is_running());
  11790. });
  11791. svr.wait_until_ready();
  11792. // The file shrinks once the first bytes are in, as a rewrite in place
  11793. // would, and reading the mapping past its new end used to raise SIGBUS.
  11794. SSLClient cli(HOST, PORT);
  11795. cli.enable_server_certificate_verification(false);
  11796. size_t received = 0;
  11797. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11798. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11799. received += len;
  11800. return true;
  11801. });
  11802. EXPECT_FALSE(res);
  11803. EXPECT_LT(received, size);
  11804. }
  11805. #endif
  11806. // Forward declaration (see the base64_encode note).
  11807. namespace httplib {
  11808. namespace detail {
  11809. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11810. const std::string &content_type,
  11811. EncodingType encoding);
  11812. } // namespace detail
  11813. } // namespace httplib
  11814. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11815. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11816. ASSERT_TRUE(mm->is_open());
  11817. Response res;
  11818. detail::set_file_content_provider(res, mm, "text/html",
  11819. detail::EncodingType::None);
  11820. std::string out;
  11821. DataSink sink;
  11822. sink.write = [&](const char *d, size_t l) {
  11823. out.append(d, l);
  11824. return true;
  11825. };
  11826. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11827. EXPECT_EQ("test.html", out);
  11828. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11829. EXPECT_EQ("test.html", out);
  11830. }
  11831. TEST(LongPollingTest, ClientCloseDetection) {
  11832. Server svr;
  11833. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11834. res.set_chunked_content_provider(
  11835. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11836. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11837. sink.os << "hello";
  11838. auto count = 10;
  11839. while (count > 0 && sink.is_writable()) {
  11840. this_thread::sleep_for(chrono::milliseconds(10));
  11841. count--;
  11842. }
  11843. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11844. return true;
  11845. });
  11846. });
  11847. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11848. auto se = detail::scope_exit([&] {
  11849. svr.stop();
  11850. listen_thread.join();
  11851. ASSERT_FALSE(svr.is_running());
  11852. });
  11853. svr.wait_until_ready();
  11854. Client cli("localhost", PORT);
  11855. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11856. EXPECT_EQ("hello", string(data, data_length));
  11857. return false; // close the socket immediately.
  11858. });
  11859. ASSERT_FALSE(res);
  11860. }
  11861. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11862. Server svr;
  11863. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11864. res.set_chunked_content_provider(
  11865. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11866. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11867. sink.os << "hello";
  11868. EXPECT_TRUE(sink.os.good());
  11869. // Wait for the client to close the connection
  11870. auto count = 10;
  11871. while (count > 0 && sink.is_writable()) {
  11872. this_thread::sleep_for(chrono::milliseconds(10));
  11873. count--;
  11874. }
  11875. // After client disconnect, write repeatedly until the socket
  11876. // write actually fails (small writes may be absorbed by the
  11877. // kernel buffer)
  11878. std::string chunk(1024, 'x');
  11879. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11880. sink.os << chunk;
  11881. }
  11882. EXPECT_TRUE(sink.os.fail());
  11883. return true;
  11884. });
  11885. });
  11886. auto port = svr.bind_to_any_port("localhost");
  11887. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11888. auto se = detail::scope_exit([&] {
  11889. svr.stop();
  11890. listen_thread.join();
  11891. ASSERT_FALSE(svr.is_running());
  11892. });
  11893. svr.wait_until_ready();
  11894. Client cli("localhost", port);
  11895. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11896. EXPECT_EQ("hello", string(data, data_length));
  11897. return false; // close the socket immediately.
  11898. });
  11899. ASSERT_FALSE(res);
  11900. }
  11901. TEST(GetWithParametersTest, GetWithParameters) {
  11902. Server svr;
  11903. svr.Get("/", [&](const Request &req, Response &) {
  11904. EXPECT_EQ("world", req.get_param_value("hello"));
  11905. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11906. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11907. });
  11908. svr.Get("/params", [&](const Request &req, Response &) {
  11909. EXPECT_EQ("world", req.get_param_value("hello"));
  11910. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11911. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11912. });
  11913. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11914. EXPECT_EQ("resource-id", req.matches[1]);
  11915. EXPECT_EQ("foo", req.get_param_value("param1"));
  11916. EXPECT_EQ("bar", req.get_param_value("param2"));
  11917. });
  11918. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11919. EXPECT_EQ("user-id", req.path_params.at("id"));
  11920. EXPECT_EQ("foo", req.get_param_value("param1"));
  11921. EXPECT_EQ("bar", req.get_param_value("param2"));
  11922. });
  11923. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11924. auto se = detail::scope_exit([&] {
  11925. svr.stop();
  11926. listen_thread.join();
  11927. ASSERT_FALSE(svr.is_running());
  11928. });
  11929. svr.wait_until_ready();
  11930. {
  11931. Client cli(HOST, PORT);
  11932. Params params;
  11933. params.emplace("hello", "world");
  11934. params.emplace("hello2", "world2");
  11935. params.emplace("hello3", "world3");
  11936. auto res = cli.Get("/", params, Headers{});
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. }
  11940. {
  11941. Client cli(HOST, PORT);
  11942. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11944. EXPECT_EQ(StatusCode::OK_200, res->status);
  11945. }
  11946. {
  11947. Client cli(HOST, PORT);
  11948. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. EXPECT_EQ(StatusCode::OK_200, res->status);
  11951. }
  11952. {
  11953. Client cli(HOST, PORT);
  11954. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. }
  11958. }
  11959. TEST(GetWithParametersTest, GetWithParameters2) {
  11960. Server svr;
  11961. svr.Get("/", [&](const Request &req, Response &res) {
  11962. auto text = req.get_param_value("hello");
  11963. res.set_content(text, "text/plain");
  11964. });
  11965. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11966. auto se = detail::scope_exit([&] {
  11967. svr.stop();
  11968. listen_thread.join();
  11969. ASSERT_FALSE(svr.is_running());
  11970. });
  11971. svr.wait_until_ready();
  11972. Client cli("localhost", PORT);
  11973. Params params;
  11974. params.emplace("hello", "world");
  11975. std::string body;
  11976. auto res = cli.Get("/", params, Headers{},
  11977. [&](const char *data, size_t data_length) {
  11978. body.append(data, data_length);
  11979. return true;
  11980. });
  11981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11982. EXPECT_EQ(StatusCode::OK_200, res->status);
  11983. EXPECT_EQ("world", body);
  11984. }
  11985. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11986. Server svr;
  11987. svr.Get("/search", [&](const Request &req, Response &res) {
  11988. auto q = req.get_param_value("q");
  11989. res.set_content(q, "text/plain");
  11990. });
  11991. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11992. auto se = detail::scope_exit([&] {
  11993. svr.stop();
  11994. listen_thread.join();
  11995. ASSERT_FALSE(svr.is_running());
  11996. });
  11997. svr.wait_until_ready();
  11998. Client cli("localhost", PORT);
  11999. // Verify that Get(path, params) works without requiring Headers argument
  12000. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12002. EXPECT_EQ(StatusCode::OK_200, res->status);
  12003. EXPECT_EQ("cpp-httplib", res->body);
  12004. }
  12005. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12006. auto host = "httpbingo.org";
  12007. auto path = std::string{"/range/32"};
  12008. #ifdef CPPHTTPLIB_SSL_ENABLED
  12009. SSLClient cli(host);
  12010. #else
  12011. Client cli(host);
  12012. #endif
  12013. cli.set_default_headers({make_range_header({{1, 10}})});
  12014. cli.set_connection_timeout(5);
  12015. {
  12016. auto res = cli.Get(path);
  12017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12018. EXPECT_EQ("bcdefghijk", res->body);
  12019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12020. }
  12021. {
  12022. auto res = cli.Get(path);
  12023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12024. EXPECT_EQ("bcdefghijk", res->body);
  12025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12026. }
  12027. }
  12028. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12029. Server svr;
  12030. svr.set_default_headers({{"Hello", "World"}});
  12031. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12032. res.set_content("ok", "text/plain");
  12033. });
  12034. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12035. auto se = detail::scope_exit([&] {
  12036. svr.stop();
  12037. listen_thread.join();
  12038. ASSERT_FALSE(svr.is_running());
  12039. });
  12040. svr.wait_until_ready();
  12041. Client cli("localhost", PORT);
  12042. auto res = cli.Get("/");
  12043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12044. EXPECT_EQ(StatusCode::OK_200, res->status);
  12045. EXPECT_EQ("ok", res->body);
  12046. EXPECT_EQ("World", res->get_header_value("Hello"));
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12051. ASSERT_TRUE(svr.is_valid());
  12052. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12053. std::this_thread::sleep_for(std::chrono::seconds(2));
  12054. res.set_content("a", "text/plain");
  12055. });
  12056. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12057. res.set_content("b", "text/plain");
  12058. });
  12059. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12060. auto se = detail::scope_exit([&] {
  12061. svr.stop();
  12062. listen_thread.join();
  12063. ASSERT_FALSE(svr.is_running());
  12064. });
  12065. svr.wait_until_ready();
  12066. SSLClient cli("localhost", PORT);
  12067. cli.enable_server_certificate_verification(false);
  12068. cli.set_keep_alive(true);
  12069. cli.set_read_timeout(std::chrono::seconds(1));
  12070. auto resa = cli.Get("/a");
  12071. ASSERT_TRUE(!resa);
  12072. EXPECT_EQ(Error::Read, resa.error());
  12073. auto resb = cli.Get("/b");
  12074. ASSERT_TRUE(resb);
  12075. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12076. EXPECT_EQ("b", resb->body);
  12077. }
  12078. // Closing an idle keep-alive connection sends close_notify and returns. The
  12079. // server must not wait for the client's close_notify: an idle client never
  12080. // sends one, so the worker would be held until the read timeout expires, and
  12081. // stop() would wait for it.
  12082. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12084. ASSERT_TRUE(svr.is_valid());
  12085. svr.set_keep_alive_timeout(1);
  12086. svr.set_read_timeout(10, 0);
  12087. svr.Get("/", [](const Request &, Response &res) {
  12088. res.set_content("ok", "text/plain");
  12089. });
  12090. auto port = svr.bind_to_any_port(HOST);
  12091. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12092. auto se = detail::scope_exit([&] {
  12093. if (listen_thread.joinable()) {
  12094. svr.stop();
  12095. listen_thread.join();
  12096. }
  12097. });
  12098. svr.wait_until_ready();
  12099. SSLClient cli(HOST, port);
  12100. cli.enable_server_certificate_verification(false);
  12101. cli.set_keep_alive(true);
  12102. auto res = cli.Get("/");
  12103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12104. EXPECT_EQ(StatusCode::OK_200, res->status);
  12105. // Stay idle past the keep-alive timeout so the server closes the connection.
  12106. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12107. auto start = std::chrono::steady_clock::now();
  12108. svr.stop();
  12109. listen_thread.join();
  12110. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12111. std::chrono::steady_clock::now() - start)
  12112. .count();
  12113. EXPECT_LT(elapsed, 3000);
  12114. }
  12115. #endif
  12116. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12117. protected:
  12118. ServerTestWithAI_PASSIVE()
  12119. : cli_(HOST, PORT)
  12120. #ifdef CPPHTTPLIB_SSL_ENABLED
  12121. ,
  12122. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12123. #endif
  12124. {
  12125. #ifdef CPPHTTPLIB_SSL_ENABLED
  12126. cli_.enable_server_certificate_verification(false);
  12127. #endif
  12128. }
  12129. virtual void SetUp() {
  12130. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12131. res.set_content("Hello World!", "text/plain");
  12132. });
  12133. t_ = thread(
  12134. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12135. svr_.wait_until_ready();
  12136. }
  12137. virtual void TearDown() {
  12138. svr_.stop();
  12139. t_.join();
  12140. }
  12141. #ifdef CPPHTTPLIB_SSL_ENABLED
  12142. SSLClient cli_;
  12143. SSLServer svr_;
  12144. #else
  12145. Client cli_;
  12146. Server svr_;
  12147. #endif
  12148. thread t_;
  12149. };
  12150. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12151. auto res = cli_.Get("/hi");
  12152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12153. EXPECT_EQ(StatusCode::OK_200, res->status);
  12154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12155. EXPECT_EQ("Hello World!", res->body);
  12156. }
  12157. class ServerUpDownTest : public ::testing::Test {
  12158. protected:
  12159. ServerUpDownTest() : cli_(HOST, PORT) {}
  12160. virtual void SetUp() {
  12161. t_ = thread([&]() {
  12162. svr_.bind_to_any_port(HOST);
  12163. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12164. ASSERT_TRUE(svr_.listen_after_bind());
  12165. });
  12166. svr_.wait_until_ready();
  12167. }
  12168. virtual void TearDown() {
  12169. svr_.stop();
  12170. t_.join();
  12171. }
  12172. Client cli_;
  12173. Server svr_;
  12174. thread t_;
  12175. };
  12176. TEST_F(ServerUpDownTest, QuickStartStop) {
  12177. // Should not crash, especially when run with
  12178. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12179. }
  12180. class PayloadMaxLengthTest : public ::testing::Test {
  12181. protected:
  12182. PayloadMaxLengthTest()
  12183. : cli_(HOST, PORT)
  12184. #ifdef CPPHTTPLIB_SSL_ENABLED
  12185. ,
  12186. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12187. #endif
  12188. {
  12189. #ifdef CPPHTTPLIB_SSL_ENABLED
  12190. cli_.enable_server_certificate_verification(false);
  12191. #endif
  12192. }
  12193. virtual void SetUp() {
  12194. svr_.set_payload_max_length(8);
  12195. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12196. res.set_content("test", "text/plain");
  12197. });
  12198. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12199. svr_.wait_until_ready();
  12200. }
  12201. virtual void TearDown() {
  12202. svr_.stop();
  12203. t_.join();
  12204. }
  12205. #ifdef CPPHTTPLIB_SSL_ENABLED
  12206. SSLClient cli_;
  12207. SSLServer svr_;
  12208. #else
  12209. Client cli_;
  12210. Server svr_;
  12211. #endif
  12212. thread t_;
  12213. };
  12214. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12215. auto res = cli_.Post("/test", "123456789", "text/plain");
  12216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12217. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12218. res = cli_.Post("/test", "12345678", "text/plain");
  12219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12220. EXPECT_EQ(StatusCode::OK_200, res->status);
  12221. }
  12222. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12223. // Test chunked encoding with payload exceeding the 8-byte limit
  12224. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12225. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12227. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12228. }
  12229. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12230. // Test chunked encoding with payload within the 8-byte limit
  12231. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12232. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12234. EXPECT_EQ(StatusCode::OK_200, res->status);
  12235. }
  12236. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12237. // Test using send_request to send chunked data exceeding payload limit
  12238. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12239. "Host: " +
  12240. std::string(HOST) + ":" + std::to_string(PORT) +
  12241. "\r\n"
  12242. "Transfer-Encoding: chunked\r\n"
  12243. "Connection: close\r\n"
  12244. "\r\n"
  12245. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12246. "0123456789\r\n"
  12247. "0\r\n" // End chunk
  12248. "\r\n";
  12249. std::string response;
  12250. bool result = send_request(1, chunked_request, &response);
  12251. if (!result) {
  12252. // If send_request fails, it might be because the server closed the
  12253. // connection due to payload limit enforcement, which is acceptable
  12254. SUCCEED()
  12255. << "Server rejected oversized chunked request (connection closed)";
  12256. } else {
  12257. // If we got a response, check if it's an error response or connection was
  12258. // closed early Short response length indicates connection was closed due to
  12259. // payload limit
  12260. if (response.length() <= 10) {
  12261. SUCCEED() << "Server closed connection for oversized chunked request";
  12262. } else {
  12263. // Check for error status codes
  12264. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12265. response.find("Payload Too Large") != std::string::npos ||
  12266. response.find("400") != std::string::npos);
  12267. }
  12268. }
  12269. }
  12270. class LargePayloadMaxLengthTest : public ::testing::Test {
  12271. protected:
  12272. LargePayloadMaxLengthTest()
  12273. : cli_(HOST, PORT)
  12274. #ifdef CPPHTTPLIB_SSL_ENABLED
  12275. ,
  12276. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12277. #endif
  12278. {
  12279. #ifdef CPPHTTPLIB_SSL_ENABLED
  12280. cli_.enable_server_certificate_verification(false);
  12281. #endif
  12282. }
  12283. virtual void SetUp() {
  12284. // Set 10MB payload limit
  12285. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12286. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12287. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12288. res.set_content("Large payload test", "text/plain");
  12289. });
  12290. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12291. svr_.wait_until_ready();
  12292. }
  12293. virtual void TearDown() {
  12294. svr_.stop();
  12295. t_.join();
  12296. }
  12297. #ifdef CPPHTTPLIB_SSL_ENABLED
  12298. SSLClient cli_;
  12299. SSLServer svr_;
  12300. #else
  12301. Client cli_;
  12302. Server svr_;
  12303. #endif
  12304. thread t_;
  12305. };
  12306. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12307. // Test chunked encoding with payload within 10MB limit
  12308. std::string medium_payload(5 * 1024 * 1024,
  12309. 'A'); // 5MB payload, within 10MB limit
  12310. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12312. EXPECT_EQ(StatusCode::OK_200, res->status);
  12313. }
  12314. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12315. // Test chunked encoding with payload exceeding 10MB limit
  12316. std::string large_payload(12 * 1024 * 1024,
  12317. 'B'); // 12MB payload, exceeds 10MB limit
  12318. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12319. // Server may either return 413 or close the connection
  12320. if (res) {
  12321. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12322. } else {
  12323. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12324. }
  12325. }
  12326. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12327. Server svr;
  12328. svr.Get("/", [](const Request &, Response &res) {
  12329. // Claims the most the client accepts, far more than it sends, then drops
  12330. // the connection.
  12331. res.set_content_provider(std::string().max_size(), "text/plain",
  12332. [](size_t, size_t, DataSink &sink) {
  12333. sink.write("abc", 3);
  12334. return false;
  12335. });
  12336. });
  12337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12338. auto se = detail::scope_exit([&] {
  12339. svr.stop();
  12340. thread.join();
  12341. ASSERT_FALSE(svr.is_running());
  12342. });
  12343. svr.wait_until_ready();
  12344. Client cli(HOST, PORT);
  12345. cli.set_payload_max_length(0);
  12346. EXPECT_FALSE(cli.Get("/"));
  12347. }
  12348. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12349. // Stream API does, not as a plain read failure
  12350. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12351. Server svr;
  12352. svr.Get("/big", [](const Request &, Response &res) {
  12353. res.set_content(std::string(100000, 'b'), "text/plain");
  12354. });
  12355. auto port = svr.bind_to_any_port(HOST);
  12356. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12357. auto se = detail::scope_exit([&] {
  12358. svr.stop();
  12359. thread.join();
  12360. });
  12361. svr.wait_until_ready();
  12362. Client cli(HOST, port);
  12363. cli.set_payload_max_length(1000);
  12364. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12365. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12366. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12367. [](const char *, size_t) { return true; });
  12368. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12369. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12370. // Small on the wire, over the limit once decompressed
  12371. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12372. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12373. #endif
  12374. }
  12375. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12376. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12377. // path.
  12378. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12379. Server svr;
  12380. const size_t LIMIT = 64 * 1024; // 64KB
  12381. svr.set_payload_max_length(LIMIT);
  12382. size_t total = 0;
  12383. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12384. const ContentReader &content_reader) {
  12385. content_reader([&](const char * /*data*/, size_t len) {
  12386. total += len;
  12387. return true;
  12388. });
  12389. res.status = 200;
  12390. res.set_content("stream_ok", "text/plain");
  12391. });
  12392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12393. auto se = detail::scope_exit([&] {
  12394. svr.stop();
  12395. thread.join();
  12396. ASSERT_FALSE(svr.is_running());
  12397. });
  12398. svr.wait_until_ready();
  12399. // Prepare 256KB raw data and gzip-compress it
  12400. std::string raw(256 * 1024, 'A');
  12401. std::string gz;
  12402. {
  12403. z_stream zs{};
  12404. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12405. Z_DEFAULT_STRATEGY);
  12406. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12407. zs.avail_in = static_cast<uInt>(raw.size());
  12408. char outbuf[4096];
  12409. int ret;
  12410. do {
  12411. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12412. zs.avail_out = sizeof(outbuf);
  12413. ret = deflate(&zs, Z_FINISH);
  12414. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12415. } while (ret != Z_STREAM_END);
  12416. deflateEnd(&zs);
  12417. }
  12418. Client cli(HOST, PORT);
  12419. cli.set_connection_timeout(std::chrono::seconds(5));
  12420. Headers headers = {{"Content-Encoding", "gzip"}};
  12421. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12422. "application/octet-stream");
  12423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12424. // Server must reject oversized decompressed payloads with 413.
  12425. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12426. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12427. EXPECT_LE(total, LIMIT);
  12428. }
  12429. #endif
  12430. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12431. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12432. // the payload must be passed through untouched instead of being rejected.
  12433. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12434. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12435. Server svr;
  12436. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12437. res.set_content(body, "image/jpeg");
  12438. res.set_header("Content-Encoding", "UTF-8");
  12439. });
  12440. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12441. res.set_content(body, "image/jpeg");
  12442. res.set_header("Content-Encoding", "identity");
  12443. });
  12444. svr.Post("/echo", [](const Request &req, Response &res) {
  12445. res.set_content(req.body, "image/jpeg");
  12446. });
  12447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12448. auto se = detail::scope_exit([&] {
  12449. svr.stop();
  12450. t.join();
  12451. ASSERT_FALSE(svr.is_running());
  12452. });
  12453. svr.wait_until_ready();
  12454. Client cli(HOST, PORT);
  12455. {
  12456. auto res = cli.Get("/image");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. EXPECT_EQ(StatusCode::OK_200, res->status);
  12459. EXPECT_EQ(body, res->body);
  12460. }
  12461. {
  12462. auto res = cli.Get("/identity");
  12463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12464. EXPECT_EQ(StatusCode::OK_200, res->status);
  12465. EXPECT_EQ(body, res->body);
  12466. }
  12467. {
  12468. // The same applies to a request body reaching the server.
  12469. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12470. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12472. EXPECT_EQ(StatusCode::OK_200, res->status);
  12473. EXPECT_EQ(body, res->body);
  12474. }
  12475. }
  12476. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12477. // gzip-encoded response even when the build has no zlib support.
  12478. static const char GZIPPED_HELLO_WORLD[] = {
  12479. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12480. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12481. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12482. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12483. // A content coding is a whole token, not something the field value merely
  12484. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12485. // as "fibre" look like Brotli, and turned a multi-coding value like
  12486. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12487. // it was never meant to see.
  12488. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12489. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12490. Server svr;
  12491. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12492. res.set_content(body, "image/jpeg");
  12493. res.set_header("Content-Encoding", "fibre");
  12494. });
  12495. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12496. res.set_content(body, "image/jpeg");
  12497. res.set_header("Content-Encoding", "gzip, br");
  12498. });
  12499. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12500. res.set_content(body, "image/jpeg");
  12501. res.set_header("Content-Encoding", "x-zstd-ish");
  12502. });
  12503. auto port = svr.bind_to_any_port(HOST);
  12504. thread t = thread([&]() { svr.listen_after_bind(); });
  12505. auto se = detail::scope_exit([&] {
  12506. svr.stop();
  12507. t.join();
  12508. ASSERT_FALSE(svr.is_running());
  12509. });
  12510. svr.wait_until_ready();
  12511. Client cli(HOST, port);
  12512. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12513. auto res = cli.Get(path);
  12514. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12515. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12516. // Not a coding we recognize, so the payload comes back untouched
  12517. EXPECT_EQ(body, res->body) << path;
  12518. }
  12519. }
  12520. // A content coding cpp-httplib recognizes but was not built with must be
  12521. // reported as such. Handing the still-compressed payload back to the caller
  12522. // would silently corrupt it.
  12523. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12524. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12525. Server svr;
  12526. // "image/jpeg" keeps the server from applying a content coding of its own,
  12527. // so the hand-crafted Content-Encoding below survives.
  12528. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12529. res.set_content(gzipped, "image/jpeg");
  12530. res.set_header("Content-Encoding", "gzip");
  12531. });
  12532. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12533. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12534. res.set_content(gzipped, "image/jpeg");
  12535. res.set_header("Content-Encoding", "GZIP");
  12536. });
  12537. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12538. auto se = detail::scope_exit([&] {
  12539. svr.stop();
  12540. t.join();
  12541. ASSERT_FALSE(svr.is_running());
  12542. });
  12543. svr.wait_until_ready();
  12544. Client cli(HOST, PORT);
  12545. {
  12546. auto res = cli.Get("/gzipped");
  12547. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12549. EXPECT_EQ("Hello World!", res->body);
  12550. #else
  12551. ASSERT_FALSE(res);
  12552. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12553. #endif
  12554. }
  12555. {
  12556. // open_stream() must behave the same way.
  12557. auto handle = cli.open_stream("GET", "/gzipped");
  12558. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12559. ASSERT_TRUE(handle.is_valid());
  12560. std::string received;
  12561. char buf[256];
  12562. ssize_t n;
  12563. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12564. received.append(buf, static_cast<size_t>(n));
  12565. }
  12566. EXPECT_EQ("Hello World!", received);
  12567. #else
  12568. EXPECT_FALSE(handle.is_valid());
  12569. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12570. #endif
  12571. }
  12572. {
  12573. // A differently-cased coding must not be mistaken for an unknown one, or
  12574. // the body would be handed back still compressed.
  12575. auto res = cli.Get("/gzipped-uppercase");
  12576. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12578. EXPECT_EQ("Hello World!", res->body);
  12579. #else
  12580. ASSERT_FALSE(res);
  12581. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12582. #endif
  12583. }
  12584. }
  12585. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12586. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12587. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12588. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12589. // body a second time and appending a second Content-Encoding field line, so
  12590. // clients that decode one coding per listed value handed back raw gzip bytes.
  12591. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12592. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12593. Server svr;
  12594. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12595. // keeps the server from applying a coding of its own.
  12596. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12597. res.set_content(gzipped, "text/plain");
  12598. res.set_header("Content-Encoding", "gzip");
  12599. });
  12600. auto port = svr.bind_to_any_port(HOST);
  12601. thread t = thread([&]() { svr.listen_after_bind(); });
  12602. auto se = detail::scope_exit([&] {
  12603. svr.stop();
  12604. t.join();
  12605. ASSERT_FALSE(svr.is_running());
  12606. });
  12607. svr.wait_until_ready();
  12608. Client cli(HOST, port);
  12609. Headers headers = {{"Accept-Encoding", "gzip"}};
  12610. auto res = cli.Get("/pre-gzipped", headers);
  12611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12612. EXPECT_EQ(StatusCode::OK_200, res->status);
  12613. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12614. EXPECT_EQ("Hello World!", res->body);
  12615. }
  12616. // set_compress(false) sends every handler response as it is, buffered or
  12617. // streamed
  12618. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12619. const std::string text(1000, 'a');
  12620. Server svr;
  12621. svr.set_compress(false);
  12622. svr.Get("/buffered", [&](const Request &, Response &res) {
  12623. res.set_content(text, "text/plain");
  12624. });
  12625. svr.Get("/streamed", [&](const Request &, Response &res) {
  12626. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12627. sink.write(text.data(), text.size());
  12628. sink.done();
  12629. return true;
  12630. });
  12631. });
  12632. auto port = svr.bind_to_any_port(HOST);
  12633. ASSERT_LT(0, port);
  12634. thread t = thread([&] { svr.listen_after_bind(); });
  12635. auto se = detail::scope_exit([&] {
  12636. svr.stop();
  12637. t.join();
  12638. ASSERT_FALSE(svr.is_running());
  12639. });
  12640. svr.wait_until_ready();
  12641. Client cli(HOST, port);
  12642. cli.set_decompress(false);
  12643. for (auto path : {"/buffered", "/streamed"}) {
  12644. SCOPED_TRACE(path);
  12645. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12647. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12648. EXPECT_EQ(text, res->body);
  12649. }
  12650. }
  12651. // A chunked provider settles its coding where the headers are written and
  12652. // reuses it at write time. Both ends of that have to hold: a handler's own
  12653. // Content-Encoding suppresses the coding, and a response without one is still
  12654. // compressed as it always was.
  12655. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12656. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12657. const std::string plain = "Hello World! Hello World! Hello World!";
  12658. Server svr;
  12659. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12660. res.set_header("Content-Encoding", "gzip");
  12661. res.set_chunked_content_provider(
  12662. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12663. sink.write(gzipped.data(), gzipped.size());
  12664. sink.done();
  12665. return true;
  12666. });
  12667. });
  12668. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12669. res.set_chunked_content_provider(
  12670. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12671. sink.write(plain.data(), plain.size());
  12672. sink.done();
  12673. return true;
  12674. });
  12675. });
  12676. auto port = svr.bind_to_any_port(HOST);
  12677. thread t = thread([&]() { svr.listen_after_bind(); });
  12678. auto se = detail::scope_exit([&] {
  12679. svr.stop();
  12680. t.join();
  12681. ASSERT_FALSE(svr.is_running());
  12682. });
  12683. svr.wait_until_ready();
  12684. Client cli(HOST, port);
  12685. Headers headers = {{"Accept-Encoding", "gzip"}};
  12686. {
  12687. auto res = cli.Get("/pre-gzipped", headers);
  12688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12689. EXPECT_EQ(StatusCode::OK_200, res->status);
  12690. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12691. EXPECT_EQ("Hello World!", res->body);
  12692. }
  12693. {
  12694. auto res = cli.Get("/negotiated", headers);
  12695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12696. EXPECT_EQ(StatusCode::OK_200, res->status);
  12697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12698. EXPECT_EQ(plain, res->body);
  12699. }
  12700. }
  12701. #endif
  12702. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12703. // the same message as the comma-joined one, so both have to be read the same
  12704. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12705. // single gzip coding, and a body the sender says was encoded twice was handed
  12706. // back after one pass, still compressed but presented as decoded.
  12707. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12708. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12709. Server svr;
  12710. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12711. res.set_content(body, "image/jpeg");
  12712. res.headers.emplace("Content-Encoding", "gzip");
  12713. res.headers.emplace("Content-Encoding", "gzip");
  12714. });
  12715. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12716. res.set_content(body, "image/jpeg");
  12717. res.set_header("Content-Encoding", "gzip, gzip");
  12718. });
  12719. auto port = svr.bind_to_any_port(HOST);
  12720. thread t = thread([&]() { svr.listen_after_bind(); });
  12721. auto se = detail::scope_exit([&] {
  12722. svr.stop();
  12723. t.join();
  12724. ASSERT_FALSE(svr.is_running());
  12725. });
  12726. svr.wait_until_ready();
  12727. Client cli(HOST, port);
  12728. // Two codings is not something cpp-httplib decodes, so both representations
  12729. // take the pass-through path rather than one of them being gunzipped once.
  12730. for (const char *path : {"/split", "/joined"}) {
  12731. auto res = cli.Get(path);
  12732. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12733. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12734. EXPECT_EQ(body, res->body) << path;
  12735. }
  12736. }
  12737. // Regression test for DoS vulnerability: a malicious server sending a response
  12738. // without Content-Length header must not cause unbounded memory consumption on
  12739. // the client side. The client should stop reading after a reasonable limit,
  12740. // similar to the server-side set_payload_max_length protection.
  12741. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12742. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12743. #ifndef _WIN32
  12744. signal(SIGPIPE, SIG_IGN);
  12745. #endif
  12746. auto server_thread = std::thread([] {
  12747. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12748. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12749. default_socket_options(srv);
  12750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12752. sockaddr_in addr{};
  12753. addr.sin_family = AF_INET;
  12754. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12755. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12756. int opt = 1;
  12757. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12758. #ifdef _WIN32
  12759. reinterpret_cast<const char *>(&opt),
  12760. #else
  12761. &opt,
  12762. #endif
  12763. sizeof(opt));
  12764. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12765. ::listen(srv, 1);
  12766. sockaddr_in cli_addr{};
  12767. socklen_t cli_len = sizeof(cli_addr);
  12768. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12769. if (cli != INVALID_SOCKET) {
  12770. char buf[4096];
  12771. ::recv(cli, buf, sizeof(buf), 0);
  12772. // Malicious response: no Content-Length, no chunked encoding
  12773. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12774. "Connection: close\r\n"
  12775. "\r\n";
  12776. ::send(cli,
  12777. #ifdef _WIN32
  12778. static_cast<const char *>(response_header.c_str()),
  12779. static_cast<int>(response_header.size()),
  12780. #else
  12781. response_header.c_str(), response_header.size(),
  12782. #endif
  12783. 0);
  12784. // Send 10MB of data
  12785. std::string chunk(64 * 1024, 'A');
  12786. size_t total_sent = 0;
  12787. while (total_sent < MALICIOUS_DATA_SIZE) {
  12788. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12789. auto sent = ::send(cli,
  12790. #ifdef _WIN32
  12791. static_cast<const char *>(chunk.c_str()),
  12792. static_cast<int>(to_send),
  12793. #else
  12794. chunk.c_str(), to_send,
  12795. #endif
  12796. 0);
  12797. if (sent <= 0) break;
  12798. total_sent += static_cast<size_t>(sent);
  12799. }
  12800. detail::close_socket(cli);
  12801. }
  12802. detail::close_socket(srv);
  12803. });
  12804. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12805. size_t total_read = 0;
  12806. {
  12807. Client cli("127.0.0.1", PORT + 2);
  12808. cli.set_read_timeout(5, 0);
  12809. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12810. auto stream = cli.open_stream("GET", "/malicious");
  12811. ASSERT_TRUE(stream.is_valid());
  12812. char buffer[64 * 1024];
  12813. ssize_t n;
  12814. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12815. total_read += static_cast<size_t>(n);
  12816. }
  12817. } // StreamHandle and Client destroyed here, closing the socket
  12818. server_thread.join();
  12819. // With set_payload_max_length, the client must stop reading before consuming
  12820. // all 10MB. The read loop should be cut off at or near the configured limit.
  12821. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12822. << "Client read " << total_read << " bytes, exceeding the configured "
  12823. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12824. }
  12825. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12826. // the entire response body without truncation.
  12827. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12828. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12829. #ifndef _WIN32
  12830. signal(SIGPIPE, SIG_IGN);
  12831. #endif
  12832. auto server_thread = std::thread([] {
  12833. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12834. default_socket_options(srv);
  12835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12836. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12837. sockaddr_in addr{};
  12838. addr.sin_family = AF_INET;
  12839. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12840. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12841. int opt = 1;
  12842. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12843. #ifdef _WIN32
  12844. reinterpret_cast<const char *>(&opt),
  12845. #else
  12846. &opt,
  12847. #endif
  12848. sizeof(opt));
  12849. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12850. ::listen(srv, 1);
  12851. sockaddr_in cli_addr{};
  12852. socklen_t cli_len = sizeof(cli_addr);
  12853. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12854. if (cli != INVALID_SOCKET) {
  12855. char buf[4096];
  12856. ::recv(cli, buf, sizeof(buf), 0);
  12857. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12858. "Connection: close\r\n"
  12859. "\r\n";
  12860. ::send(cli,
  12861. #ifdef _WIN32
  12862. static_cast<const char *>(response_header.c_str()),
  12863. static_cast<int>(response_header.size()),
  12864. #else
  12865. response_header.c_str(), response_header.size(),
  12866. #endif
  12867. 0);
  12868. std::string chunk(64 * 1024, 'A');
  12869. size_t total_sent = 0;
  12870. while (total_sent < DATA_SIZE) {
  12871. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12872. auto sent = ::send(cli,
  12873. #ifdef _WIN32
  12874. static_cast<const char *>(chunk.c_str()),
  12875. static_cast<int>(to_send),
  12876. #else
  12877. chunk.c_str(), to_send,
  12878. #endif
  12879. 0);
  12880. if (sent <= 0) break;
  12881. total_sent += static_cast<size_t>(sent);
  12882. }
  12883. #ifdef _WIN32
  12884. ::shutdown(cli, SD_SEND);
  12885. #else
  12886. ::shutdown(cli, SHUT_WR);
  12887. #endif
  12888. // Drain until the client closes its end, ensuring all data is delivered
  12889. char drain[1024];
  12890. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12891. detail::close_socket(cli);
  12892. }
  12893. detail::close_socket(srv);
  12894. });
  12895. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12896. size_t total_read = 0;
  12897. {
  12898. Client cli("127.0.0.1", PORT + 2);
  12899. cli.set_read_timeout(5, 0);
  12900. cli.set_payload_max_length(0); // 0 means no limit
  12901. auto stream = cli.open_stream("GET", "/data");
  12902. ASSERT_TRUE(stream.is_valid());
  12903. char buffer[64 * 1024];
  12904. ssize_t n;
  12905. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12906. total_read += static_cast<size_t>(n);
  12907. }
  12908. }
  12909. server_thread.join();
  12910. EXPECT_EQ(total_read, DATA_SIZE)
  12911. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12912. << " bytes without truncation, but only read " << total_read << " bytes.";
  12913. }
  12914. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12915. // enormous Content-Length must not cause the client to pre-allocate a huge
  12916. // response body buffer. The reservation is capped at payload_max_length_, and
  12917. // the read itself fails when the body exceeds the limit.
  12918. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12919. #ifndef _WIN32
  12920. signal(SIGPIPE, SIG_IGN);
  12921. #endif
  12922. auto server_thread = std::thread([] {
  12923. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12924. default_socket_options(srv);
  12925. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12926. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12927. sockaddr_in addr{};
  12928. addr.sin_family = AF_INET;
  12929. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12930. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12931. int opt = 1;
  12932. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12933. #ifdef _WIN32
  12934. reinterpret_cast<const char *>(&opt),
  12935. #else
  12936. &opt,
  12937. #endif
  12938. sizeof(opt));
  12939. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12940. ::listen(srv, 1);
  12941. sockaddr_in cli_addr{};
  12942. socklen_t cli_len = sizeof(cli_addr);
  12943. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12944. if (cli != INVALID_SOCKET) {
  12945. char buf[4096];
  12946. ::recv(cli, buf, sizeof(buf), 0);
  12947. // Malicious response: claim a 20GB body but send only a tiny payload.
  12948. std::string response = "HTTP/1.1 200 OK\r\n"
  12949. "Content-Length: 20000000000\r\n"
  12950. "\r\n"
  12951. "abc";
  12952. ::send(cli,
  12953. #ifdef _WIN32
  12954. static_cast<const char *>(response.c_str()),
  12955. static_cast<int>(response.size()),
  12956. #else
  12957. response.c_str(), response.size(),
  12958. #endif
  12959. 0);
  12960. detail::close_socket(cli);
  12961. }
  12962. detail::close_socket(srv);
  12963. });
  12964. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12965. {
  12966. Client cli("127.0.0.1", PORT + 2);
  12967. cli.set_read_timeout(5, 0);
  12968. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12969. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12970. // (server claims more bytes than payload_max_length permits), but it must
  12971. // not exhaust memory before getting there.
  12972. auto res = cli.Get("/malicious");
  12973. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12974. }
  12975. server_thread.join();
  12976. }
  12977. // Verify that content_receiver bypasses the default payload_max_length,
  12978. // allowing streaming downloads larger than 100MB without requiring an explicit
  12979. // set_payload_max_length call.
  12980. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12981. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12982. #ifndef _WIN32
  12983. signal(SIGPIPE, SIG_IGN);
  12984. #endif
  12985. auto server_thread = std::thread([] {
  12986. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12987. default_socket_options(srv);
  12988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12990. sockaddr_in addr{};
  12991. addr.sin_family = AF_INET;
  12992. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12994. int opt = 1;
  12995. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12996. #ifdef _WIN32
  12997. reinterpret_cast<const char *>(&opt),
  12998. #else
  12999. &opt,
  13000. #endif
  13001. sizeof(opt));
  13002. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13003. ::listen(srv, 1);
  13004. sockaddr_in cli_addr{};
  13005. socklen_t cli_len = sizeof(cli_addr);
  13006. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13007. if (cli != INVALID_SOCKET) {
  13008. char buf[4096];
  13009. ::recv(cli, buf, sizeof(buf), 0);
  13010. // Response with Content-Length larger than default 100MB limit
  13011. auto content_length = std::to_string(DATA_SIZE);
  13012. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13013. "Content-Length: " +
  13014. content_length +
  13015. "\r\n"
  13016. "Connection: close\r\n"
  13017. "\r\n";
  13018. ::send(cli,
  13019. #ifdef _WIN32
  13020. static_cast<const char *>(response_header.c_str()),
  13021. static_cast<int>(response_header.size()),
  13022. #else
  13023. response_header.c_str(), response_header.size(),
  13024. #endif
  13025. 0);
  13026. std::string chunk(64 * 1024, 'A');
  13027. size_t total_sent = 0;
  13028. while (total_sent < DATA_SIZE) {
  13029. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13030. auto sent = ::send(cli,
  13031. #ifdef _WIN32
  13032. static_cast<const char *>(chunk.c_str()),
  13033. static_cast<int>(to_send),
  13034. #else
  13035. chunk.c_str(), to_send,
  13036. #endif
  13037. 0);
  13038. if (sent <= 0) break;
  13039. total_sent += static_cast<size_t>(sent);
  13040. }
  13041. detail::close_socket(cli);
  13042. }
  13043. detail::close_socket(srv);
  13044. });
  13045. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13046. size_t total_received = 0;
  13047. {
  13048. Client cli("127.0.0.1", PORT + 2);
  13049. cli.set_read_timeout(10, 0);
  13050. // Do NOT call set_payload_max_length — use the default 100MB limit
  13051. auto res =
  13052. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13053. total_received += data_length;
  13054. return true;
  13055. });
  13056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13057. EXPECT_EQ(StatusCode::OK_200, res->status);
  13058. }
  13059. server_thread.join();
  13060. EXPECT_EQ(total_received, DATA_SIZE)
  13061. << "With content_receiver, the client should read all " << DATA_SIZE
  13062. << " bytes despite the default 100MB payload_max_length, but only read "
  13063. << total_received << " bytes.";
  13064. }
  13065. // Verify that an explicit set_payload_max_length smaller than the response is
  13066. // enforced even when a content_receiver is used.
  13067. TEST(ClientVulnerabilityTest,
  13068. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13069. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13070. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13071. #ifndef _WIN32
  13072. signal(SIGPIPE, SIG_IGN);
  13073. #endif
  13074. auto server_thread = std::thread([] {
  13075. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13076. default_socket_options(srv);
  13077. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13078. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13079. sockaddr_in addr{};
  13080. addr.sin_family = AF_INET;
  13081. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13082. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13083. int opt = 1;
  13084. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13085. #ifdef _WIN32
  13086. reinterpret_cast<const char *>(&opt),
  13087. #else
  13088. &opt,
  13089. #endif
  13090. sizeof(opt));
  13091. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13092. ::listen(srv, 1);
  13093. sockaddr_in cli_addr{};
  13094. socklen_t cli_len = sizeof(cli_addr);
  13095. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13096. if (cli != INVALID_SOCKET) {
  13097. char buf[4096];
  13098. ::recv(cli, buf, sizeof(buf), 0);
  13099. auto content_length = std::to_string(DATA_SIZE);
  13100. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13101. "Content-Length: " +
  13102. content_length +
  13103. "\r\n"
  13104. "Connection: close\r\n"
  13105. "\r\n";
  13106. ::send(cli,
  13107. #ifdef _WIN32
  13108. static_cast<const char *>(response_header.c_str()),
  13109. static_cast<int>(response_header.size()),
  13110. #else
  13111. response_header.c_str(), response_header.size(),
  13112. #endif
  13113. 0);
  13114. std::string chunk(64 * 1024, 'A');
  13115. size_t total_sent = 0;
  13116. while (total_sent < DATA_SIZE) {
  13117. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13118. auto sent = ::send(cli,
  13119. #ifdef _WIN32
  13120. static_cast<const char *>(chunk.c_str()),
  13121. static_cast<int>(to_send),
  13122. #else
  13123. chunk.c_str(), to_send,
  13124. #endif
  13125. 0);
  13126. if (sent <= 0) break;
  13127. total_sent += static_cast<size_t>(sent);
  13128. }
  13129. detail::close_socket(cli);
  13130. }
  13131. detail::close_socket(srv);
  13132. });
  13133. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13134. size_t total_received = 0;
  13135. {
  13136. Client cli("127.0.0.1", PORT + 2);
  13137. cli.set_read_timeout(10, 0);
  13138. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13139. auto res =
  13140. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13141. total_received += data_length;
  13142. return true;
  13143. });
  13144. // Should fail because 200MB exceeds the explicit 150MB limit
  13145. EXPECT_FALSE(res);
  13146. }
  13147. server_thread.join();
  13148. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13149. << "Client with content_receiver should respect the explicit "
  13150. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13151. << total_received << " bytes.";
  13152. }
  13153. // Verify that an explicit set_payload_max_length larger than the response
  13154. // allows the content_receiver to read all data successfully.
  13155. TEST(ClientVulnerabilityTest,
  13156. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13157. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13158. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13159. #ifndef _WIN32
  13160. signal(SIGPIPE, SIG_IGN);
  13161. #endif
  13162. auto server_thread = std::thread([] {
  13163. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13164. default_socket_options(srv);
  13165. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13166. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13167. sockaddr_in addr{};
  13168. addr.sin_family = AF_INET;
  13169. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13170. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13171. int opt = 1;
  13172. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13173. #ifdef _WIN32
  13174. reinterpret_cast<const char *>(&opt),
  13175. #else
  13176. &opt,
  13177. #endif
  13178. sizeof(opt));
  13179. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13180. ::listen(srv, 1);
  13181. sockaddr_in cli_addr{};
  13182. socklen_t cli_len = sizeof(cli_addr);
  13183. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13184. if (cli != INVALID_SOCKET) {
  13185. char buf[4096];
  13186. ::recv(cli, buf, sizeof(buf), 0);
  13187. auto content_length = std::to_string(DATA_SIZE);
  13188. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13189. "Content-Length: " +
  13190. content_length +
  13191. "\r\n"
  13192. "Connection: close\r\n"
  13193. "\r\n";
  13194. ::send(cli,
  13195. #ifdef _WIN32
  13196. static_cast<const char *>(response_header.c_str()),
  13197. static_cast<int>(response_header.size()),
  13198. #else
  13199. response_header.c_str(), response_header.size(),
  13200. #endif
  13201. 0);
  13202. std::string chunk(64 * 1024, 'A');
  13203. size_t total_sent = 0;
  13204. while (total_sent < DATA_SIZE) {
  13205. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13206. auto sent = ::send(cli,
  13207. #ifdef _WIN32
  13208. static_cast<const char *>(chunk.c_str()),
  13209. static_cast<int>(to_send),
  13210. #else
  13211. chunk.c_str(), to_send,
  13212. #endif
  13213. 0);
  13214. if (sent <= 0) break;
  13215. total_sent += static_cast<size_t>(sent);
  13216. }
  13217. #ifdef _WIN32
  13218. ::shutdown(cli, SD_SEND);
  13219. #else
  13220. ::shutdown(cli, SHUT_WR);
  13221. #endif
  13222. char drain[1024];
  13223. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13224. detail::close_socket(cli);
  13225. }
  13226. detail::close_socket(srv);
  13227. });
  13228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13229. size_t total_received = 0;
  13230. {
  13231. Client cli("127.0.0.1", PORT + 2);
  13232. cli.set_read_timeout(10, 0);
  13233. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13234. auto res =
  13235. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13236. total_received += data_length;
  13237. return true;
  13238. });
  13239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13240. EXPECT_EQ(StatusCode::OK_200, res->status);
  13241. }
  13242. server_thread.join();
  13243. EXPECT_EQ(total_received, DATA_SIZE)
  13244. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13245. << " bytes (larger than " << DATA_SIZE
  13246. << " bytes response), content_receiver should read all data, but only "
  13247. "read "
  13248. << total_received << " bytes.";
  13249. }
  13250. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13251. // Regression test for "zip bomb" attack on the client side: a malicious server
  13252. // sends a small gzip-compressed response that decompresses to a huge payload.
  13253. // The client must enforce payload_max_length on the decompressed size.
  13254. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13255. constexpr size_t DECOMPRESSED_SIZE =
  13256. 10 * 1024 * 1024; // 10MB after decompression
  13257. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13258. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13259. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13260. std::string compressed;
  13261. {
  13262. httplib::detail::gzip_compressor compressor;
  13263. bool ok =
  13264. compressor.compress(uncompressed.data(), uncompressed.size(),
  13265. /*last=*/true, [&](const char *buf, size_t len) {
  13266. compressed.append(buf, len);
  13267. return true;
  13268. });
  13269. ASSERT_TRUE(ok);
  13270. }
  13271. // Sanity: compressed data should be much smaller than the decompressed size
  13272. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13273. #ifndef _WIN32
  13274. signal(SIGPIPE, SIG_IGN);
  13275. #endif
  13276. // Set up the listening socket in the main thread so the server is guaranteed
  13277. // to be ready before the client connects (eliminates race condition).
  13278. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13279. default_socket_options(srv);
  13280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13281. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13282. sockaddr_in addr{};
  13283. addr.sin_family = AF_INET;
  13284. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13285. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13286. int opt = 1;
  13287. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13288. #ifdef _WIN32
  13289. reinterpret_cast<const char *>(&opt),
  13290. #else
  13291. &opt,
  13292. #endif
  13293. sizeof(opt));
  13294. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13295. ASSERT_EQ(0, ::listen(srv, 1));
  13296. auto server_thread = std::thread([&compressed, srv] {
  13297. sockaddr_in cli_addr{};
  13298. socklen_t cli_len = sizeof(cli_addr);
  13299. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13300. if (cli != INVALID_SOCKET) {
  13301. // Read the full HTTP request (until \r\n\r\n)
  13302. char buf[4096];
  13303. size_t total = 0;
  13304. while (total < sizeof(buf)) {
  13305. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13306. if (n <= 0) break;
  13307. total += static_cast<size_t>(n);
  13308. // Check for end of headers
  13309. if (total >= 4) {
  13310. std::string req(buf, total);
  13311. if (req.find("\r\n\r\n") != std::string::npos) break;
  13312. }
  13313. }
  13314. // Malicious response: gzip-compressed body, no Content-Length
  13315. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13316. "Content-Encoding: gzip\r\n"
  13317. "Connection: close\r\n"
  13318. "\r\n";
  13319. ::send(cli,
  13320. #ifdef _WIN32
  13321. static_cast<const char *>(response_header.c_str()),
  13322. static_cast<int>(response_header.size()),
  13323. #else
  13324. response_header.c_str(), response_header.size(),
  13325. #endif
  13326. 0);
  13327. // Send the compressed payload (small on the wire, huge when decompressed)
  13328. size_t total_sent = 0;
  13329. while (total_sent < compressed.size()) {
  13330. auto to_send = std::min(compressed.size() - total_sent,
  13331. static_cast<size_t>(64 * 1024));
  13332. auto sent =
  13333. ::send(cli,
  13334. #ifdef _WIN32
  13335. static_cast<const char *>(compressed.c_str() + total_sent),
  13336. static_cast<int>(to_send),
  13337. #else
  13338. compressed.c_str() + total_sent, to_send,
  13339. #endif
  13340. 0);
  13341. if (sent <= 0) break;
  13342. total_sent += static_cast<size_t>(sent);
  13343. }
  13344. detail::close_socket(cli);
  13345. }
  13346. });
  13347. auto se = detail::scope_exit([&] {
  13348. detail::close_socket(srv);
  13349. server_thread.join();
  13350. });
  13351. size_t total_decompressed = 0;
  13352. {
  13353. Client cli("127.0.0.1", PORT + 3);
  13354. cli.set_read_timeout(5, 0);
  13355. cli.set_decompress(true);
  13356. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13357. auto stream = cli.open_stream("GET", "/zipbomb");
  13358. ASSERT_TRUE(stream.is_valid());
  13359. char buffer[64 * 1024];
  13360. ssize_t n;
  13361. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13362. total_decompressed += static_cast<size_t>(n);
  13363. }
  13364. }
  13365. // The decompressed size must be capped by payload_max_length. Without
  13366. // protection, the client would decompress the full 10MB from a tiny
  13367. // compressed payload, enabling a zip bomb DoS attack.
  13368. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13369. << "Client decompressed " << total_decompressed
  13370. << " bytes from a gzip response. The decompressed size should be "
  13371. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13372. }
  13373. #endif
  13374. TEST(HostAndPortPropertiesTest, NoSSL) {
  13375. httplib::Client cli("www.google.com", 1234);
  13376. ASSERT_EQ("www.google.com", cli.host());
  13377. ASSERT_EQ(1234, cli.port());
  13378. }
  13379. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13380. httplib::Client cli("www.google.com:1234");
  13381. ASSERT_EQ("www.google.com", cli.host());
  13382. ASSERT_EQ(1234, cli.port());
  13383. }
  13384. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13385. // Port number that overflows int — should not crash, client becomes invalid
  13386. httplib::Client cli("http://www.google.com:99999999999999999999");
  13387. ASSERT_FALSE(cli.is_valid());
  13388. }
  13389. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13390. // Port 99999 exceeds valid range (1-65535) — should not crash
  13391. httplib::Client cli("http://www.google.com:99999");
  13392. ASSERT_FALSE(cli.is_valid());
  13393. auto res = cli.Get("/");
  13394. EXPECT_FALSE(res);
  13395. EXPECT_EQ(Error::Connection, res.error());
  13396. }
  13397. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13398. httplib::Client cli("http://user:pass@localhost:1234");
  13399. ASSERT_FALSE(cli.is_valid());
  13400. EXPECT_FALSE(cli.Get("/"));
  13401. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13402. }
  13403. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13404. httplib::Client cli("http://www.google.com:80abc");
  13405. ASSERT_FALSE(cli.is_valid());
  13406. }
  13407. #ifdef CPPHTTPLIB_SSL_ENABLED
  13408. TEST(HostAndPortPropertiesTest, SSL) {
  13409. httplib::SSLClient cli("www.google.com");
  13410. ASSERT_EQ("www.google.com", cli.host());
  13411. ASSERT_EQ(443, cli.port());
  13412. }
  13413. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13414. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13415. std::string cert;
  13416. read_file(CA_CERT_FILE, cert);
  13417. httplib::SSLClient httplib_client("www.google.com");
  13418. // Load CA store first time
  13419. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13420. // Load CA store second time (update)
  13421. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13422. // Verify client is still valid and can make connections
  13423. httplib_client.enable_server_certificate_verification(true);
  13424. auto res = httplib_client.Get("/");
  13425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13426. // Google may return 200 or 301 depending on various factors
  13427. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13428. res->status == StatusCode::MovedPermanently_301);
  13429. }
  13430. TEST(SSLClientTest, ServerNameIndication_Online) {
  13431. auto host = "httpbingo.org";
  13432. auto path = std::string{"/get"};
  13433. SSLClient cli(host, 443);
  13434. auto res = cli.Get(path);
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. ASSERT_EQ(StatusCode::OK_200, res->status);
  13437. }
  13438. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13439. // Use a site that will cause SSL verification failure due to self-signed cert
  13440. SSLClient cli("self-signed.badssl.com", 443);
  13441. cli.enable_server_certificate_verification(true);
  13442. auto res = cli.Get("/");
  13443. ASSERT_TRUE(!res);
  13444. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13445. // Verify backend error is captured for SSLServerVerification
  13446. // This occurs when certificate verification fails
  13447. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13448. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13449. EXPECT_NE(0UL, res.ssl_backend_error());
  13450. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13451. res.ssl_error());
  13452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13453. #if !defined(_WIN32) || \
  13454. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13455. // On non-Windows or when Windows Schannel is disabled, the error comes
  13456. // from OpenSSL's verification
  13457. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13458. res.ssl_backend_error());
  13459. #endif
  13460. #endif
  13461. }
  13462. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13463. // Use a site where hostname doesn't match the certificate
  13464. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13465. SSLClient cli("wrong.host.badssl.com", 443);
  13466. cli.enable_server_certificate_verification(true);
  13467. cli.enable_server_hostname_verification(true);
  13468. auto res = cli.Get("/");
  13469. ASSERT_TRUE(!res);
  13470. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13471. // Verify backend error is captured for hostname verification failure
  13472. EXPECT_NE(0UL, res.ssl_backend_error());
  13473. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13474. res.ssl_error());
  13475. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13476. #if !defined(_WIN32) || \
  13477. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13478. // On non-Windows or when Windows Schannel is disabled, the error comes
  13479. // from OpenSSL's hostname verification
  13480. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13481. res.ssl_backend_error());
  13482. #endif
  13483. #endif
  13484. }
  13485. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13486. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13487. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13488. SSLClient cli("www.google.com", 443);
  13489. cli.enable_server_certificate_verification(true);
  13490. auto res = cli.Get("/");
  13491. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13492. }
  13493. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13494. SSLClient cli("www.google.com", 443);
  13495. cli.enable_server_certificate_verification(true);
  13496. cli.enable_windows_certificate_verification(false);
  13497. auto res = cli.Get("/");
  13498. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13499. }
  13500. // The server sends an intermediate cross-signed by a root Windows trusts,
  13501. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13502. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13503. SSLClient cli("accounts.spotify.com", 443);
  13504. auto res = cli.Get("/");
  13505. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13506. << " ssl_backend_error=" << res.ssl_backend_error();
  13507. }
  13508. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13509. // policy status, which no backend reports for a self-signed certificate.
  13510. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13511. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13512. ASSERT_TRUE(svr.is_valid());
  13513. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13514. auto se = detail::scope_exit([&] {
  13515. svr.stop();
  13516. t.join();
  13517. ASSERT_FALSE(svr.is_running());
  13518. });
  13519. svr.wait_until_ready();
  13520. SSLClient cli("127.0.0.1", PORT);
  13521. cli.set_connection_timeout(30);
  13522. auto res = cli.Get("/");
  13523. ASSERT_FALSE(res);
  13524. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13525. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13526. }
  13527. #endif
  13528. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13529. Client cli("https://google.com");
  13530. auto res = cli.Get("/");
  13531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13532. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13533. }
  13534. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13535. SSLClient cli("google.com");
  13536. cli.set_ca_cert_path(CA_CERT_FILE);
  13537. auto res = cli.Get("/");
  13538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13539. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13540. }
  13541. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13542. SSLClient cli("google.com");
  13543. cli.enable_server_certificate_verification(true);
  13544. cli.set_ca_cert_path("hello");
  13545. auto res = cli.Get("/");
  13546. ASSERT_TRUE(!res);
  13547. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13548. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13549. // should be set
  13550. EXPECT_EQ(0, res.ssl_error());
  13551. // Verify backend error is captured for SSLLoadingCerts
  13552. // This error occurs when loading CA certificates fails
  13553. EXPECT_NE(0UL, res.ssl_backend_error());
  13554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13555. // OpenSSL specific error codes:
  13556. // > openssl errstr 0x80000002
  13557. // error:80000002:system library::No such file or directory
  13558. // > openssl errstr 0xA000126
  13559. // error:0A000126:SSL routines::unexpected eof while reading
  13560. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13561. res.ssl_backend_error() == 0xA000126);
  13562. #endif
  13563. }
  13564. TEST(SSLClientTest, ServerCertificateVerification4) {
  13565. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. svr.Get("/test", [&](const Request &, Response &res) {
  13568. res.set_content("test", "text/plain");
  13569. svr.stop();
  13570. ASSERT_TRUE(true);
  13571. });
  13572. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13573. auto se = detail::scope_exit([&] {
  13574. t.join();
  13575. ASSERT_FALSE(svr.is_running());
  13576. });
  13577. svr.wait_until_ready();
  13578. SSLClient cli("127.0.0.1", PORT);
  13579. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13580. cli.enable_server_certificate_verification(true);
  13581. cli.set_connection_timeout(30);
  13582. auto res = cli.Get("/test");
  13583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13584. ASSERT_EQ(StatusCode::OK_200, res->status);
  13585. }
  13586. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13587. std::string cert;
  13588. read_file(CA_CERT_FILE, cert);
  13589. SSLClient cli("google.com");
  13590. cli.load_ca_cert_store(cert.data(), cert.size());
  13591. const auto res = cli.Get("/");
  13592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13593. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13594. }
  13595. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13596. // clang-format off
  13597. static constexpr char cert[] =
  13598. "GlobalSign Root CA\n"
  13599. "==================\n"
  13600. "-----BEGIN CERTIFICATE-----\n"
  13601. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13602. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13603. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13604. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13605. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13606. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13607. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13608. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13609. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13610. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13611. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13612. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13613. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13614. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13615. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13616. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13617. "-----END CERTIFICATE-----\n";
  13618. // clang-format on
  13619. SSLClient cli("google.com");
  13620. cli.load_ca_cert_store(cert, sizeof(cert));
  13621. const auto res = cli.Get("/");
  13622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13623. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13624. }
  13625. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13626. SSLClient cli("www.youtube.com");
  13627. cli.set_ca_cert_path(CA_CERT_FILE);
  13628. cli.enable_server_certificate_verification(true);
  13629. cli.set_follow_location(true);
  13630. auto res = cli.Get("/");
  13631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13632. ASSERT_EQ(StatusCode::OK_200, res->status);
  13633. }
  13634. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13635. SSLClient cli("wWw.YouTube.Com");
  13636. cli.set_ca_cert_path(CA_CERT_FILE);
  13637. cli.enable_server_certificate_verification(true);
  13638. cli.enable_server_hostname_verification(true);
  13639. cli.set_follow_location(true);
  13640. auto res = cli.Get("/");
  13641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13642. ASSERT_EQ(StatusCode::OK_200, res->status);
  13643. }
  13644. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13645. SSLClient cli("gOoGlE.COm");
  13646. cli.enable_server_certificate_verification(true);
  13647. cli.enable_server_hostname_verification(true);
  13648. cli.set_follow_location(true);
  13649. auto res = cli.Get("/");
  13650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13651. ASSERT_EQ(StatusCode::OK_200, res->status);
  13652. }
  13653. TEST(SSLClientTest, Issue2004_Online) {
  13654. Client client("https://google.com");
  13655. client.set_follow_location(true);
  13656. auto res = client.Get("/");
  13657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13658. ASSERT_EQ(StatusCode::OK_200, res->status);
  13659. auto body = res->body;
  13660. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13661. }
  13662. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13663. // Create SSLClient with invalid cert/key to make is_valid() return false
  13664. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13665. "nonexistent_key.pem");
  13666. // is_valid() should be false due to cert loading failure
  13667. ASSERT_FALSE(cli.is_valid());
  13668. auto res = cli.Get("/");
  13669. ASSERT_FALSE(res);
  13670. EXPECT_EQ(Error::SSLConnection, res.error());
  13671. }
  13672. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13673. // Test for Issue #2251: SSL error not properly reported when client cert
  13674. // and key paths are swapped or mismatched
  13675. // This simulates the scenario where user accidentally swaps the cert and key
  13676. // files
  13677. // Using client cert file as private key and vice versa (completely wrong)
  13678. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13679. // Should fail validation due to cert/key mismatch
  13680. ASSERT_FALSE(cli.is_valid());
  13681. // Attempt to make a request should fail with proper error
  13682. auto res = cli.Get("/");
  13683. ASSERT_FALSE(res);
  13684. EXPECT_EQ(Error::SSLConnection, res.error());
  13685. // SSL error should be recorded in the Result object (this is the key fix for
  13686. // Issue #2251)
  13687. auto backend_error = res.ssl_backend_error();
  13688. EXPECT_NE(0u, backend_error);
  13689. }
  13690. // Tests cert/key mismatch detection at the TLS context level
  13691. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13692. // Test that using mismatched cert/key causes connection failure.
  13693. // We verify this at the SSLClient level rather than through internal
  13694. // TLS API functions.
  13695. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13696. cli.enable_server_certificate_verification(false);
  13697. cli.set_connection_timeout(2);
  13698. // The mismatch should cause a connection or handshake error
  13699. auto res = cli.Get("/test");
  13700. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13701. // Either way, the request should fail
  13702. EXPECT_FALSE(res);
  13703. }
  13704. #endif
  13705. #if 0
  13706. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13707. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13708. ASSERT_TRUE(cli != nullptr);
  13709. cli->set_address_family(AF_INET6);
  13710. cli->set_interface("en0");
  13711. auto res = cli->Get("/get");
  13712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13713. ASSERT_EQ(StatusCode::OK_200, res->status);
  13714. }
  13715. #endif
  13716. // Client certificate tests - work with all TLS backends
  13717. #ifdef CPPHTTPLIB_SSL_ENABLED
  13718. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13719. void ClientCertPresent(
  13720. const std::string &client_cert_file,
  13721. const std::string &client_private_key_file,
  13722. const std::string &client_encrypted_private_key_pass = std::string(),
  13723. const ClientCertServerSetup &setup = nullptr) {
  13724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13725. ASSERT_TRUE(svr.is_valid());
  13726. if (setup) { setup(svr); }
  13727. svr.Get("/test", [&](const Request &req, Response &res) {
  13728. res.set_content("test", "text/plain");
  13729. auto cert = req.peer_cert();
  13730. ASSERT_TRUE(static_cast<bool>(cert));
  13731. std::string common_name = cert.subject_cn();
  13732. EXPECT_EQ("Common Name", common_name);
  13733. });
  13734. auto port = svr.bind_to_any_port(HOST);
  13735. ASSERT_LT(0, port);
  13736. thread t = thread([&]() { svr.listen_after_bind(); });
  13737. auto se = detail::scope_exit([&] {
  13738. svr.stop();
  13739. t.join();
  13740. ASSERT_FALSE(svr.is_running());
  13741. });
  13742. svr.wait_until_ready();
  13743. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13744. client_encrypted_private_key_pass);
  13745. cli.enable_server_certificate_verification(false);
  13746. cli.set_connection_timeout(30);
  13747. auto res = cli.Get("/test");
  13748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13749. ASSERT_EQ(StatusCode::OK_200, res->status);
  13750. }
  13751. TEST(SSLClientServerTest, ClientCertPresent) {
  13752. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13753. }
  13754. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13755. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13756. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13757. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13758. }
  13759. // Expects svr, which must require client certificates, to reject a client
  13760. // that has none
  13761. void RejectsClientWithoutCert(SSLServer &svr) {
  13762. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13763. auto port = svr.bind_to_any_port(HOST);
  13764. ASSERT_LT(0, port);
  13765. thread t = thread([&]() { svr.listen_after_bind(); });
  13766. auto se = detail::scope_exit([&] {
  13767. svr.stop();
  13768. t.join();
  13769. ASSERT_FALSE(svr.is_running());
  13770. });
  13771. svr.wait_until_ready();
  13772. SSLClient cli(HOST, port);
  13773. cli.set_connection_timeout(30);
  13774. // Skip the server certificate check, so that the request fails because the
  13775. // client certificate is missing rather than because cert.pem is not trusted
  13776. cli.enable_server_certificate_verification(false);
  13777. auto res = cli.Get("/test");
  13778. ASSERT_FALSE(res);
  13779. // The server rejects the client during the handshake, or on TLS 1.3 right
  13780. // after it, which the client notices on its first write or read
  13781. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13782. res.error() == Error::Write || res.error() == Error::Read)
  13783. << to_string(res.error());
  13784. if (res.error() == Error::SSLConnection) {
  13785. EXPECT_NE(0UL, res.ssl_backend_error());
  13786. }
  13787. // A rejection noticed on the write keeps the TLS error the write hit
  13788. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13789. }
  13790. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13792. ASSERT_TRUE(svr.is_valid());
  13793. if (setup) { setup(svr); }
  13794. RejectsClientWithoutCert(svr);
  13795. }
  13796. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13797. // A server that requires client certificates must keep requiring them after
  13798. // setup changes it, and keep accepting a client that has one
  13799. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13800. ClientCertMissing(setup);
  13801. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13802. setup);
  13803. }
  13804. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13805. ClientCertStillRequired([](SSLServer &svr) {
  13806. ASSERT_TRUE(tls::set_verify_callback(
  13807. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13808. });
  13809. }
  13810. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13811. ClientCertStillRequired([](SSLServer &svr) {
  13812. ASSERT_TRUE(tls::set_verify_callback(
  13813. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13814. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13815. });
  13816. }
  13817. // The client verifies the server certificate during the handshake, so a
  13818. // server that fails the check never gets the client certificate, even when a
  13819. // verifier of the client's own accepts it
  13820. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13821. struct Case {
  13822. const char *trusted_ca;
  13823. const char *host;
  13824. Error error;
  13825. };
  13826. // cert2.pem names localhost: the first client does not trust it, and the
  13827. // second trusts it but asks for another name
  13828. for (const auto &c :
  13829. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13830. Case{SERVER_CERT2_FILE, "example.com",
  13831. Error::SSLServerHostnameVerification}}) {
  13832. for (auto with_verifier : {false, true}) {
  13833. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13834. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13835. CLIENT_CA_CERT_FILE);
  13836. ASSERT_TRUE(svr.is_valid());
  13837. std::atomic<bool> got_client_cert{false};
  13838. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13839. [&](const tls::VerifyContext &) {
  13840. got_client_cert = true;
  13841. return true;
  13842. }));
  13843. auto port = svr.bind_to_any_port("127.0.0.1");
  13844. ASSERT_LT(0, port);
  13845. thread t = thread([&] { svr.listen_after_bind(); });
  13846. svr.wait_until_ready();
  13847. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13848. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13849. cli.set_ca_cert_path(c.trusted_ca);
  13850. if (with_verifier) {
  13851. cli.set_server_certificate_verifier(
  13852. [](const tls::VerifyContext &) { return true; });
  13853. }
  13854. auto res = cli.Get("/");
  13855. EXPECT_FALSE(res);
  13856. EXPECT_EQ(c.error, res.error());
  13857. svr.stop();
  13858. t.join();
  13859. EXPECT_FALSE(got_client_cert);
  13860. }
  13861. }
  13862. }
  13863. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13864. std::string cert_pem, key_pem, ca_pem;
  13865. read_file(SERVER_CERT_FILE, cert_pem);
  13866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13867. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13868. ASSERT_TRUE(
  13869. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13870. }
  13871. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13873. ASSERT_TRUE(svr.is_valid());
  13874. UpdateCertsPemWithClientCA(svr);
  13875. RejectsClientWithoutCert(svr);
  13876. }
  13877. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13878. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13879. }
  13880. // A TLS error from one request must not show up in a later request's Result
  13881. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13883. ASSERT_TRUE(svr.is_valid());
  13884. svr.Get("/test", [](const Request &, Response &res) {
  13885. res.set_content("test", "text/plain");
  13886. });
  13887. auto port = svr.bind_to_any_port(HOST);
  13888. ASSERT_LT(0, port);
  13889. thread t = thread([&]() { svr.listen_after_bind(); });
  13890. auto se = detail::scope_exit([&] {
  13891. svr.stop();
  13892. t.join();
  13893. ASSERT_FALSE(svr.is_running());
  13894. });
  13895. svr.wait_until_ready();
  13896. SSLClient cli(HOST, port);
  13897. cli.set_connection_timeout(30);
  13898. cli.enable_server_hostname_verification(false);
  13899. // cert.pem is not trusted, so the handshake fails
  13900. ASSERT_FALSE(cli.Get("/test"));
  13901. cli.enable_server_certificate_verification(false);
  13902. auto res = cli.Get("/test");
  13903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13904. EXPECT_EQ(0, res.ssl_error());
  13905. EXPECT_EQ(0UL, res.ssl_backend_error());
  13906. }
  13907. // PEM memory-based constructor tests (works with all TLS backends).
  13908. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13909. // terminator after it.
  13910. void PemMemoryClientCertPresent(
  13911. const std::string &client_cert_file,
  13912. const std::string &client_private_key_file,
  13913. const std::string &client_encrypted_private_key_pass = std::string(),
  13914. bool exact_size = false) {
  13915. // Read PEM files into memory
  13916. std::string server_cert_pem, server_key_pem;
  13917. std::string client_ca_pem;
  13918. std::string client_cert_pem, client_key_pem;
  13919. read_file(SERVER_CERT_FILE, server_cert_pem);
  13920. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13921. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13922. read_file(client_cert_file, client_cert_pem);
  13923. read_file(client_private_key_file, client_key_pem);
  13924. std::list<std::vector<char>> exact_copies;
  13925. auto data = [&](const std::string &pem) -> const char * {
  13926. if (!exact_size) { return pem.c_str(); }
  13927. exact_copies.emplace_back(pem.begin(), pem.end());
  13928. return exact_copies.back().data();
  13929. };
  13930. // Create server with PEM memory
  13931. SSLServer::PemMemory server_pem = {
  13932. data(server_cert_pem),
  13933. server_cert_pem.size(),
  13934. data(server_key_pem),
  13935. server_key_pem.size(),
  13936. data(client_ca_pem),
  13937. client_ca_pem.size(),
  13938. nullptr // no password for server key
  13939. };
  13940. SSLServer svr(server_pem);
  13941. ASSERT_TRUE(svr.is_valid());
  13942. svr.Get("/test", [&](const Request &req, Response &res) {
  13943. res.set_content("test", "text/plain");
  13944. auto cert = req.peer_cert();
  13945. ASSERT_TRUE(static_cast<bool>(cert));
  13946. EXPECT_EQ("Common Name", cert.subject_cn());
  13947. });
  13948. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13949. auto se = detail::scope_exit([&] {
  13950. svr.stop();
  13951. t.join();
  13952. ASSERT_FALSE(svr.is_running());
  13953. });
  13954. svr.wait_until_ready();
  13955. // Create client with PEM memory
  13956. const char *password = client_encrypted_private_key_pass.empty()
  13957. ? nullptr
  13958. : client_encrypted_private_key_pass.c_str();
  13959. SSLClient::PemMemory client_pem = {
  13960. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13961. client_key_pem.size(), password};
  13962. SSLClient cli(HOST, PORT, client_pem);
  13963. cli.enable_server_certificate_verification(false);
  13964. cli.set_connection_timeout(30);
  13965. auto res = cli.Get("/test");
  13966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13967. ASSERT_EQ(StatusCode::OK_200, res->status);
  13968. }
  13969. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13970. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13971. }
  13972. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13973. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13974. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13975. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13976. }
  13977. // A server built from PEM memory with a client CA requires client certificates,
  13978. // also when the CA is a NUL-terminated string passed with a length of 0
  13979. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13980. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13981. read_file(SERVER_CERT_FILE, server_cert_pem);
  13982. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13983. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13984. SSLServer::PemMemory server_pem = {
  13985. server_cert_pem.c_str(),
  13986. server_cert_pem.size(),
  13987. server_key_pem.c_str(),
  13988. server_key_pem.size(),
  13989. client_ca_pem.c_str(),
  13990. client_ca_pem.size(),
  13991. nullptr // no password for server key
  13992. };
  13993. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13994. SCOPED_TRACE(client_ca_pem_len);
  13995. server_pem.client_ca_pem_len = client_ca_pem_len;
  13996. SSLServer svr(server_pem);
  13997. ASSERT_TRUE(svr.is_valid());
  13998. RejectsClientWithoutCert(svr);
  13999. }
  14000. // An empty CA fails to load instead of turning the check off
  14001. server_pem.client_ca_pem = "";
  14002. server_pem.client_ca_pem_len = 0;
  14003. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14004. }
  14005. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14006. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14007. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14008. true);
  14009. }
  14010. // A length shorter than the PEM cuts it short, so it no longer loads
  14011. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14012. std::string cert, key;
  14013. read_file(SERVER_CERT_FILE, cert);
  14014. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14015. for (auto cut_cert : {true, false}) {
  14016. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14017. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14018. SSLServer::PemMemory server_pem = {
  14019. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14020. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14021. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14022. key_len, nullptr};
  14023. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14024. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14025. key.c_str(), key_len, nullptr};
  14026. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14027. }
  14028. }
  14029. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14030. class NoListenSSLServer : public SSLServer {
  14031. public:
  14032. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14033. const char *client_ca_cert_file_path,
  14034. const char *client_ca_cert_dir_path = nullptr)
  14035. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14036. client_ca_cert_dir_path),
  14037. stop_(false) {}
  14038. std::atomic_bool stop_;
  14039. private:
  14040. bool process_and_close_socket(socket_t /*sock*/) override {
  14041. // Don't create SSL context
  14042. while (!stop_.load()) {
  14043. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14044. }
  14045. return true;
  14046. }
  14047. };
  14048. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14049. CLIENT_CA_CERT_FILE);
  14050. ASSERT_TRUE(svr.is_valid());
  14051. svr.Get("/test", [&](const Request &, Response &res) {
  14052. res.set_content("test", "text/plain");
  14053. });
  14054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14055. auto se = detail::scope_exit([&] {
  14056. svr.stop_ = true;
  14057. svr.stop();
  14058. t.join();
  14059. ASSERT_FALSE(svr.is_running());
  14060. });
  14061. svr.wait_until_ready();
  14062. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14063. cli.enable_server_certificate_verification(false);
  14064. cli.set_connection_timeout(1);
  14065. auto res = cli.Get("/test");
  14066. ASSERT_TRUE(!res);
  14067. EXPECT_EQ(Error::SSLConnection, res.error());
  14068. // Timeout results in WantRead error code (maps to backend-specific value)
  14069. EXPECT_NE(0, res.ssl_error());
  14070. }
  14071. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14072. // Test SSLServer with client certificate verification using the standard
  14073. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14075. CLIENT_CA_CERT_DIR);
  14076. ASSERT_TRUE(svr.is_valid());
  14077. svr.Get("/test", [&](const Request &req, Response &res) {
  14078. res.set_content("test", "text/plain");
  14079. auto cert = req.peer_cert();
  14080. ASSERT_TRUE(static_cast<bool>(cert));
  14081. auto common_name = cert.subject_cn();
  14082. EXPECT_EQ("Common Name", common_name);
  14083. });
  14084. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14085. auto se = detail::scope_exit([&] {
  14086. svr.stop();
  14087. t.join();
  14088. ASSERT_FALSE(svr.is_running());
  14089. });
  14090. svr.wait_until_ready();
  14091. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14092. cli.enable_server_certificate_verification(false);
  14093. cli.set_connection_timeout(30);
  14094. auto res = cli.Get("/test");
  14095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14096. ASSERT_EQ(StatusCode::OK_200, res->status);
  14097. }
  14098. // Test verify_hostname on every backend: a host is named by a SAN only
  14099. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14100. using namespace httplib::tls;
  14101. // We need a running server to test against
  14102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14103. ASSERT_TRUE(svr.is_valid());
  14104. svr.Get("/test", [](const Request &, Response &res) {
  14105. res.set_content("ok", "text/plain");
  14106. });
  14107. thread t([&]() { svr.listen(HOST, PORT); });
  14108. auto se = detail::scope_exit([&] {
  14109. svr.stop();
  14110. t.join();
  14111. });
  14112. svr.wait_until_ready();
  14113. bool verify_callback_called = false;
  14114. bool verify_result_wrong = false;
  14115. SSLClient cli(HOST, PORT);
  14116. cli.enable_server_certificate_verification(true);
  14117. cli.set_ca_cert_path(CA_CERT_FILE);
  14118. cli.set_connection_timeout(5);
  14119. // Note: Test certificate has CN="Common Name", not "localhost"
  14120. bool verify_result_cn = false;
  14121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14122. verify_callback_called = true;
  14123. if (!ctx.cert) return false;
  14124. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14125. verify_result_cn = ctx.check_hostname("Common Name");
  14126. // Test 2: wrong hostname should not match
  14127. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14128. return true; // Accept for the purpose of this test
  14129. });
  14130. auto res = cli.Get("/test");
  14131. // The request may succeed or fail depending on cert configuration
  14132. // but the callback should have been called
  14133. ASSERT_TRUE(verify_callback_called)
  14134. << "Verify callback should have been called";
  14135. EXPECT_FALSE(verify_result_cn)
  14136. << "verify_hostname must not match the certificate CN (no SAN)";
  14137. // Wrong hostname should not match
  14138. EXPECT_FALSE(verify_result_wrong)
  14139. << "verify_hostname should not match 'wronghost.example.com'";
  14140. }
  14141. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14142. // backend verifies it.
  14143. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14144. // Certificate CN is "localhost" and it carries no SAN.
  14145. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14146. ASSERT_TRUE(svr.is_valid());
  14147. svr.Get("/test", [](const Request &, Response &res) {
  14148. res.set_content("ok", "text/plain");
  14149. });
  14150. auto port = svr.bind_to_any_port(HOST);
  14151. thread t([&]() { svr.listen_after_bind(); });
  14152. auto se = detail::scope_exit([&] {
  14153. svr.stop();
  14154. t.join();
  14155. });
  14156. svr.wait_until_ready();
  14157. SSLClient cli("localhost", port);
  14158. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14159. cli.enable_server_certificate_verification(true);
  14160. cli.set_connection_timeout(5);
  14161. auto res = cli.Get("/test");
  14162. ASSERT_FALSE(res);
  14163. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14164. // The same certificate is accepted once host name verification is off, so the
  14165. // failure above is the host name and not the chain.
  14166. cli.enable_server_hostname_verification(false);
  14167. res = cli.Get("/test");
  14168. ASSERT_TRUE(res) << to_string(res.error());
  14169. EXPECT_EQ(StatusCode::OK_200, res->status);
  14170. }
  14171. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14172. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14173. // X509_check_ip behavior and must hold for every backend.
  14174. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14175. using namespace httplib::tls;
  14176. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14177. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14178. ASSERT_TRUE(svr.is_valid());
  14179. svr.Get("/test", [](const Request &, Response &res) {
  14180. res.set_content("ok", "text/plain");
  14181. });
  14182. thread t([&]() { svr.listen(HOST, PORT); });
  14183. auto se = detail::scope_exit([&] {
  14184. svr.stop();
  14185. t.join();
  14186. });
  14187. svr.wait_until_ready();
  14188. bool verify_callback_called = false;
  14189. bool ip_matched_via_cn = true;
  14190. SSLClient cli(HOST, PORT);
  14191. cli.enable_server_certificate_verification(true);
  14192. cli.set_ca_cert_path(CA_CERT_FILE);
  14193. cli.set_connection_timeout(5);
  14194. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14195. verify_callback_called = true;
  14196. if (!ctx.cert) return false;
  14197. // The IP appears only in the CN, so it must NOT be accepted.
  14198. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14199. return true; // Accept for the purpose of this test
  14200. });
  14201. cli.Get("/test");
  14202. ASSERT_TRUE(verify_callback_called)
  14203. << "Verify callback should have been called";
  14204. EXPECT_FALSE(ip_matched_via_cn)
  14205. << "An IP host must not be authenticated via the certificate CN";
  14206. }
  14207. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14208. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14209. using namespace httplib::tls;
  14210. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14211. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14212. ASSERT_TRUE(svr.is_valid());
  14213. svr.Get("/test", [](const Request &, Response &res) {
  14214. res.set_content("ok", "text/plain");
  14215. });
  14216. thread t([&]() { svr.listen(HOST, PORT); });
  14217. auto se = detail::scope_exit([&] {
  14218. svr.stop();
  14219. t.join();
  14220. });
  14221. svr.wait_until_ready();
  14222. bool verify_callback_called = false;
  14223. bool san_matched = false;
  14224. bool wrong_ipv6_matched = true;
  14225. bool cn_ipv6_matched = true;
  14226. SSLClient cli(HOST, PORT);
  14227. cli.enable_server_certificate_verification(true);
  14228. cli.set_ca_cert_path(CA_CERT_FILE);
  14229. cli.set_connection_timeout(5);
  14230. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14231. verify_callback_called = true;
  14232. if (!ctx.cert) return false;
  14233. // Matches the IPv6 iPAddress SAN.
  14234. san_matched = ctx.check_hostname("2001:db8::1");
  14235. // A different IPv6 address must not match.
  14236. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14237. // "::1" lives only in the CN, so it must not be accepted.
  14238. cn_ipv6_matched = ctx.check_hostname("::1");
  14239. return true; // Accept for the purpose of this test
  14240. });
  14241. cli.Get("/test");
  14242. ASSERT_TRUE(verify_callback_called)
  14243. << "Verify callback should have been called";
  14244. EXPECT_TRUE(san_matched)
  14245. << "verify_hostname should match an IPv6 iPAddress SAN";
  14246. EXPECT_FALSE(wrong_ipv6_matched)
  14247. << "verify_hostname should not match a non-matching IPv6 address";
  14248. EXPECT_FALSE(cn_ipv6_matched)
  14249. << "An IPv6 host must not be authenticated via the certificate CN";
  14250. }
  14251. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14252. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14253. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14254. using namespace httplib::tls;
  14255. // SANs: DNS:a.zz, IP:42.46.122.122
  14256. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14257. ASSERT_TRUE(svr.is_valid());
  14258. svr.Get("/test", [](const Request &, Response &res) {
  14259. res.set_content("ok", "text/plain");
  14260. });
  14261. auto port = svr.bind_to_any_port(HOST);
  14262. thread t([&]() { svr.listen_after_bind(); });
  14263. auto se = detail::scope_exit([&] {
  14264. svr.stop();
  14265. t.join();
  14266. });
  14267. svr.wait_until_ready();
  14268. bool verify_callback_called = false;
  14269. bool dns_san_matched = false;
  14270. bool ip_san_matched = false;
  14271. bool ip_matched_via_dns_san = true;
  14272. bool dns_matched_via_ip_san = true;
  14273. bool cn_matched_next_to_dns_san = true;
  14274. SSLClient cli(HOST, port);
  14275. cli.enable_server_certificate_verification(true);
  14276. cli.set_ca_cert_path(CA_CERT_FILE);
  14277. cli.set_connection_timeout(5);
  14278. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14279. verify_callback_called = true;
  14280. if (!ctx.cert) return false;
  14281. dns_san_matched = ctx.check_hostname("a.zz");
  14282. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14283. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14284. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14285. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14286. return true; // Accept for the purpose of this test
  14287. });
  14288. cli.Get("/test");
  14289. ASSERT_TRUE(verify_callback_called)
  14290. << "Verify callback should have been called";
  14291. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14292. EXPECT_TRUE(ip_san_matched)
  14293. << "verify_hostname should match an iPAddress SAN";
  14294. EXPECT_FALSE(ip_matched_via_dns_san)
  14295. << "An IP host must not be authenticated via a dNSName SAN";
  14296. EXPECT_FALSE(dns_matched_via_ip_san)
  14297. << "A DNS host must not be authenticated via an iPAddress SAN";
  14298. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14299. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14300. }
  14301. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14302. // "www.*.example.test" names one host and not every host under example.test.
  14303. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14304. using namespace httplib::tls;
  14305. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14306. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14307. ASSERT_TRUE(svr.is_valid());
  14308. svr.Get("/test", [](const Request &, Response &res) {
  14309. res.set_content("ok", "text/plain");
  14310. });
  14311. auto port = svr.bind_to_any_port(HOST);
  14312. thread t([&]() { svr.listen_after_bind(); });
  14313. auto se = detail::scope_exit([&] {
  14314. svr.stop();
  14315. t.join();
  14316. });
  14317. svr.wait_until_ready();
  14318. bool verify_callback_called = false;
  14319. bool leftmost_wildcard_matched = false;
  14320. bool wildcard_spanned_labels = true;
  14321. bool inner_wildcard_matched = true;
  14322. SSLClient cli(HOST, port);
  14323. cli.enable_server_certificate_verification(true);
  14324. cli.set_ca_cert_path(CA_CERT_FILE);
  14325. cli.set_connection_timeout(5);
  14326. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14327. verify_callback_called = true;
  14328. if (!ctx.cert) return false;
  14329. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14330. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14331. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14332. return true; // Accept for the purpose of this test
  14333. });
  14334. cli.Get("/test");
  14335. ASSERT_TRUE(verify_callback_called)
  14336. << "Verify callback should have been called";
  14337. EXPECT_TRUE(leftmost_wildcard_matched)
  14338. << "A leftmost wildcard should match a single label";
  14339. EXPECT_FALSE(wildcard_spanned_labels)
  14340. << "A wildcard label must not match more than one label";
  14341. EXPECT_FALSE(inner_wildcard_matched)
  14342. << "A wildcard outside the leftmost label must not be honoured";
  14343. }
  14344. // sans() must report each SAN entry under its own type.
  14345. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14346. using namespace httplib::tls;
  14347. // SANs: DNS:a.zz, IP:42.46.122.122
  14348. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14349. ASSERT_TRUE(svr.is_valid());
  14350. svr.Get("/test", [](const Request &, Response &res) {
  14351. res.set_content("ok", "text/plain");
  14352. });
  14353. auto port = svr.bind_to_any_port(HOST);
  14354. thread t([&]() { svr.listen_after_bind(); });
  14355. auto se = detail::scope_exit([&] {
  14356. svr.stop();
  14357. t.join();
  14358. });
  14359. svr.wait_until_ready();
  14360. bool verify_callback_called = false;
  14361. std::vector<SanEntry> sans;
  14362. SSLClient cli(HOST, port);
  14363. cli.enable_server_certificate_verification(true);
  14364. cli.set_ca_cert_path(CA_CERT_FILE);
  14365. cli.set_connection_timeout(5);
  14366. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14367. verify_callback_called = true;
  14368. if (!ctx.cert) return false;
  14369. sans = ctx.sans();
  14370. return true; // Accept for the purpose of this test
  14371. });
  14372. cli.Get("/test");
  14373. ASSERT_TRUE(verify_callback_called)
  14374. << "Verify callback should have been called";
  14375. auto has_san = [&](SanType type, const std::string &value) {
  14376. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14377. return san.type == type && san.value == value;
  14378. });
  14379. };
  14380. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14381. << "sans() should report the dNSName SAN";
  14382. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14383. << "sans() should report the iPAddress SAN";
  14384. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14385. << "sans() must not report the dNSName SAN as an address";
  14386. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14387. << "sans() must not report the iPAddress SAN as a DNS name";
  14388. }
  14389. #endif
  14390. // mbedTLS-specific callback constructor test
  14391. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14392. #ifdef CPPHTTPLIB_SSL_ENABLED
  14393. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14395. ASSERT_TRUE(svr.is_valid());
  14396. // Set up a handler to verify client certificate is present
  14397. bool client_cert_verified = false;
  14398. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14399. // Verify that client certificate was provided
  14400. client_cert_verified = true;
  14401. res.set_content("success", "text/plain");
  14402. });
  14403. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14404. auto se = detail::scope_exit([&] {
  14405. svr.stop();
  14406. t.join();
  14407. ASSERT_FALSE(svr.is_running());
  14408. });
  14409. svr.wait_until_ready();
  14410. // Client with certificate
  14411. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14412. cli.enable_server_certificate_verification(false);
  14413. cli.set_connection_timeout(30);
  14414. auto res = cli.Get("/test");
  14415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14416. ASSERT_EQ(StatusCode::OK_200, res->status);
  14417. ASSERT_TRUE(client_cert_verified);
  14418. EXPECT_EQ("success", res->body);
  14419. }
  14420. #endif
  14421. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14422. // backends
  14423. #ifdef CPPHTTPLIB_SSL_ENABLED
  14424. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14425. using namespace httplib::tls;
  14426. // Test that when client CA cert file is provided,
  14427. // the server properly requests and validates client certificates
  14428. // Create a server with client authentication
  14429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14430. ASSERT_TRUE(svr.is_valid());
  14431. bool handler_called = false;
  14432. svr.Get("/test", [&](const Request &req, Response &res) {
  14433. handler_called = true;
  14434. // Verify that a client certificate was provided
  14435. auto cert = req.peer_cert();
  14436. ASSERT_TRUE(static_cast<bool>(cert));
  14437. // Get the issuer name
  14438. std::string issuer_str = cert.issuer_name();
  14439. ASSERT_FALSE(issuer_str.empty());
  14440. // The client certificate should be issued by our test CA
  14441. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14442. res.set_content("authenticated", "text/plain");
  14443. });
  14444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14445. auto se = detail::scope_exit([&] {
  14446. svr.stop();
  14447. t.join();
  14448. ASSERT_FALSE(svr.is_running());
  14449. });
  14450. svr.wait_until_ready();
  14451. // Connect with a client certificate issued by the CA
  14452. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14453. cli.enable_server_certificate_verification(false);
  14454. cli.set_connection_timeout(30);
  14455. auto res = cli.Get("/test");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::OK_200, res->status);
  14458. ASSERT_TRUE(handler_called);
  14459. EXPECT_EQ("authenticated", res->body);
  14460. }
  14461. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14462. using namespace httplib::tls;
  14463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14464. ASSERT_TRUE(svr.is_valid());
  14465. svr.Get("/test", [](const Request &, Response &res) {
  14466. res.set_content("ok", "text/plain");
  14467. });
  14468. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14469. auto se = detail::scope_exit([&] {
  14470. svr.stop();
  14471. t.join();
  14472. });
  14473. svr.wait_until_ready();
  14474. SSLClient cli(HOST, PORT);
  14475. cli.enable_server_certificate_verification(false);
  14476. cli.set_connection_timeout(30);
  14477. bool cert_checked = false;
  14478. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14479. if (ctx.cert) {
  14480. auto sans = ctx.sans();
  14481. // Test certificate may or may not have SANs - just verify the API
  14482. // works If SANs exist, verify the types are valid
  14483. for (const auto &san : sans) {
  14484. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14485. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14486. san.type == SanType::OTHER);
  14487. EXPECT_FALSE(san.value.empty());
  14488. }
  14489. cert_checked = true;
  14490. }
  14491. return true;
  14492. });
  14493. auto res = cli.Get("/test");
  14494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14495. EXPECT_TRUE(cert_checked);
  14496. }
  14497. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14498. using namespace httplib::tls;
  14499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14500. ASSERT_TRUE(svr.is_valid());
  14501. svr.Get("/test", [](const Request &, Response &res) {
  14502. res.set_content("ok", "text/plain");
  14503. });
  14504. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14505. auto se = detail::scope_exit([&] {
  14506. svr.stop();
  14507. t.join();
  14508. });
  14509. svr.wait_until_ready();
  14510. SSLClient cli(HOST, PORT);
  14511. cli.enable_server_certificate_verification(false);
  14512. cli.set_connection_timeout(30);
  14513. bool validity_checked = false;
  14514. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14515. if (ctx.cert) {
  14516. time_t not_before = 0, not_after = 0;
  14517. bool result = ctx.validity(not_before, not_after);
  14518. EXPECT_TRUE(result);
  14519. // Verify that not_before < now < not_after for a valid cert
  14520. time_t now = time(nullptr);
  14521. EXPECT_LT(not_before, now);
  14522. EXPECT_GT(not_after, now);
  14523. validity_checked = true;
  14524. }
  14525. return true;
  14526. });
  14527. auto res = cli.Get("/test");
  14528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14529. EXPECT_TRUE(validity_checked);
  14530. }
  14531. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14532. using namespace httplib::tls;
  14533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14534. ASSERT_TRUE(svr.is_valid());
  14535. svr.Get("/test", [](const Request &, Response &res) {
  14536. res.set_content("ok", "text/plain");
  14537. });
  14538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. });
  14543. svr.wait_until_ready();
  14544. SSLClient cli(HOST, PORT);
  14545. cli.enable_server_certificate_verification(false);
  14546. cli.set_connection_timeout(30);
  14547. bool serial_checked = false;
  14548. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14549. if (ctx.cert) {
  14550. std::string serial = ctx.serial();
  14551. EXPECT_FALSE(serial.empty());
  14552. // Serial should be a hex string
  14553. for (char c : serial) {
  14554. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14555. (c >= 'a' && c <= 'f'));
  14556. }
  14557. serial_checked = true;
  14558. }
  14559. return true;
  14560. });
  14561. auto res = cli.Get("/test");
  14562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14563. EXPECT_TRUE(serial_checked);
  14564. }
  14565. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14566. // Test 1: Valid CA file - no error should be recorded
  14567. {
  14568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14569. CLIENT_CA_CERT_FILE);
  14570. ASSERT_TRUE(svr.is_valid());
  14571. // With valid setup, last_ssl_error should be 0
  14572. EXPECT_EQ(0, svr.ssl_last_error());
  14573. }
  14574. // Test 2: Invalid CA file content
  14575. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14576. {
  14577. // Create a temporary file with completely invalid content
  14578. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14579. {
  14580. std::ofstream ofs(temp_invalid_ca);
  14581. ofs << "This is not a certificate file at all\n";
  14582. ofs << "Just plain text content\n";
  14583. }
  14584. // Create server with invalid CA file
  14585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14586. // Clean up temporary file
  14587. std::remove(temp_invalid_ca);
  14588. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14589. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14590. // Note: SSL_CTX_load_verify_locations typically fails first,
  14591. // but our error handling code path is still exercised
  14592. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14593. }
  14594. }
  14595. TEST(VerifyCallbackTest, VerifyContextFields) {
  14596. using namespace httplib::tls;
  14597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14598. ASSERT_TRUE(svr.is_valid());
  14599. svr.Get("/test", [](const Request &, Response &res) {
  14600. res.set_content("ok", "text/plain");
  14601. });
  14602. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14603. auto se = detail::scope_exit([&] {
  14604. svr.stop();
  14605. t.join();
  14606. });
  14607. svr.wait_until_ready();
  14608. SSLClient cli(HOST, PORT);
  14609. cli.enable_server_certificate_verification(false);
  14610. cli.set_connection_timeout(30);
  14611. int callback_count = 0;
  14612. bool saw_leaf_cert = false;
  14613. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14614. if (ctx.cert) {
  14615. callback_count++;
  14616. // We should see at least one certificate (the leaf)
  14617. std::string cn = ctx.subject_cn();
  14618. if (!cn.empty()) { saw_leaf_cert = true; }
  14619. // Verify context fields are populated
  14620. EXPECT_NE(ctx.session, nullptr);
  14621. EXPECT_GE(ctx.depth, 0);
  14622. }
  14623. return true;
  14624. });
  14625. auto res = cli.Get("/test");
  14626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14627. EXPECT_GT(callback_count, 0);
  14628. EXPECT_TRUE(saw_leaf_cert);
  14629. }
  14630. // A verifier that accepts runs alongside the built-in verification, and is the
  14631. // only check once that is turned off.
  14632. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14633. using namespace httplib::tls;
  14634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14635. ASSERT_TRUE(svr.is_valid());
  14636. svr.Get("/test", [](const Request &, Response &res) {
  14637. res.set_content("ok", "text/plain");
  14638. });
  14639. auto port = svr.bind_to_any_port(HOST);
  14640. thread t([&]() { svr.listen_after_bind(); });
  14641. auto se = detail::scope_exit([&] {
  14642. svr.stop();
  14643. t.join();
  14644. });
  14645. svr.wait_until_ready();
  14646. SSLClient cli(HOST, port);
  14647. cli.enable_server_hostname_verification(false);
  14648. auto calls = 0;
  14649. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14650. calls++;
  14651. return true;
  14652. });
  14653. // cert.pem is not trusted
  14654. auto res = cli.Get("/test");
  14655. ASSERT_FALSE(res);
  14656. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14657. EXPECT_GT(calls, 0);
  14658. cli.enable_server_certificate_verification(false);
  14659. res = cli.Get("/test");
  14660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14661. EXPECT_EQ("ok", res->body);
  14662. }
  14663. // A verifier belongs to the client that set it, not to the thread that set it.
  14664. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14665. using namespace httplib::tls;
  14666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14667. ASSERT_TRUE(svr.is_valid());
  14668. svr.Get("/test", [](const Request &, Response &res) {
  14669. res.set_content("ok", "text/plain");
  14670. });
  14671. auto port = svr.bind_to_any_port(HOST);
  14672. thread t([&]() { svr.listen_after_bind(); });
  14673. auto se = detail::scope_exit([&] {
  14674. svr.stop();
  14675. t.join();
  14676. });
  14677. svr.wait_until_ready();
  14678. auto rejecting_calls = 0;
  14679. SSLClient rejecting(HOST, port);
  14680. rejecting.enable_server_certificate_verification(false);
  14681. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14682. rejecting_calls++;
  14683. return false;
  14684. });
  14685. auto accepting_calls = 0;
  14686. SSLClient accepting(HOST, port);
  14687. accepting.enable_server_certificate_verification(false);
  14688. // Set on another thread than the requests below.
  14689. thread([&]() {
  14690. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14691. accepting_calls++;
  14692. return true;
  14693. });
  14694. }).join();
  14695. // Requested on another thread than the verifier was set on.
  14696. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14697. EXPECT_GT(rejecting_calls, 0);
  14698. auto res = accepting.Get("/test");
  14699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14700. EXPECT_GT(accepting_calls, 0);
  14701. }
  14702. // A verifier replaced while a handshake runs it lives until it returns.
  14703. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14704. using namespace httplib::tls;
  14705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14706. ASSERT_TRUE(svr.is_valid());
  14707. svr.Get("/test", [](const Request &, Response &res) {
  14708. res.set_content("ok", "text/plain");
  14709. });
  14710. auto port = svr.bind_to_any_port(HOST);
  14711. thread t([&]() { svr.listen_after_bind(); });
  14712. auto se = detail::scope_exit([&] {
  14713. svr.stop();
  14714. t.join();
  14715. });
  14716. svr.wait_until_ready();
  14717. SSLClient cli(HOST, port);
  14718. cli.enable_server_certificate_verification(false);
  14719. std::promise<void> entered;
  14720. std::promise<void> replaced;
  14721. auto replaced_future = replaced.get_future();
  14722. auto first_call = true;
  14723. // Long enough to live on the heap
  14724. std::string expected(64, 'v');
  14725. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14726. if (first_call) {
  14727. first_call = false;
  14728. entered.set_value();
  14729. replaced_future.wait();
  14730. }
  14731. return expected == std::string(64, 'v');
  14732. });
  14733. thread request([&]() {
  14734. auto res = cli.Get("/test");
  14735. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14736. });
  14737. entered.get_future().wait();
  14738. cli.set_server_certificate_verifier(
  14739. [](const VerifyContext &) { return true; });
  14740. replaced.set_value();
  14741. request.join();
  14742. }
  14743. // VerifyContext::session is the same handle the other tls:: functions take.
  14744. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14745. using namespace httplib::tls;
  14746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14747. ASSERT_TRUE(svr.is_valid());
  14748. svr.Get("/test", [](const Request &, Response &res) {
  14749. res.set_content("ok", "text/plain");
  14750. });
  14751. auto port = svr.bind_to_any_port(HOST);
  14752. thread t([&]() { svr.listen_after_bind(); });
  14753. auto se = detail::scope_exit([&] {
  14754. svr.stop();
  14755. t.join();
  14756. });
  14757. svr.wait_until_ready();
  14758. SSLClient cli(HOST, port);
  14759. cli.enable_server_certificate_verification(false);
  14760. session_t verifier_session = nullptr;
  14761. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14762. verifier_session = ctx.session;
  14763. return true;
  14764. });
  14765. session_t session_verifier_session = nullptr;
  14766. cli.set_session_verifier([&](session_t session) {
  14767. session_verifier_session = session;
  14768. return SSLVerifierResponse::NoDecisionMade;
  14769. });
  14770. auto res = cli.Get("/test");
  14771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14772. EXPECT_NE(nullptr, verifier_session);
  14773. EXPECT_EQ(session_verifier_session, verifier_session);
  14774. }
  14775. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14776. using httplib::tls::TlsError;
  14777. // Test that verify_error_to_string returns empty for success
  14778. std::string success_str = TlsError::verify_error_to_string(0);
  14779. EXPECT_TRUE(success_str.empty());
  14780. // Test that verify_error_to_string returns non-empty for error codes
  14781. // Using a common error code (certificate expired)
  14782. std::string error_str =
  14783. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14784. EXPECT_FALSE(error_str.empty());
  14785. }
  14786. TEST(SessionVerifierTest, CertificateAccepted) {
  14787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14788. ASSERT_TRUE(svr.is_valid());
  14789. svr.Get("/test", [](const Request &, Response &res) {
  14790. res.set_content("ok", "text/plain");
  14791. });
  14792. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14793. auto se = detail::scope_exit([&] {
  14794. svr.stop();
  14795. t.join();
  14796. });
  14797. svr.wait_until_ready();
  14798. SSLClient cli(HOST, PORT);
  14799. cli.enable_server_certificate_verification(false);
  14800. cli.set_connection_timeout(30);
  14801. bool callback_called = false;
  14802. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14803. EXPECT_NE(session, nullptr);
  14804. callback_called = true;
  14805. return SSLVerifierResponse::CertificateAccepted;
  14806. });
  14807. auto res = cli.Get("/test");
  14808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14809. EXPECT_EQ(200, res->status);
  14810. EXPECT_TRUE(callback_called);
  14811. }
  14812. TEST(SessionVerifierTest, CertificateRejected) {
  14813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14814. ASSERT_TRUE(svr.is_valid());
  14815. svr.Get("/test", [](const Request &, Response &res) {
  14816. res.set_content("ok", "text/plain");
  14817. });
  14818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. t.join();
  14822. });
  14823. svr.wait_until_ready();
  14824. SSLClient cli(HOST, PORT);
  14825. cli.enable_server_certificate_verification(false);
  14826. cli.set_connection_timeout(30);
  14827. bool callback_called = false;
  14828. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14829. EXPECT_NE(session, nullptr);
  14830. callback_called = true;
  14831. return SSLVerifierResponse::CertificateRejected;
  14832. });
  14833. auto res = cli.Get("/test");
  14834. EXPECT_FALSE(res);
  14835. EXPECT_TRUE(callback_called);
  14836. }
  14837. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14839. ASSERT_TRUE(svr.is_valid());
  14840. svr.Get("/test", [](const Request &, Response &res) {
  14841. res.set_content("ok", "text/plain");
  14842. });
  14843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14844. auto se = detail::scope_exit([&] {
  14845. svr.stop();
  14846. t.join();
  14847. });
  14848. svr.wait_until_ready();
  14849. // NoDecisionMade with verification disabled should succeed (no default check)
  14850. SSLClient cli(HOST, PORT);
  14851. cli.enable_server_certificate_verification(false);
  14852. cli.set_connection_timeout(30);
  14853. bool callback_called = false;
  14854. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14855. EXPECT_NE(session, nullptr);
  14856. callback_called = true;
  14857. return SSLVerifierResponse::NoDecisionMade;
  14858. });
  14859. auto res = cli.Get("/test");
  14860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14861. EXPECT_EQ(200, res->status);
  14862. EXPECT_TRUE(callback_called);
  14863. }
  14864. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14866. ASSERT_TRUE(svr.is_valid());
  14867. svr.Get("/test", [](const Request &, Response &res) {
  14868. res.set_content("ok", "text/plain");
  14869. });
  14870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14871. auto se = detail::scope_exit([&] {
  14872. svr.stop();
  14873. t.join();
  14874. });
  14875. svr.wait_until_ready();
  14876. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14877. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14878. // so we only check that the request fails, not whether the callback was
  14879. // called.
  14880. SSLClient cli(HOST, PORT);
  14881. cli.enable_server_certificate_verification(true);
  14882. cli.set_connection_timeout(30);
  14883. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14884. EXPECT_NE(session, nullptr);
  14885. return SSLVerifierResponse::NoDecisionMade;
  14886. });
  14887. auto res = cli.Get("/test");
  14888. EXPECT_FALSE(res);
  14889. }
  14890. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14891. // Test SSL server using PemMemory constructor with client CA certificates
  14892. // Read PEM files
  14893. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14894. read_file(SERVER_CERT_FILE, server_cert_pem);
  14895. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14896. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14897. // Create SSLServer with PemMemory constructor including client CA
  14898. SSLServer::PemMemory server_pem = {
  14899. server_cert_pem.c_str(),
  14900. server_cert_pem.size(),
  14901. server_key_pem.c_str(),
  14902. server_key_pem.size(),
  14903. client_ca_pem.c_str(),
  14904. client_ca_pem.size(),
  14905. nullptr // no password for server key
  14906. };
  14907. SSLServer svr(server_pem);
  14908. ASSERT_TRUE(svr.is_valid());
  14909. // No SSL error should be recorded for valid setup
  14910. EXPECT_EQ(0, svr.ssl_last_error());
  14911. // Set up server endpoints
  14912. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14913. res.set_content("ok", "text/plain");
  14914. });
  14915. // Start server in a thread
  14916. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14917. svr.wait_until_ready();
  14918. // Connect with client certificate (using constructor with paths)
  14919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14920. cli.enable_server_certificate_verification(false);
  14921. auto res = cli.Get("/test-pem-ca");
  14922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14923. EXPECT_EQ(200, res->status);
  14924. EXPECT_EQ("ok", res->body);
  14925. svr.stop();
  14926. server_thread.join();
  14927. }
  14928. #endif
  14929. #ifdef _WIN32
  14930. TEST(CleanupTest, WSACleanup) {
  14931. int ret = WSACleanup();
  14932. ASSERT_EQ(0, ret);
  14933. }
  14934. #endif
  14935. #ifndef CPPHTTPLIB_SSL_ENABLED
  14936. TEST(NoSSLSupport, SimpleInterface) {
  14937. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14938. }
  14939. #endif
  14940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14941. TEST(InvalidScheme, SimpleInterface) {
  14942. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14943. }
  14944. #endif
  14945. TEST(NoScheme, SimpleInterface) {
  14946. Client cli("yahoo.com:80");
  14947. ASSERT_TRUE(cli.is_valid());
  14948. }
  14949. TEST(SendAPI, SimpleInterface_Online) {
  14950. Client cli("http://yahoo.com");
  14951. Request req;
  14952. req.method = "GET";
  14953. req.path = "/";
  14954. auto res = cli.send(req);
  14955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14956. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14957. }
  14958. TEST(SendAPI, WithParamsInRequest) {
  14959. Server svr;
  14960. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14961. EXPECT_TRUE(req.has_param("test"));
  14962. EXPECT_EQ("test_value", req.get_param_value("test"));
  14963. });
  14964. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. t.join();
  14968. ASSERT_FALSE(svr.is_running());
  14969. });
  14970. svr.wait_until_ready();
  14971. Client cli(HOST, PORT);
  14972. {
  14973. Request req;
  14974. req.method = "GET";
  14975. req.path = "/";
  14976. req.params.emplace("test", "test_value");
  14977. auto res = cli.send(req);
  14978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14979. }
  14980. {
  14981. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14983. }
  14984. }
  14985. TEST(ClientImplMethods, GetSocketTest) {
  14986. httplib::Server svr;
  14987. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14988. res.status = StatusCode::OK_200;
  14989. });
  14990. auto port = svr.bind_to_any_port("127.0.0.1");
  14991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14992. auto se = detail::scope_exit([&] {
  14993. svr.stop();
  14994. thread.join();
  14995. ASSERT_FALSE(svr.is_running());
  14996. });
  14997. svr.wait_until_ready();
  14998. {
  14999. httplib::Client cli("127.0.0.1", port);
  15000. cli.set_keep_alive(true);
  15001. // Use the behavior of cpp-httplib of opening the connection
  15002. // only when the first request happens. If that changes,
  15003. // this test would be obsolete.
  15004. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15005. // This also implicitly tests the server. But other tests would fail much
  15006. // earlier than this one to be considered.
  15007. auto res = cli.Get("/");
  15008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15009. EXPECT_EQ(StatusCode::OK_200, res->status);
  15010. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15011. }
  15012. }
  15013. #ifdef CPPHTTPLIB_SSL_ENABLED
  15014. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15015. Client cli("http://yahoo.com");
  15016. auto res = cli.Get("/");
  15017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15018. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15019. cli.set_follow_location(true);
  15020. res = cli.Get("/");
  15021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15022. EXPECT_EQ(StatusCode::OK_200, res->status);
  15023. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15024. }
  15025. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15026. Client cli("https://yahoo.com");
  15027. auto res = cli.Get("/");
  15028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15029. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15030. cli.set_follow_location(true);
  15031. res = cli.Get("/");
  15032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15033. EXPECT_EQ(StatusCode::OK_200, res->status);
  15034. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15035. }
  15036. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15037. Client cli("https://yahoo.com");
  15038. auto res = cli.Get("/");
  15039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15040. ASSERT_FALSE(!res);
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. ASSERT_FALSE(res == nullptr);
  15043. ASSERT_TRUE(res != nullptr);
  15044. EXPECT_EQ(Error::Success, res.error());
  15045. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15046. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15047. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15048. cli.set_follow_location(true);
  15049. res = cli.Get("/");
  15050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15051. EXPECT_EQ(Error::Success, res.error());
  15052. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15053. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15054. EXPECT_EQ(StatusCode::OK_200, res->status);
  15055. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15056. }
  15057. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15058. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15059. Client cli("https://cdnjs.cloudflare.com");
  15060. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15061. Headers{{"Accept-Encoding", "br"}});
  15062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15063. EXPECT_EQ(StatusCode::OK_200, res->status);
  15064. EXPECT_EQ(287630U, res->body.size());
  15065. EXPECT_EQ("application/javascript; charset=utf-8",
  15066. res->get_header_value("Content-Type"));
  15067. }
  15068. #endif
  15069. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15070. #undef REDIR_HOST // Silence compiler warning
  15071. #define REDIR_HOST "https://httpbingo.org"
  15072. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15073. Client cli(REDIR_HOST);
  15074. cli.set_follow_location(true);
  15075. auto res =
  15076. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15078. EXPECT_EQ(StatusCode::OK_200, res->status);
  15079. }
  15080. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15081. Client cli(REDIR_HOST);
  15082. cli.set_follow_location(true);
  15083. Params params;
  15084. params.emplace("url", "http://example.com");
  15085. params.emplace("status_code", "302");
  15086. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15088. EXPECT_EQ(StatusCode::OK_200, res->status);
  15089. }
  15090. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15091. Client cli(REDIR_HOST);
  15092. cli.set_follow_location(true);
  15093. Params params;
  15094. params.emplace("url", "http://example.com");
  15095. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15097. EXPECT_EQ(StatusCode::OK_200, res->status);
  15098. }
  15099. TEST(HttpToHttpsRedirectTest, CertFile) {
  15100. auto ssl_port = PORT + 1;
  15101. Server svr;
  15102. ASSERT_TRUE(svr.is_valid());
  15103. svr.Get("/index", [&](const Request &, Response &res) {
  15104. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15105. "/index");
  15106. svr.stop();
  15107. });
  15108. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15109. ASSERT_TRUE(ssl_svr.is_valid());
  15110. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15111. res.set_content("test", "text/plain");
  15112. ssl_svr.stop();
  15113. });
  15114. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15115. thread t2 =
  15116. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15117. auto se = detail::scope_exit([&] {
  15118. t2.join();
  15119. t.join();
  15120. ASSERT_FALSE(svr.is_running());
  15121. });
  15122. svr.wait_until_ready();
  15123. ssl_svr.wait_until_ready();
  15124. Client cli("127.0.0.1", PORT);
  15125. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15126. cli.enable_server_certificate_verification(true);
  15127. cli.set_follow_location(true);
  15128. cli.set_connection_timeout(30);
  15129. auto res = cli.Get("/index");
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. ASSERT_EQ(StatusCode::OK_200, res->status);
  15132. }
  15133. TEST(SSLClientRedirectTest, CertFile) {
  15134. auto ssl_port = PORT + 1;
  15135. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15136. ASSERT_TRUE(ssl_svr1.is_valid());
  15137. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15138. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15139. "/index");
  15140. ssl_svr1.stop();
  15141. });
  15142. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15143. ASSERT_TRUE(ssl_svr2.is_valid());
  15144. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15145. res.set_content("test", "text/plain");
  15146. ssl_svr2.stop();
  15147. });
  15148. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15149. thread t2 =
  15150. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15151. auto se = detail::scope_exit([&] {
  15152. t2.join();
  15153. t.join();
  15154. ASSERT_FALSE(ssl_svr1.is_running());
  15155. });
  15156. ssl_svr1.wait_until_ready();
  15157. ssl_svr2.wait_until_ready();
  15158. SSLClient cli("127.0.0.1", PORT);
  15159. std::string cert;
  15160. read_file(SERVER_CERT2_FILE, cert);
  15161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15162. cli.enable_server_certificate_verification(true);
  15163. cli.set_follow_location(true);
  15164. cli.set_connection_timeout(30);
  15165. auto res = cli.Get("/index");
  15166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15167. ASSERT_EQ(StatusCode::OK_200, res->status);
  15168. }
  15169. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15170. // another port, so the client follows it with a new client.
  15171. static Result GetThroughTlsRedirectToDifferentPort(
  15172. const std::function<void(SSLClient &)> &setup,
  15173. const char *target_cert = SERVER_CERT2_FILE,
  15174. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15175. auto ssl_port = PORT + 1;
  15176. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15177. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15178. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15179. "/index");
  15180. });
  15181. SSLServer ssl_svr2(target_cert, target_key);
  15182. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15183. res.set_content("test", "text/plain");
  15184. });
  15185. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15186. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15187. auto se = detail::scope_exit([&] {
  15188. ssl_svr2.stop();
  15189. ssl_svr1.stop();
  15190. t2.join();
  15191. t.join();
  15192. });
  15193. ssl_svr1.wait_until_ready();
  15194. ssl_svr2.wait_until_ready();
  15195. SSLClient cli("127.0.0.1", PORT);
  15196. cli.set_follow_location(true);
  15197. cli.set_connection_timeout(30);
  15198. setup(cli);
  15199. return cli.Get("/index");
  15200. }
  15201. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15202. auto calls = 0;
  15203. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15204. cli.enable_server_certificate_verification(false);
  15205. // Accept the first server only.
  15206. cli.set_session_verifier([&](tls::session_t) {
  15207. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15208. : SSLVerifierResponse::CertificateRejected;
  15209. });
  15210. });
  15211. ASSERT_FALSE(res);
  15212. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15213. EXPECT_EQ(2, calls);
  15214. }
  15215. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15216. std::string pinned;
  15217. auto res = GetThroughTlsRedirectToDifferentPort(
  15218. [&](SSLClient &cli) {
  15219. cli.enable_server_certificate_verification(false);
  15220. // Pin the first certificate seen.
  15221. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15222. if (pinned.empty()) { pinned = ctx.serial(); }
  15223. return ctx.serial() == pinned;
  15224. });
  15225. },
  15226. // A certificate other than the first server's.
  15227. SERVER_CERT_FILE);
  15228. EXPECT_FALSE(res);
  15229. EXPECT_FALSE(pinned.empty());
  15230. }
  15231. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15232. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15233. std::string cert;
  15234. read_file(SERVER_CERT2_FILE, cert);
  15235. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15236. });
  15237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15238. EXPECT_EQ(StatusCode::OK_200, res->status);
  15239. }
  15240. // The target's certificate is signed by the root CA, which the first server's
  15241. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15242. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15243. auto res = GetThroughTlsRedirectToDifferentPort(
  15244. [](SSLClient &cli) {
  15245. std::string root_ca, cert;
  15246. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15247. read_file(SERVER_CERT2_FILE, cert);
  15248. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15249. cli.load_ca_cert_store(cert.data(), cert.size());
  15250. cli.enable_server_hostname_verification(false);
  15251. },
  15252. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15254. EXPECT_EQ(StatusCode::OK_200, res->status);
  15255. }
  15256. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15257. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15258. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15259. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15260. auto res = GetThroughTlsRedirectToDifferentPort(
  15261. [](SSLClient &cli) {
  15262. std::string root_ca, cert;
  15263. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15264. read_file(SERVER_CERT2_FILE, cert);
  15265. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15266. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15267. cli.enable_server_hostname_verification(false);
  15268. },
  15269. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15270. ASSERT_FALSE(res);
  15271. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15272. }
  15273. #endif
  15274. #endif
  15275. #ifdef CPPHTTPLIB_SSL_ENABLED
  15276. // Test that set_ca_cert_store() skips system certs (consistent with
  15277. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15278. // should be trusted - system certs should NOT be loaded.
  15279. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15280. // Load a specific cert that is NOT a system CA cert
  15281. std::string cert;
  15282. read_file(SERVER_CERT2_FILE, cert);
  15283. SSLClient cli("google.com");
  15284. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15285. cli.enable_server_certificate_verification(true);
  15286. // This should FAIL because:
  15287. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15288. // 2. System certs should NOT be loaded when custom store is set
  15289. // If system certs WERE loaded, this would succeed
  15290. auto res = cli.Get("/");
  15291. ASSERT_FALSE(res);
  15292. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15293. }
  15294. // Same as above, but through the native store handle path. Regression test:
  15295. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15296. // merged system certs into the user-provided store.
  15297. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15298. std::string cert;
  15299. read_file(SERVER_CERT2_FILE, cert);
  15300. SSLClient cli("google.com");
  15301. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15302. cli.enable_server_certificate_verification(true);
  15303. auto res = cli.Get("/");
  15304. ASSERT_FALSE(res);
  15305. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15306. }
  15307. // A custom store set via the native handle must still verify a server whose
  15308. // cert it does contain.
  15309. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15310. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15311. ASSERT_TRUE(svr.is_valid());
  15312. svr.Get("/test", [&](const Request &, Response &res) {
  15313. res.set_content("test", "text/plain");
  15314. });
  15315. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15316. auto se = detail::scope_exit([&] {
  15317. svr.stop();
  15318. t.join();
  15319. ASSERT_FALSE(svr.is_running());
  15320. });
  15321. svr.wait_until_ready();
  15322. SSLClient cli("127.0.0.1", PORT);
  15323. std::string cert;
  15324. read_file(SERVER_CERT2_FILE, cert);
  15325. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15326. cli.enable_server_certificate_verification(true);
  15327. cli.set_connection_timeout(30);
  15328. auto res = cli.Get("/test");
  15329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15330. ASSERT_EQ(StatusCode::OK_200, res->status);
  15331. }
  15332. // CA certs loaded through the universal Client must be transferred to the
  15333. // client created internally for following an HTTPS redirect. Regression test:
  15334. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15335. // the CA data for redirect transfer.
  15336. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15337. auto ssl_port = PORT + 1;
  15338. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15339. ASSERT_TRUE(ssl_svr1.is_valid());
  15340. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15341. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15342. "/index");
  15343. });
  15344. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15345. ASSERT_TRUE(ssl_svr2.is_valid());
  15346. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15347. res.set_content("test", "text/plain");
  15348. });
  15349. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15350. thread t2 =
  15351. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15352. auto se = detail::scope_exit([&] {
  15353. ssl_svr2.stop();
  15354. ssl_svr1.stop();
  15355. t2.join();
  15356. t.join();
  15357. ASSERT_FALSE(ssl_svr1.is_running());
  15358. });
  15359. ssl_svr1.wait_until_ready();
  15360. ssl_svr2.wait_until_ready();
  15361. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15362. std::string cert;
  15363. read_file(SERVER_CERT2_FILE, cert);
  15364. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15365. cli.enable_server_certificate_verification(true);
  15366. cli.set_follow_location(true);
  15367. cli.set_connection_timeout(30);
  15368. auto res = cli.Get("/index");
  15369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15370. ASSERT_EQ(StatusCode::OK_200, res->status);
  15371. }
  15372. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15373. // so a host signed by a system CA verifies even though a custom CA is set
  15374. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15375. std::string cert;
  15376. read_file(SERVER_CERT2_FILE, cert);
  15377. SSLClient cli("google.com");
  15378. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15379. cli.enable_system_ca(true);
  15380. cli.enable_server_certificate_verification(true);
  15381. auto res = cli.Get("/");
  15382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15383. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15384. }
  15385. // The custom CA remains effective when combined with the system CA
  15386. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15387. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15388. ASSERT_TRUE(svr.is_valid());
  15389. svr.Get("/test", [&](const Request &, Response &res) {
  15390. res.set_content("test", "text/plain");
  15391. });
  15392. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15393. auto se = detail::scope_exit([&] {
  15394. svr.stop();
  15395. t.join();
  15396. ASSERT_FALSE(svr.is_running());
  15397. });
  15398. svr.wait_until_ready();
  15399. SSLClient cli("127.0.0.1", PORT);
  15400. std::string cert;
  15401. read_file(SERVER_CERT2_FILE, cert);
  15402. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15403. cli.enable_system_ca(true);
  15404. cli.enable_server_certificate_verification(true);
  15405. cli.set_connection_timeout(30);
  15406. auto res = cli.Get("/test");
  15407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15408. ASSERT_EQ(StatusCode::OK_200, res->status);
  15409. }
  15410. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15411. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15412. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15413. static CFDictionaryRef
  15414. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15415. const SecTrustSettingsResult *result) {
  15416. auto constraint =
  15417. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15418. &kCFTypeDictionaryValueCallBacks);
  15419. if (policy) {
  15420. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15421. }
  15422. if (policy_string) {
  15423. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15424. kCFStringEncodingUTF8);
  15425. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15426. CFRelease(str);
  15427. }
  15428. if (result) {
  15429. auto number_value = static_cast<SInt32>(*result);
  15430. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15431. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15432. CFRelease(number);
  15433. }
  15434. return constraint;
  15435. }
  15436. static SecTrustSettingsResult
  15437. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15438. auto trust_settings =
  15439. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15440. for (auto constraint : constraints) {
  15441. CFArrayAppendValue(trust_settings, constraint);
  15442. CFRelease(constraint);
  15443. }
  15444. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15445. CFRelease(trust_settings);
  15446. return result;
  15447. }
  15448. // The system CA loader takes a Keychain certificate as a trusted root only
  15449. // when its Trust Settings say so for SSL, not merely because it has some.
  15450. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15451. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15452. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15453. const auto deny = kSecTrustSettingsResultDeny;
  15454. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15455. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15456. auto x509_policy = SecPolicyCreateBasicX509();
  15457. // "Always Trust", which stores no constraint at all
  15458. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15459. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15460. ssl_trust_settings_result(
  15461. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15462. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15463. ssl_trust_settings_result(
  15464. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15465. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15466. ssl_trust_settings_result(
  15467. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15468. // "Never Trust", for everything or for SSL
  15469. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15470. ssl_trust_settings_result(
  15471. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15472. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15473. ssl_trust_settings_result(
  15474. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15475. // Trusted for another policy, for one host, or not at all
  15476. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15477. ssl_trust_settings_result(
  15478. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15479. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15480. ssl_trust_settings_result({make_usage_constraint(
  15481. ssl_policy, "www.example.com", &trust_root)}));
  15482. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15483. ssl_trust_settings_result(
  15484. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15485. // The first constraint that applies to SSL decides
  15486. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15487. ssl_trust_settings_result(
  15488. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15489. make_usage_constraint(nullptr, nullptr, &deny)}));
  15490. CFRelease(x509_policy);
  15491. CFRelease(ssl_policy);
  15492. }
  15493. #endif
  15494. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15495. // skip chain verification entirely (only the certificate identity was
  15496. // checked), so a server presenting an untrusted certificate with a matching
  15497. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15498. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15499. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15500. ASSERT_TRUE(svr.is_valid());
  15501. svr.Get("/test", [&](const Request &, Response &res) {
  15502. res.set_content("test", "text/plain");
  15503. });
  15504. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15505. auto se = detail::scope_exit([&] {
  15506. svr.stop();
  15507. t.join();
  15508. ASSERT_FALSE(svr.is_running());
  15509. });
  15510. svr.wait_until_ready();
  15511. SSLClient cli("127.0.0.1", PORT);
  15512. std::string cert;
  15513. // A trusted CA that did not sign the server certificate. The server cert
  15514. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15515. // this connection.
  15516. read_file(CLIENT_CA_CERT_FILE, cert);
  15517. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15518. cli.enable_server_certificate_verification(true);
  15519. cli.set_connection_timeout(30);
  15520. auto res = cli.Get("/test");
  15521. ASSERT_FALSE(res);
  15522. }
  15523. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15524. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15525. // CA that failed to come through fails verification instead of trusting them.
  15526. // (wolfSSL does not list the system CAs it loaded.)
  15527. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15528. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15529. ASSERT_TRUE(svr.is_valid());
  15530. auto port = svr.bind_to_any_port("127.0.0.1");
  15531. ASSERT_LT(0, port);
  15532. thread t = thread([&] { svr.listen_after_bind(); });
  15533. auto se = detail::scope_exit([&] {
  15534. svr.stop();
  15535. t.join();
  15536. ASSERT_FALSE(svr.is_running());
  15537. });
  15538. svr.wait_until_ready();
  15539. // The CAs a client trusts once its first request has loaded them
  15540. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15541. Client cli("https://127.0.0.1:" + std::to_string(port));
  15542. setup(cli);
  15543. cli.Get("/");
  15544. return tls::get_ca_names(cli.tls_context()).size();
  15545. };
  15546. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15547. EXPECT_EQ(0u,
  15548. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15549. }
  15550. #endif
  15551. // A TLS setting changed between requests applies to the next one, not just to
  15552. // the next connection
  15553. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15554. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15555. ASSERT_TRUE(svr.is_valid());
  15556. svr.Get("/", [](const Request &req, Response &res) {
  15557. res.set_content(std::to_string(req.remote_port), "text/plain");
  15558. });
  15559. auto port = svr.bind_to_any_port("127.0.0.1");
  15560. ASSERT_LT(0, port);
  15561. thread t = thread([&] { svr.listen_after_bind(); });
  15562. auto se = detail::scope_exit([&] {
  15563. svr.stop();
  15564. t.join();
  15565. ASSERT_FALSE(svr.is_running());
  15566. });
  15567. svr.wait_until_ready();
  15568. SSLClient cli("127.0.0.1", port);
  15569. cli.set_keep_alive(true);
  15570. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15571. cli.enable_server_certificate_verification(false);
  15572. // The port the request went out from, so a new one means a new connection
  15573. auto client_port = [&] {
  15574. auto res = cli.Get("/");
  15575. return res ? res->body : std::string();
  15576. };
  15577. auto last = client_port();
  15578. ASSERT_FALSE(last.empty());
  15579. // Setting a value it already has keeps the connection
  15580. cli.enable_server_certificate_verification(false);
  15581. cli.enable_server_hostname_verification(true);
  15582. EXPECT_EQ(last, client_port());
  15583. cli.enable_server_certificate_verification(true);
  15584. auto res = cli.Get("/");
  15585. EXPECT_FALSE(res);
  15586. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15587. std::string ca;
  15588. read_file(SERVER_CERT2_FILE, ca);
  15589. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15590. last = client_port();
  15591. ASSERT_FALSE(last.empty());
  15592. std::vector<std::function<void()>> setters = {
  15593. [&] { cli.enable_server_hostname_verification(false); },
  15594. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15595. [&] {
  15596. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15597. },
  15598. [&] {
  15599. cli.set_server_certificate_verifier(
  15600. [](const tls::VerifyContext &) { return true; });
  15601. },
  15602. [&] {
  15603. cli.set_session_verifier(
  15604. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15605. },
  15606. };
  15607. for (const auto &setter : setters) {
  15608. setter();
  15609. auto next = client_port();
  15610. ASSERT_FALSE(next.empty());
  15611. EXPECT_NE(last, next);
  15612. last = next;
  15613. }
  15614. cli.set_session_verifier(
  15615. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15616. auto handle = cli.open_stream("GET", "/");
  15617. EXPECT_FALSE(handle.is_valid());
  15618. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15619. }
  15620. // A PEM given to create_ca_store() needs no NUL after it
  15621. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15622. std::string pem;
  15623. read_file(SERVER_CERT2_FILE, pem);
  15624. auto buf = pem + "X";
  15625. auto store = tls::create_ca_store(buf.data(), pem.size());
  15626. EXPECT_TRUE(store != nullptr);
  15627. SSLClient cli("localhost");
  15628. cli.set_ca_cert_store(store);
  15629. }
  15630. // enable_system_ca(false) prevents system CA loading entirely
  15631. TEST(SSLClientTest, DisableSystemCa_Online) {
  15632. SSLClient cli("google.com");
  15633. cli.enable_system_ca(false);
  15634. cli.enable_server_certificate_verification(true);
  15635. auto res = cli.Get("/");
  15636. ASSERT_FALSE(res);
  15637. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15638. // itself when the CA chain is empty
  15639. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15640. res.error() == Error::SSLConnection);
  15641. }
  15642. // The universal Client forwards enable_system_ca()
  15643. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15644. std::string cert;
  15645. read_file(SERVER_CERT2_FILE, cert);
  15646. Client cli("https://google.com");
  15647. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15648. cli.enable_system_ca(true);
  15649. cli.enable_server_certificate_verification(true);
  15650. auto res = cli.Get("/");
  15651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15652. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15653. }
  15654. // The system CA policy must carry over to the client created internally for
  15655. // following a cross-host HTTPS redirect
  15656. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15657. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15658. ASSERT_TRUE(svr.is_valid());
  15659. svr.Get("/index", [&](const Request &, Response &res) {
  15660. res.set_redirect("https://www.google.com/");
  15661. });
  15662. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15663. auto se = detail::scope_exit([&] {
  15664. svr.stop();
  15665. t.join();
  15666. ASSERT_FALSE(svr.is_running());
  15667. });
  15668. svr.wait_until_ready();
  15669. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15670. std::string cert;
  15671. read_file(SERVER_CERT2_FILE, cert);
  15672. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15673. cli.enable_system_ca(true);
  15674. cli.enable_server_certificate_verification(true);
  15675. cli.set_follow_location(true);
  15676. cli.set_connection_timeout(30);
  15677. // Receiving any response proves the redirect client completed the TLS
  15678. // handshake with a system-CA-signed host
  15679. auto res = cli.Get("/index");
  15680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15681. }
  15682. TEST(MultipartFormDataTest, LargeData) {
  15683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15684. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15685. const ContentReader &content_reader) {
  15686. if (req.is_multipart_form_data()) {
  15687. std::vector<FormData> items;
  15688. content_reader(
  15689. [&](const FormData &file) {
  15690. items.push_back(file);
  15691. return true;
  15692. },
  15693. [&](const char *data, size_t data_length) {
  15694. items.back().content.append(data, data_length);
  15695. return true;
  15696. });
  15697. EXPECT_TRUE(std::string(items[0].name) == "document");
  15698. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15699. EXPECT_TRUE(items[0].filename == "2MB_data");
  15700. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15701. EXPECT_TRUE(items[1].name == "hello");
  15702. EXPECT_TRUE(items[1].content == "world");
  15703. EXPECT_TRUE(items[1].filename == "");
  15704. EXPECT_TRUE(items[1].content_type == "");
  15705. } else {
  15706. std::string body;
  15707. content_reader([&](const char *data, size_t data_length) {
  15708. body.append(data, data_length);
  15709. return true;
  15710. });
  15711. }
  15712. });
  15713. auto port = svr.bind_to_any_port(HOST);
  15714. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15715. auto se = detail::scope_exit([&] {
  15716. svr.stop();
  15717. t.join();
  15718. ASSERT_FALSE(svr.is_running());
  15719. });
  15720. svr.wait_until_ready();
  15721. {
  15722. std::string data(1024 * 1024 * 2, '.');
  15723. std::stringstream buffer;
  15724. buffer << data;
  15725. SSLClient cli(HOST, port);
  15726. cli.enable_server_certificate_verification(false);
  15727. UploadFormDataItems items{
  15728. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15729. {"hello", "world", "", ""},
  15730. };
  15731. auto res = cli.Post("/post", items);
  15732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15733. ASSERT_EQ(StatusCode::OK_200, res->status);
  15734. }
  15735. }
  15736. TEST(MultipartFormDataTest, DataProviderItems) {
  15737. std::random_device seed_gen;
  15738. std::mt19937 random(seed_gen());
  15739. std::string rand1;
  15740. rand1.resize(1000);
  15741. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15742. std::string rand2;
  15743. rand2.resize(3000);
  15744. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15746. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15747. const ContentReader &content_reader) {
  15748. ASSERT_FALSE(req.is_multipart_form_data());
  15749. std::string body;
  15750. content_reader([&](const char *data, size_t data_length) {
  15751. body.append(data, data_length);
  15752. return true;
  15753. });
  15754. EXPECT_EQ(body, "");
  15755. });
  15756. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15757. const ContentReader &content_reader) {
  15758. ASSERT_TRUE(req.is_multipart_form_data());
  15759. std::vector<FormData> items;
  15760. content_reader(
  15761. [&](const FormData &file) {
  15762. items.push_back(file);
  15763. return true;
  15764. },
  15765. [&](const char *data, size_t data_length) {
  15766. items.back().content.append(data, data_length);
  15767. return true;
  15768. });
  15769. ASSERT_TRUE(items.size() == 2);
  15770. EXPECT_EQ(std::string(items[0].name), "name1");
  15771. EXPECT_EQ(items[0].content, "Testing123");
  15772. EXPECT_EQ(items[0].filename, "filename1");
  15773. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15774. EXPECT_EQ(items[1].name, "name2");
  15775. EXPECT_EQ(items[1].content, "Testing456");
  15776. EXPECT_EQ(items[1].filename, "");
  15777. EXPECT_EQ(items[1].content_type, "");
  15778. });
  15779. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15780. const ContentReader &content_reader) {
  15781. ASSERT_TRUE(req.is_multipart_form_data());
  15782. std::vector<FormData> items;
  15783. content_reader(
  15784. [&](const FormData &file) {
  15785. items.push_back(file);
  15786. return true;
  15787. },
  15788. [&](const char *data, size_t data_length) {
  15789. items.back().content.append(data, data_length);
  15790. return true;
  15791. });
  15792. ASSERT_TRUE(items.size() == 2);
  15793. EXPECT_EQ(items[0].name, "name3");
  15794. EXPECT_EQ(items[0].content, rand1);
  15795. EXPECT_EQ(items[0].filename, "filename3");
  15796. EXPECT_EQ(items[0].content_type, "");
  15797. EXPECT_EQ(items[1].name, "name4");
  15798. EXPECT_EQ(items[1].content, rand2);
  15799. EXPECT_EQ(items[1].filename, "filename4");
  15800. EXPECT_EQ(items[1].content_type, "");
  15801. });
  15802. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15803. const ContentReader &content_reader) {
  15804. ASSERT_TRUE(req.is_multipart_form_data());
  15805. std::vector<FormData> items;
  15806. content_reader(
  15807. [&](const FormData &file) {
  15808. items.push_back(file);
  15809. return true;
  15810. },
  15811. [&](const char *data, size_t data_length) {
  15812. items.back().content.append(data, data_length);
  15813. return true;
  15814. });
  15815. ASSERT_TRUE(items.size() == 4);
  15816. EXPECT_EQ(std::string(items[0].name), "name1");
  15817. EXPECT_EQ(items[0].content, "Testing123");
  15818. EXPECT_EQ(items[0].filename, "filename1");
  15819. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15820. EXPECT_EQ(items[1].name, "name2");
  15821. EXPECT_EQ(items[1].content, "Testing456");
  15822. EXPECT_EQ(items[1].filename, "");
  15823. EXPECT_EQ(items[1].content_type, "");
  15824. EXPECT_EQ(items[2].name, "name3");
  15825. EXPECT_EQ(items[2].content, rand1);
  15826. EXPECT_EQ(items[2].filename, "filename3");
  15827. EXPECT_EQ(items[2].content_type, "");
  15828. EXPECT_EQ(items[3].name, "name4");
  15829. EXPECT_EQ(items[3].content, rand2);
  15830. EXPECT_EQ(items[3].filename, "filename4");
  15831. EXPECT_EQ(items[3].content_type, "");
  15832. });
  15833. auto port = svr.bind_to_any_port("localhost");
  15834. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15835. auto se = detail::scope_exit([&] {
  15836. svr.stop();
  15837. t.join();
  15838. ASSERT_FALSE(svr.is_running());
  15839. });
  15840. svr.wait_until_ready();
  15841. {
  15842. SSLClient cli("localhost", port);
  15843. cli.enable_server_certificate_verification(false);
  15844. UploadFormDataItems items{
  15845. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15846. {"name2", "Testing456", "", ""}, // not a file
  15847. };
  15848. {
  15849. auto res = cli.Post("/post-none", {}, {}, {});
  15850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15851. ASSERT_EQ(StatusCode::OK_200, res->status);
  15852. }
  15853. FormDataProviderItems providers;
  15854. {
  15855. auto res =
  15856. cli.Post("/post-items", {}, items, providers); // empty providers
  15857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15858. ASSERT_EQ(StatusCode::OK_200, res->status);
  15859. }
  15860. providers.push_back({"name3",
  15861. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15862. // test the offset is given correctly at each step
  15863. if (!offset)
  15864. sink.os.write(rand1.data(), 30);
  15865. else if (offset == 30)
  15866. sink.os.write(rand1.data() + 30, 300);
  15867. else if (offset == 330)
  15868. sink.os.write(rand1.data() + 330, 670);
  15869. else if (offset == rand1.size())
  15870. sink.done();
  15871. return true;
  15872. },
  15873. "filename3",
  15874. {}});
  15875. providers.push_back({"name4",
  15876. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15877. // test the offset is given correctly at each step
  15878. if (!offset)
  15879. sink.os.write(rand2.data(), 2000);
  15880. else if (offset == 2000)
  15881. sink.os.write(rand2.data() + 2000, 1);
  15882. else if (offset == 2001)
  15883. sink.os.write(rand2.data() + 2001, 999);
  15884. else if (offset == rand2.size())
  15885. sink.done();
  15886. return true;
  15887. },
  15888. "filename4",
  15889. {}});
  15890. {
  15891. auto res = cli.Post("/post-providers", {}, {}, providers);
  15892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15893. ASSERT_EQ(StatusCode::OK_200, res->status);
  15894. }
  15895. {
  15896. auto res = cli.Post("/post-both", {}, items, providers);
  15897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15898. ASSERT_EQ(StatusCode::OK_200, res->status);
  15899. }
  15900. }
  15901. }
  15902. TEST(MultipartFormDataTest, BadHeader) {
  15903. Server svr;
  15904. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15905. res.set_content("ok", "text/plain");
  15906. });
  15907. thread t = thread([&] { svr.listen(HOST, PORT); });
  15908. auto se = detail::scope_exit([&] {
  15909. svr.stop();
  15910. t.join();
  15911. ASSERT_FALSE(svr.is_running());
  15912. });
  15913. svr.wait_until_ready();
  15914. const std::string body =
  15915. "This is the preamble. It is to be ignored, though it\r\n"
  15916. "is a handy place for composition agents to include an\r\n"
  15917. "explanatory note to non-MIME conformant readers.\r\n"
  15918. "\r\n"
  15919. "\r\n"
  15920. "--simple boundary\r\n"
  15921. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15922. ": BAD...\r\n"
  15923. "\r\n"
  15924. "value1\r\n"
  15925. "--simple boundary\r\n"
  15926. "Content-Disposition: form-data; name=\"field2\"; "
  15927. "filename=\"example.txt\"\r\n"
  15928. "\r\n"
  15929. "value2\r\n"
  15930. "--simple boundary--\r\n"
  15931. "This is the epilogue. It is also to be ignored.\r\n";
  15932. std::string content_type =
  15933. R"(multipart/form-data; boundary="simple boundary")";
  15934. Client cli(HOST, PORT);
  15935. auto res = cli.Post("/post", body, content_type.c_str());
  15936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15937. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15938. }
  15939. TEST(MultipartFormDataTest, WithPreamble) {
  15940. Server svr;
  15941. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15942. res.set_content("ok", "text/plain");
  15943. });
  15944. thread t = thread([&] { svr.listen(HOST, PORT); });
  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. const std::string body =
  15952. "This is the preamble. It is to be ignored, though it\r\n"
  15953. "is a handy place for composition agents to include an\r\n"
  15954. "explanatory note to non-MIME conformant readers.\r\n"
  15955. "\r\n"
  15956. "\r\n"
  15957. "--simple boundary\r\n"
  15958. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15959. "\r\n"
  15960. "value1\r\n"
  15961. "--simple boundary\r\n"
  15962. "Content-Disposition: form-data; name=\"field2\"; "
  15963. "filename=\"example.txt\"\r\n"
  15964. "\r\n"
  15965. "value2\r\n"
  15966. "--simple boundary--\r\n"
  15967. "This is the epilogue. It is also to be ignored.\r\n";
  15968. std::string content_type =
  15969. R"(multipart/form-data; boundary="simple boundary")";
  15970. Client cli(HOST, PORT);
  15971. auto res = cli.Post("/post", body, content_type.c_str());
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. EXPECT_EQ(StatusCode::OK_200, res->status);
  15974. }
  15975. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15977. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15978. const ContentReader &content_reader) {
  15979. if (req.is_multipart_form_data()) {
  15980. std::vector<FormData> items;
  15981. content_reader(
  15982. [&](const FormData &file) {
  15983. items.push_back(file);
  15984. return true;
  15985. },
  15986. [&](const char *data, size_t data_length) {
  15987. items.back().content.append(data, data_length);
  15988. return true;
  15989. });
  15990. EXPECT_TRUE(std::string(items[0].name) == "document");
  15991. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15992. EXPECT_TRUE(items[0].filename == "2MB_data");
  15993. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15994. EXPECT_TRUE(items[1].name == "hello");
  15995. EXPECT_TRUE(items[1].content == "world");
  15996. EXPECT_TRUE(items[1].filename == "");
  15997. EXPECT_TRUE(items[1].content_type == "");
  15998. } else {
  15999. std::string body;
  16000. content_reader([&](const char *data, size_t data_length) {
  16001. body.append(data, data_length);
  16002. return true;
  16003. });
  16004. }
  16005. });
  16006. auto port = svr.bind_to_any_port("localhost");
  16007. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16008. auto se = detail::scope_exit([&] {
  16009. svr.stop();
  16010. t.join();
  16011. ASSERT_FALSE(svr.is_running());
  16012. });
  16013. svr.wait_until_ready();
  16014. {
  16015. std::string data(1024 * 1024 * 2, '.');
  16016. std::stringstream buffer;
  16017. buffer << data;
  16018. SSLClient cli("localhost", port);
  16019. cli.enable_server_certificate_verification(false);
  16020. UploadFormDataItems items{
  16021. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16022. {"hello", "world", "", ""},
  16023. };
  16024. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16026. ASSERT_EQ(StatusCode::OK_200, res->status);
  16027. }
  16028. }
  16029. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16030. std::string data(1024 * 1024 * 2, '&');
  16031. std::stringstream buffer;
  16032. buffer << data;
  16033. Client cli("https://localhost:8080");
  16034. UploadFormDataItems items{
  16035. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16036. {"hello", "world", "", ""},
  16037. };
  16038. for (const char &c : " \t\r\n") {
  16039. auto res =
  16040. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16041. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16042. ASSERT_FALSE(res);
  16043. }
  16044. }
  16045. TEST(MultipartFormDataTest, PutFormData) {
  16046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16047. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16048. const ContentReader &content_reader) {
  16049. if (req.is_multipart_form_data()) {
  16050. std::vector<FormData> items;
  16051. content_reader(
  16052. [&](const FormData &file) {
  16053. items.push_back(file);
  16054. return true;
  16055. },
  16056. [&](const char *data, size_t data_length) {
  16057. items.back().content.append(data, data_length);
  16058. return true;
  16059. });
  16060. EXPECT_TRUE(std::string(items[0].name) == "document");
  16061. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16062. EXPECT_TRUE(items[0].filename == "2MB_data");
  16063. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16064. EXPECT_TRUE(items[1].name == "hello");
  16065. EXPECT_TRUE(items[1].content == "world");
  16066. EXPECT_TRUE(items[1].filename == "");
  16067. EXPECT_TRUE(items[1].content_type == "");
  16068. } else {
  16069. std::string body;
  16070. content_reader([&](const char *data, size_t data_length) {
  16071. body.append(data, data_length);
  16072. return true;
  16073. });
  16074. }
  16075. });
  16076. auto port = svr.bind_to_any_port("localhost");
  16077. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16078. auto se = detail::scope_exit([&] {
  16079. svr.stop();
  16080. t.join();
  16081. ASSERT_FALSE(svr.is_running());
  16082. });
  16083. svr.wait_until_ready();
  16084. {
  16085. std::string data(1024 * 1024 * 2, '&');
  16086. std::stringstream buffer;
  16087. buffer << data;
  16088. SSLClient cli("localhost", port);
  16089. cli.enable_server_certificate_verification(false);
  16090. UploadFormDataItems items{
  16091. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16092. {"hello", "world", "", ""},
  16093. };
  16094. auto res = cli.Put("/put", items);
  16095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16096. ASSERT_EQ(StatusCode::OK_200, res->status);
  16097. }
  16098. }
  16099. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16101. svr.Put("/put_customboundary",
  16102. [&](const Request &req, const Response & /*res*/,
  16103. const ContentReader &content_reader) {
  16104. if (req.is_multipart_form_data()) {
  16105. std::vector<FormData> items;
  16106. content_reader(
  16107. [&](const FormData &file) {
  16108. items.push_back(file);
  16109. return true;
  16110. },
  16111. [&](const char *data, size_t data_length) {
  16112. items.back().content.append(data, data_length);
  16113. return true;
  16114. });
  16115. EXPECT_TRUE(std::string(items[0].name) == "document");
  16116. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16117. EXPECT_TRUE(items[0].filename == "2MB_data");
  16118. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16119. EXPECT_TRUE(items[1].name == "hello");
  16120. EXPECT_TRUE(items[1].content == "world");
  16121. EXPECT_TRUE(items[1].filename == "");
  16122. EXPECT_TRUE(items[1].content_type == "");
  16123. } else {
  16124. std::string body;
  16125. content_reader([&](const char *data, size_t data_length) {
  16126. body.append(data, data_length);
  16127. return true;
  16128. });
  16129. }
  16130. });
  16131. auto port = svr.bind_to_any_port("localhost");
  16132. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16133. auto se = detail::scope_exit([&] {
  16134. svr.stop();
  16135. t.join();
  16136. ASSERT_FALSE(svr.is_running());
  16137. });
  16138. svr.wait_until_ready();
  16139. {
  16140. std::string data(1024 * 1024 * 2, '&');
  16141. std::stringstream buffer;
  16142. buffer << data;
  16143. SSLClient cli("localhost", port);
  16144. cli.enable_server_certificate_verification(false);
  16145. UploadFormDataItems items{
  16146. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16147. {"hello", "world", "", ""},
  16148. };
  16149. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16151. ASSERT_EQ(StatusCode::OK_200, res->status);
  16152. }
  16153. }
  16154. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16155. std::string data(1024 * 1024 * 2, '&');
  16156. std::stringstream buffer;
  16157. buffer << data;
  16158. Client cli("https://localhost:8080");
  16159. cli.enable_server_certificate_verification(false);
  16160. UploadFormDataItems items{
  16161. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16162. {"hello", "world", "", ""},
  16163. };
  16164. for (const char &c : " \t\r\n") {
  16165. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16166. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16167. ASSERT_FALSE(res);
  16168. }
  16169. }
  16170. TEST(MultipartFormDataTest, AlternateFilename) {
  16171. auto handled = false;
  16172. Server svr;
  16173. svr.Post("/test", [&](const Request &req, Response &res) {
  16174. ASSERT_EQ(2u, req.form.files.size());
  16175. ASSERT_EQ(1u, req.form.fields.size());
  16176. // Test files
  16177. const auto &file1 = req.form.get_file("file1");
  16178. ASSERT_EQ("file1", file1.name);
  16179. ASSERT_EQ("A.txt", file1.filename);
  16180. ASSERT_EQ("text/plain", file1.content_type);
  16181. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16182. const auto &file2 = req.form.get_file("file2");
  16183. ASSERT_EQ("file2", file2.name);
  16184. ASSERT_EQ("a.html", file2.filename);
  16185. ASSERT_EQ("text/html", file2.content_type);
  16186. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16187. file2.content);
  16188. // Test text field
  16189. const auto &text = req.form.get_field("text");
  16190. ASSERT_EQ("text default", text);
  16191. res.set_content("ok", "text/plain");
  16192. handled = true;
  16193. });
  16194. thread t = thread([&] { svr.listen(HOST, PORT); });
  16195. auto se = detail::scope_exit([&] {
  16196. svr.stop();
  16197. t.join();
  16198. ASSERT_FALSE(svr.is_running());
  16199. ASSERT_TRUE(handled);
  16200. });
  16201. svr.wait_until_ready();
  16202. auto req = "POST /test HTTP/1.1\r\n"
  16203. "Host: localhost\r\n"
  16204. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16205. "Content-Length: 399\r\n"
  16206. "\r\n"
  16207. "----------\r\n"
  16208. "Content-Disposition: form-data; name=\"text\"\r\n"
  16209. "\r\n"
  16210. "text default\r\n"
  16211. "----------\r\n"
  16212. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16213. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16214. "Content-Type: text/plain\r\n"
  16215. "\r\n"
  16216. "Content of a.txt.\r\n"
  16217. "\r\n"
  16218. "----------\r\n"
  16219. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16220. "\"a.html\"\r\n"
  16221. "Content-Type: text/html\r\n"
  16222. "\r\n"
  16223. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16224. "\r\n"
  16225. "------------\r\n";
  16226. ASSERT_TRUE(send_request(1, req));
  16227. }
  16228. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16229. auto handled = false;
  16230. Server svr;
  16231. svr.Post("/test", [&](const Request &req, Response &res) {
  16232. // Case-insensitive "utf-8''" prefix with a long value
  16233. const auto &file = req.form.get_file("file1");
  16234. ASSERT_EQ("file1", file.name);
  16235. // 8000 chars exercises both the Content-Disposition parser and the
  16236. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16237. // Prior to the fix, std::regex_match on this header would cause O(N)
  16238. // stack recursion in libstdc++, leading to SIGSEGV.
  16239. std::string expected_filename(8000, 'A');
  16240. ASSERT_EQ(expected_filename, file.filename);
  16241. res.set_content("ok", "text/plain");
  16242. handled = true;
  16243. });
  16244. thread t = thread([&] { svr.listen(HOST, PORT); });
  16245. auto se = detail::scope_exit([&] {
  16246. svr.stop();
  16247. t.join();
  16248. ASSERT_FALSE(svr.is_running());
  16249. ASSERT_TRUE(handled);
  16250. });
  16251. svr.wait_until_ready();
  16252. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16253. // Regression test for GHSA-qq6v-r583-3h69
  16254. std::string long_filename(8000, 'A');
  16255. std::string body = "----------\r\n"
  16256. "Content-Disposition: form-data; name=\"file1\"; "
  16257. "filename*=\"Utf-8''" +
  16258. long_filename +
  16259. "\"\r\n"
  16260. "\r\n"
  16261. "hello\r\n"
  16262. "------------\r\n";
  16263. auto req = "POST /test HTTP/1.1\r\n"
  16264. "Host: localhost\r\n"
  16265. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16266. "Content-Length: " +
  16267. std::to_string(body.size()) + "\r\n\r\n" + body;
  16268. ASSERT_TRUE(send_request(1, req));
  16269. }
  16270. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16271. auto handled = false;
  16272. Server svr;
  16273. svr.Post("/test", [&](const Request &req, Response &) {
  16274. ASSERT_EQ(2u, req.form.fields.size());
  16275. const auto &text1 = req.form.get_field("text1");
  16276. ASSERT_EQ("text1", text1);
  16277. const auto &text2 = req.form.get_field("text2");
  16278. ASSERT_EQ("text2", text2);
  16279. handled = true;
  16280. });
  16281. thread t = thread([&] { svr.listen(HOST, PORT); });
  16282. auto se = detail::scope_exit([&] {
  16283. svr.stop();
  16284. t.join();
  16285. ASSERT_FALSE(svr.is_running());
  16286. ASSERT_TRUE(handled);
  16287. });
  16288. svr.wait_until_ready();
  16289. auto req = "POST /test HTTP/1.1\r\n"
  16290. "Host: localhost\r\n"
  16291. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16292. "Content-Length: 146\r\n"
  16293. "\r\n----------\r\n"
  16294. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16295. "\r\n"
  16296. "text1"
  16297. "\r\n----------\r\n"
  16298. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16299. "\r\n"
  16300. "text2"
  16301. "\r\n------------";
  16302. std::string response;
  16303. ASSERT_TRUE(send_request(1, req, &response));
  16304. ASSERT_EQ("200", response.substr(9, 3));
  16305. }
  16306. TEST(MultipartFormDataTest, ContentLength) {
  16307. auto handled = false;
  16308. Server svr;
  16309. svr.Post("/test", [&](const Request &req, Response &) {
  16310. ASSERT_EQ(2u, req.form.fields.size());
  16311. const auto &text1 = req.form.get_field("text1");
  16312. ASSERT_EQ("text1", text1);
  16313. const auto &text2 = req.form.get_field("text2");
  16314. ASSERT_EQ("text2", text2);
  16315. handled = true;
  16316. });
  16317. thread t = thread([&] { svr.listen(HOST, PORT); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. ASSERT_TRUE(handled);
  16323. });
  16324. svr.wait_until_ready();
  16325. auto req = "POST /test HTTP/1.1\r\n"
  16326. "Host: localhost\r\n"
  16327. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16328. "Content-Length: 167\r\n"
  16329. "\r\n----------\r\n"
  16330. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16331. "Content-Length: 5\r\n"
  16332. "\r\n"
  16333. "text1"
  16334. "\r\n----------\r\n"
  16335. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16336. "\r\n"
  16337. "text2"
  16338. "\r\n------------\r\n";
  16339. std::string response;
  16340. ASSERT_TRUE(send_request(1, req, &response));
  16341. ASSERT_EQ("200", response.substr(9, 3));
  16342. }
  16343. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16344. auto handled = false;
  16345. Server svr;
  16346. svr.Post("/test", [&](const Request &req, Response &) {
  16347. ASSERT_EQ(2u, req.form.fields.size());
  16348. const auto &text1 = req.form.get_field("text1");
  16349. ASSERT_EQ("text1", text1);
  16350. // TODO: Add header access for text fields if needed
  16351. const auto &text2 = req.form.get_field("text2");
  16352. ASSERT_EQ("text2", text2);
  16353. // TODO: Header access for text fields needs to be implemented
  16354. // auto &headers = it->second.headers;
  16355. // ASSERT_EQ(3U, headers.size());
  16356. // auto custom_header = headers.find("x-whatever");
  16357. // ASSERT_TRUE(custom_header != headers.end());
  16358. // ASSERT_NE("customvalue", custom_header->second);
  16359. // ASSERT_EQ("CustomValue", custom_header->second);
  16360. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16361. handled = true;
  16362. });
  16363. thread t = thread([&] { svr.listen(HOST, PORT); });
  16364. auto se = detail::scope_exit([&] {
  16365. svr.stop();
  16366. t.join();
  16367. ASSERT_FALSE(svr.is_running());
  16368. ASSERT_TRUE(handled);
  16369. });
  16370. svr.wait_until_ready();
  16371. auto req = "POST /test HTTP/1.1\r\n"
  16372. "Host: localhost\r\n"
  16373. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16374. "Content-Length: 232\r\n"
  16375. "\r\n----------\r\n"
  16376. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16377. "Content-Length: 5\r\n"
  16378. "X-Test: 1\r\n"
  16379. "\r\n"
  16380. "text1"
  16381. "\r\n----------\r\n"
  16382. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16383. "Content-Type: text/plain\r\n"
  16384. "X-Whatever: CustomValue\r\n"
  16385. "\r\n"
  16386. "text2"
  16387. "\r\n------------\r\n"
  16388. "That should be disregarded. Not even read";
  16389. std::string response;
  16390. ASSERT_TRUE(send_request(1, req, &response));
  16391. ASSERT_EQ("200", response.substr(9, 3));
  16392. }
  16393. TEST(MultipartFormDataTest, LargeHeader) {
  16394. auto handled = false;
  16395. Server svr;
  16396. svr.Post("/test", [&](const Request &req, Response &) {
  16397. ASSERT_EQ(1u, req.form.fields.size());
  16398. const auto &text = req.form.get_field("name1");
  16399. ASSERT_EQ("text1", text);
  16400. handled = true;
  16401. });
  16402. thread t = thread([&] { svr.listen(HOST, PORT); });
  16403. auto se = detail::scope_exit([&] {
  16404. svr.stop();
  16405. t.join();
  16406. ASSERT_FALSE(svr.is_running());
  16407. ASSERT_TRUE(handled);
  16408. });
  16409. svr.wait_until_ready();
  16410. auto boundary = std::string("cpp-httplib-multipart-data");
  16411. std::string content = "--" + boundary +
  16412. "\r\n"
  16413. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16414. "\r\n"
  16415. "text1\r\n"
  16416. "--" +
  16417. boundary + "--\r\n";
  16418. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16419. "Host: localhost\r\n"
  16420. "Content-Type: multipart/form-data;boundary=" +
  16421. boundary +
  16422. "\r\n"
  16423. "Content-Length: " +
  16424. std::to_string(content.size()) +
  16425. "\r\n"
  16426. "Dummy-Header: ";
  16427. std::string header_suffix = "\r\n"
  16428. "\r\n";
  16429. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16430. size_t header_dummy_size =
  16431. read_buff_size -
  16432. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16433. auto header_dummy = std::string(header_dummy_size, '@');
  16434. auto req = header_prefix + header_dummy + header_suffix + content;
  16435. std::string response;
  16436. ASSERT_TRUE(send_request(1, req, &response));
  16437. ASSERT_EQ("200", response.substr(9, 3));
  16438. }
  16439. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16440. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16441. // (not chunked Transfer-Encoding) after the streaming refactor.
  16442. auto handled = false;
  16443. Server svr;
  16444. svr.Post("/upload", [&](const Request &req, Response &res) {
  16445. auto cl_it = req.headers.find("Content-Length");
  16446. EXPECT_TRUE(cl_it != req.headers.end());
  16447. auto te_it = req.headers.find("Transfer-Encoding");
  16448. EXPECT_TRUE(te_it == req.headers.end());
  16449. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16450. res.set_content("ok", "text/plain");
  16451. handled = true;
  16452. });
  16453. auto port = svr.bind_to_any_port(HOST);
  16454. auto t = thread([&] { svr.listen_after_bind(); });
  16455. auto se = detail::scope_exit([&] {
  16456. svr.stop();
  16457. t.join();
  16458. ASSERT_FALSE(svr.is_running());
  16459. ASSERT_TRUE(handled);
  16460. });
  16461. svr.wait_until_ready();
  16462. UploadFormDataItems items = {
  16463. {"field1", "hello", "", "text/plain"},
  16464. {"file1", "world", "test.txt", "application/octet-stream"},
  16465. };
  16466. Client cli(HOST, port);
  16467. auto res = cli.Post("/upload", {}, items);
  16468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16469. EXPECT_EQ(StatusCode::OK_200, res->status);
  16470. }
  16471. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16472. // Verify that make_multipart_content_provider coalesces many small segments
  16473. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16474. constexpr size_t kItemCount = 1000;
  16475. UploadFormDataItems items;
  16476. items.reserve(kItemCount);
  16477. for (size_t i = 0; i < kItemCount; i++) {
  16478. items.push_back(
  16479. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16480. }
  16481. const std::string boundary = "----test-boundary";
  16482. auto content_length = detail::get_multipart_content_length(items, boundary);
  16483. auto provider = detail::make_multipart_content_provider(items, boundary);
  16484. // Drive the provider the same way write_content_with_progress does
  16485. size_t write_count = 0;
  16486. size_t total_bytes = 0;
  16487. DataSink sink;
  16488. size_t offset = 0;
  16489. sink.write = [&](const char *d, size_t l) -> bool {
  16490. (void)d;
  16491. write_count++;
  16492. total_bytes += l;
  16493. offset += l;
  16494. return true;
  16495. };
  16496. sink.is_writable = []() -> bool { return true; };
  16497. while (offset < content_length) {
  16498. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16499. }
  16500. EXPECT_EQ(content_length, total_bytes);
  16501. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16502. // With buffering into 64KB blocks, write_count should be much smaller.
  16503. auto segment_count = 3 * kItemCount + 1;
  16504. EXPECT_LT(write_count, segment_count / 10);
  16505. }
  16506. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16507. // Integration test: send many UploadFormDataItems and verify the server
  16508. // receives all of them correctly (#2410).
  16509. constexpr size_t kItemCount = 500;
  16510. auto handled = false;
  16511. Server svr;
  16512. svr.Post("/upload", [&](const Request &req, Response &res) {
  16513. EXPECT_EQ(kItemCount, req.form.fields.size());
  16514. for (size_t i = 0; i < kItemCount; i++) {
  16515. auto key = "field" + std::to_string(i);
  16516. auto val = "value" + std::to_string(i);
  16517. auto it = req.form.fields.find(key);
  16518. if (it != req.form.fields.end()) {
  16519. EXPECT_EQ(val, it->second.content);
  16520. } else {
  16521. ADD_FAILURE() << "Missing field: " << key;
  16522. }
  16523. }
  16524. res.set_content("ok", "text/plain");
  16525. handled = true;
  16526. });
  16527. auto port = svr.bind_to_any_port(HOST);
  16528. auto t = thread([&] { svr.listen_after_bind(); });
  16529. auto se = detail::scope_exit([&] {
  16530. svr.stop();
  16531. t.join();
  16532. ASSERT_FALSE(svr.is_running());
  16533. ASSERT_TRUE(handled);
  16534. });
  16535. svr.wait_until_ready();
  16536. UploadFormDataItems items;
  16537. items.reserve(kItemCount);
  16538. for (size_t i = 0; i < kItemCount; i++) {
  16539. items.push_back(
  16540. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16541. }
  16542. Client cli(HOST, port);
  16543. auto res = cli.Post("/upload", items);
  16544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16545. EXPECT_EQ(StatusCode::OK_200, res->status);
  16546. }
  16547. TEST(MultipartFormDataTest, MakeFileProvider) {
  16548. // Verify make_file_provider sends a file's contents correctly.
  16549. const std::string file_content(4096, 'Z');
  16550. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16551. {
  16552. std::ofstream ofs(tmp_path, std::ios::binary);
  16553. ofs.write(file_content.data(),
  16554. static_cast<std::streamsize>(file_content.size()));
  16555. }
  16556. auto handled = false;
  16557. Server svr;
  16558. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16559. const ContentReader &content_reader) {
  16560. ASSERT_TRUE(req.is_multipart_form_data());
  16561. std::vector<FormData> items;
  16562. content_reader(
  16563. [&](const FormData &file) {
  16564. items.push_back(file);
  16565. return true;
  16566. },
  16567. [&](const char *data, size_t data_length) {
  16568. items.back().content.append(data, data_length);
  16569. return true;
  16570. });
  16571. ASSERT_EQ(1u, items.size());
  16572. EXPECT_EQ("myfile", items[0].name);
  16573. EXPECT_EQ("data.bin", items[0].filename);
  16574. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16575. EXPECT_EQ(file_content, items[0].content);
  16576. handled = true;
  16577. });
  16578. auto port = svr.bind_to_any_port(HOST);
  16579. auto t = thread([&] { svr.listen_after_bind(); });
  16580. auto se = detail::scope_exit([&] {
  16581. svr.stop();
  16582. t.join();
  16583. ASSERT_FALSE(svr.is_running());
  16584. ASSERT_TRUE(handled);
  16585. std::remove(tmp_path.c_str());
  16586. });
  16587. svr.wait_until_ready();
  16588. FormDataProviderItems providers;
  16589. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16590. "application/octet-stream"));
  16591. Client cli(HOST, port);
  16592. auto res = cli.Post("/upload", {}, {}, providers);
  16593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16594. EXPECT_EQ(StatusCode::OK_200, res->status);
  16595. }
  16596. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16597. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16598. // (100) headers is rejected with a 400 Bad Request response.
  16599. Server svr;
  16600. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16601. res.set_content("ok", "text/plain");
  16602. });
  16603. thread t = thread([&] { svr.listen(HOST, PORT); });
  16604. auto se = detail::scope_exit([&] {
  16605. svr.stop();
  16606. t.join();
  16607. ASSERT_FALSE(svr.is_running());
  16608. });
  16609. svr.wait_until_ready();
  16610. // Build a multipart part with 101 custom headers (exceeding
  16611. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16612. std::stringstream body;
  16613. body << "--simpleboundary\r\n"
  16614. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16615. for (int i = 0; i < 101; i++) {
  16616. body << "X-Custom-Header-" << i << ": value\r\n";
  16617. }
  16618. body << "\r\n"
  16619. << "value1\r\n"
  16620. << "--simpleboundary--\r\n";
  16621. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16622. Client cli(HOST, PORT);
  16623. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16625. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16626. }
  16627. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16628. // A body that never contains the declared boundary must not be accumulated
  16629. // while the parser waits for it. Buffering it would also make every read
  16630. // rescan everything seen so far, which is quadratic in the body size.
  16631. Server svr;
  16632. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16633. res.set_content("ok", "text/plain");
  16634. });
  16635. auto port = svr.bind_to_any_port(HOST);
  16636. thread t = thread([&] { svr.listen_after_bind(); });
  16637. auto se = detail::scope_exit([&] {
  16638. svr.stop();
  16639. t.join();
  16640. ASSERT_FALSE(svr.is_running());
  16641. });
  16642. svr.wait_until_ready();
  16643. Client cli(HOST, port);
  16644. cli.set_read_timeout(60, 0);
  16645. cli.set_write_timeout(60, 0);
  16646. // '-' is the worst case: it matches the first character of the boundary, so
  16647. // every position has to be checked against it.
  16648. auto post_dashes = [&](size_t size) {
  16649. const std::string body(size, '-');
  16650. auto start = std::chrono::steady_clock::now();
  16651. auto res =
  16652. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16653. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16654. std::chrono::steady_clock::now() - start)
  16655. .count();
  16656. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16657. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16658. return ms;
  16659. };
  16660. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16661. // Windows.
  16662. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16663. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16664. // Comparing the two sizes rather than checking an absolute duration keeps
  16665. // this meaningful across build types and CI load, both of which move the
  16666. // absolute numbers by more than an order of magnitude. Four times the bytes
  16667. // costs about four times the time when parsing is linear, and about sixteen
  16668. // times when the body is buffered and rescanned.
  16669. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16670. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16671. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16672. << "ms, which suggests the body is being buffered and rescanned";
  16673. }
  16674. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16675. // A boundary can only be followed by CRLF or by "--", so anything else is
  16676. // malformed no matter what comes next. The parser must say so right away
  16677. // instead of buffering the rest of the declared body.
  16678. Server svr;
  16679. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16680. res.set_content("ok", "text/plain");
  16681. });
  16682. auto port = svr.bind_to_any_port(HOST);
  16683. thread t = thread([&] { svr.listen_after_bind(); });
  16684. auto se = detail::scope_exit([&] {
  16685. svr.stop();
  16686. t.join();
  16687. ASSERT_FALSE(svr.is_running());
  16688. });
  16689. svr.wait_until_ready();
  16690. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16691. // buffers instead of failing would still be waiting for the remaining bytes.
  16692. const std::string body = "--zzzz\r\n"
  16693. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16694. "\r\n"
  16695. "text1"
  16696. "\r\n--zzzzXX";
  16697. const std::string req = "POST /post HTTP/1.1\r\n"
  16698. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16699. "Content-Length: 1048576\r\n"
  16700. "\r\n" +
  16701. body;
  16702. std::string response;
  16703. ASSERT_TRUE(send_request(3, req, &response, port));
  16704. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16705. EXPECT_EQ("400", response.substr(9, 3));
  16706. }
  16707. // Posts a multipart body split into two writes, so that the server sees the
  16708. // split at whatever offset the caller chose, and expects the single "text1"
  16709. // field to come through.
  16710. static void expect_split_multipart_ok(const std::string &body1,
  16711. const std::string &body2) {
  16712. auto handled = false;
  16713. Server svr;
  16714. svr.Post("/post", [&](const Request &req, Response &) {
  16715. EXPECT_EQ(1u, req.form.fields.size());
  16716. EXPECT_EQ("text1", req.form.get_field("text1"));
  16717. handled = true;
  16718. });
  16719. auto port = svr.bind_to_any_port(HOST);
  16720. thread t = thread([&] { svr.listen_after_bind(); });
  16721. auto se = detail::scope_exit([&] {
  16722. svr.stop();
  16723. t.join();
  16724. ASSERT_FALSE(svr.is_running());
  16725. ASSERT_TRUE(handled);
  16726. });
  16727. svr.wait_until_ready();
  16728. // "Connection: close" makes the server close once it has answered, so the
  16729. // response drain ends immediately instead of idling until the read timeout.
  16730. const std::string head =
  16731. "POST /post HTTP/1.1\r\n"
  16732. "Host: localhost\r\n"
  16733. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16734. "Connection: close\r\n"
  16735. "Content-Length: " +
  16736. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16737. std::string response;
  16738. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16739. ASSERT_GE(response.size(), 12u) << "no response";
  16740. EXPECT_EQ("200", response.substr(9, 3));
  16741. }
  16742. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16743. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16744. // ignored, including when it does not arrive in the same read as the
  16745. // close-delimiter itself.
  16746. expect_split_multipart_ok("--zzzz\r\n"
  16747. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16748. "\r\n"
  16749. "text1"
  16750. "\r\n--zzzz--",
  16751. "\r\nthis epilogue must be ignored\r\n");
  16752. }
  16753. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16754. // The initial boundary may be preceded by a preamble of any length and may
  16755. // straddle a read boundary. Discarding data while waiting for it must not
  16756. // throw away a partial boundary sitting at the end of the buffer.
  16757. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16758. "zz\r\n"
  16759. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16760. "\r\n"
  16761. "text1"
  16762. "\r\n--zzzz--\r\n");
  16763. }
  16764. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16765. // The received boundary was only checked for being non-empty, so it could be
  16766. // as long as a header is allowed to be. The parser scans the body for
  16767. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16768. // costs a nearly full comparison at nearly every position, making the
  16769. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16770. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16771. Server svr;
  16772. svr.Post("/post", [](const Request &req, Response &res) {
  16773. EXPECT_EQ(1u, req.form.fields.size());
  16774. EXPECT_EQ("text1", req.form.get_field("text1"));
  16775. res.set_content("ok", "text/plain");
  16776. });
  16777. auto port = svr.bind_to_any_port(HOST);
  16778. thread t = thread([&] { svr.listen_after_bind(); });
  16779. auto se = detail::scope_exit([&] {
  16780. svr.stop();
  16781. t.join();
  16782. ASSERT_FALSE(svr.is_running());
  16783. });
  16784. svr.wait_until_ready();
  16785. Client cli(HOST, port);
  16786. auto post_with_boundary_of_length = [&](size_t len) {
  16787. const std::string boundary(len, 'a');
  16788. const std::string body =
  16789. "--" + boundary +
  16790. "\r\n"
  16791. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16792. "\r\n"
  16793. "text1"
  16794. "\r\n--" +
  16795. boundary + "--\r\n";
  16796. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16797. };
  16798. auto res = post_with_boundary_of_length(70);
  16799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16800. EXPECT_EQ(StatusCode::OK_200, res->status);
  16801. res = post_with_boundary_of_length(71);
  16802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16803. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16804. }
  16805. TEST(MakeFileBodyTest, Basic) {
  16806. const std::string file_content(4096, 'Z');
  16807. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16808. {
  16809. std::ofstream ofs(tmp_path, std::ios::binary);
  16810. ofs.write(file_content.data(),
  16811. static_cast<std::streamsize>(file_content.size()));
  16812. }
  16813. auto handled = false;
  16814. Server svr;
  16815. svr.Post("/upload", [&](const Request &req, Response &res) {
  16816. EXPECT_EQ(file_content, req.body);
  16817. handled = true;
  16818. res.status = StatusCode::OK_200;
  16819. });
  16820. auto port = svr.bind_to_any_port(HOST);
  16821. auto t = thread([&] { svr.listen_after_bind(); });
  16822. auto se = detail::scope_exit([&] {
  16823. svr.stop();
  16824. t.join();
  16825. ASSERT_FALSE(svr.is_running());
  16826. ASSERT_TRUE(handled);
  16827. std::remove(tmp_path.c_str());
  16828. });
  16829. svr.wait_until_ready();
  16830. auto fb = make_file_body(tmp_path);
  16831. ASSERT_GT(fb.first, 0u);
  16832. Client cli(HOST, port);
  16833. auto res =
  16834. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16836. EXPECT_EQ(StatusCode::OK_200, res->status);
  16837. }
  16838. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16839. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16840. {
  16841. std::ofstream ofs(path, std::ios::binary);
  16842. const std::string content(100, 'A');
  16843. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16844. }
  16845. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16846. auto body = make_file_body(path);
  16847. ASSERT_EQ(100u, body.first);
  16848. ASSERT_TRUE(static_cast<bool>(body.second));
  16849. // Rewritten shorter after its length was measured - and, on a server, after
  16850. // that length has already gone out as Content-Length.
  16851. {
  16852. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16853. const std::string content(10, 'A');
  16854. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16855. }
  16856. std::string written;
  16857. DataSink sink;
  16858. sink.write = [&](const char *d, size_t l) {
  16859. written.append(d, l);
  16860. return true;
  16861. };
  16862. // The provider has to report failure. write_content_with_progress() advances
  16863. // its offset only by what was written, so a provider that returns true
  16864. // without completing the length it promised is called again straight away,
  16865. // and again.
  16866. EXPECT_FALSE(body.second(0, body.first, sink));
  16867. EXPECT_EQ(std::string(10, 'A'), written);
  16868. }
  16869. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16870. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16871. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16872. {
  16873. std::ofstream ofs(path, std::ios::binary);
  16874. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16875. }
  16876. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16877. auto body = make_file_body(path);
  16878. ASSERT_EQ(content.size(), body.first);
  16879. ASSERT_TRUE(static_cast<bool>(body.second));
  16880. std::string written;
  16881. DataSink sink;
  16882. sink.write = [&](const char *d, size_t l) {
  16883. written.append(d, l);
  16884. return true;
  16885. };
  16886. EXPECT_TRUE(body.second(0, body.first, sink));
  16887. EXPECT_EQ(content, written);
  16888. }
  16889. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16890. static constexpr unsigned int number_of_tasks{1000000};
  16891. std::atomic_uint count{0};
  16892. std::unique_ptr<TaskQueue> task_queue{
  16893. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16894. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16895. auto queued = task_queue->enqueue(
  16896. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16897. EXPECT_TRUE(queued);
  16898. }
  16899. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16900. task_queue->shutdown();
  16901. #else
  16902. EXPECT_NO_THROW(task_queue->shutdown());
  16903. #endif
  16904. EXPECT_EQ(number_of_tasks, count.load());
  16905. }
  16906. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16907. static constexpr unsigned int number_of_tasks{1000000};
  16908. static constexpr unsigned int qlimit{2};
  16909. unsigned int queued_count{0};
  16910. std::atomic_uint count{0};
  16911. std::unique_ptr<TaskQueue> task_queue{
  16912. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16913. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16914. if (task_queue->enqueue(
  16915. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16916. queued_count++;
  16917. }
  16918. }
  16919. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16920. task_queue->shutdown();
  16921. #else
  16922. EXPECT_NO_THROW(task_queue->shutdown());
  16923. #endif
  16924. EXPECT_EQ(queued_count, count.load());
  16925. EXPECT_TRUE(queued_count <= number_of_tasks);
  16926. EXPECT_TRUE(queued_count >= qlimit);
  16927. }
  16928. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16929. // Use a short idle timeout so a dynamic thread spawns, times out and
  16930. // exits during the test, and the pool keeps working afterwards.
  16931. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16932. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16933. /*idle_timeout_sec=*/1}};
  16934. std::atomic_uint count{0};
  16935. std::condition_variable cv;
  16936. std::mutex mtx;
  16937. bool release = false;
  16938. // Block the base thread so the second task spawns a dynamic thread.
  16939. EXPECT_TRUE(task_queue->enqueue([&] {
  16940. std::unique_lock<std::mutex> lock(mtx);
  16941. while (!release) {
  16942. cv.wait(lock);
  16943. }
  16944. count++;
  16945. }));
  16946. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16947. // Let the dynamic thread finish its task and exceed the idle timeout.
  16948. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16949. {
  16950. std::unique_lock<std::mutex> lock(mtx);
  16951. release = true;
  16952. }
  16953. cv.notify_all();
  16954. // The pool must still accept and run tasks after the dynamic thread exited.
  16955. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16956. task_queue->shutdown();
  16957. EXPECT_EQ(3u, count.load());
  16958. }
  16959. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16960. static constexpr size_t number_of_tasks{32};
  16961. std::unique_ptr<TaskQueue> task_queue{
  16962. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16963. // Let the base threads go idle so the burst below finds them waiting.
  16964. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16965. std::mutex mtx;
  16966. std::condition_variable cv;
  16967. size_t running = 0;
  16968. bool release = false;
  16969. for (size_t i = 0; i < number_of_tasks; i++) {
  16970. EXPECT_TRUE(task_queue->enqueue([&] {
  16971. std::unique_lock<std::mutex> lock(mtx);
  16972. running++;
  16973. cv.notify_all();
  16974. cv.wait(lock, [&] { return release; });
  16975. }));
  16976. }
  16977. {
  16978. std::unique_lock<std::mutex> lock(mtx);
  16979. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16980. [&] { return running == number_of_tasks; }));
  16981. release = true;
  16982. }
  16983. cv.notify_all();
  16984. task_queue->shutdown();
  16985. }
  16986. TEST(TaskQueueTest, MaxQueuedRequests) {
  16987. static constexpr unsigned int qlimit{3};
  16988. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16989. std::condition_variable sem_cv;
  16990. std::mutex sem_mtx;
  16991. int credits = 0;
  16992. bool queued;
  16993. /* Fill up the queue with tasks that will block until we give them credits to
  16994. * complete. */
  16995. for (unsigned int n = 0; n <= qlimit;) {
  16996. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16997. std::unique_lock<std::mutex> lock(sem_mtx);
  16998. while (credits <= 0) {
  16999. sem_cv.wait(lock);
  17000. }
  17001. /* Consume the credit and signal the test code if they are all gone. */
  17002. if (--credits == 0) { sem_cv.notify_one(); }
  17003. });
  17004. if (n < qlimit) {
  17005. /* The first qlimit enqueues must succeed. */
  17006. EXPECT_TRUE(queued);
  17007. } else {
  17008. /* The last one will succeed only when the worker thread
  17009. * starts and dequeues the first blocking task. Although
  17010. * not necessary for the correctness of this test, we sleep for
  17011. * a short while to avoid busy waiting. */
  17012. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17013. }
  17014. if (queued) { n++; }
  17015. }
  17016. /* Further enqueues must fail since the queue is full. */
  17017. for (auto i = 0; i < 4; i++) {
  17018. queued = task_queue->enqueue([] {});
  17019. EXPECT_FALSE(queued);
  17020. }
  17021. /* Give the credits to allow the previous tasks to complete. */
  17022. {
  17023. std::unique_lock<std::mutex> lock(sem_mtx);
  17024. credits += qlimit + 1;
  17025. }
  17026. sem_cv.notify_all();
  17027. /* Wait for all the credits to be consumed. */
  17028. {
  17029. std::unique_lock<std::mutex> lock(sem_mtx);
  17030. while (credits > 0) {
  17031. sem_cv.wait(lock);
  17032. }
  17033. }
  17034. /* Check that we are able again to enqueue at least qlimit tasks. */
  17035. for (unsigned int i = 0; i < qlimit; i++) {
  17036. queued = task_queue->enqueue([] {});
  17037. EXPECT_TRUE(queued);
  17038. }
  17039. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17040. task_queue->shutdown();
  17041. #else
  17042. EXPECT_NO_THROW(task_queue->shutdown());
  17043. #endif
  17044. }
  17045. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17046. Server svr;
  17047. std::string method;
  17048. std::string body;
  17049. auto has_content_length = false;
  17050. auto has_transfer_encoding = false;
  17051. std::atomic<int> bad_requests{0};
  17052. // Leftover body bytes get parsed as a malformed request and answered with
  17053. // 400
  17054. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17055. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17056. });
  17057. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17058. res.set_redirect("/down", StatusCode::SeeOther_303);
  17059. });
  17060. svr.Get("/down", [&](const Request &req, Response &res) {
  17061. method = req.method;
  17062. body = req.body;
  17063. has_content_length = req.has_header("Content-Length");
  17064. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17065. res.set_content("ok", "text/plain");
  17066. });
  17067. auto port = svr.bind_to_any_port(HOST);
  17068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17069. auto se = detail::scope_exit([&] {
  17070. svr.stop();
  17071. thread.join();
  17072. ASSERT_FALSE(svr.is_running());
  17073. });
  17074. svr.wait_until_ready();
  17075. const std::string payload = "SECRET-BODY";
  17076. auto check = [&](Client &cli, const Result &res) {
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(StatusCode::OK_200, res->status);
  17079. EXPECT_EQ("ok", res->body);
  17080. EXPECT_EQ("GET", method);
  17081. EXPECT_TRUE(body.empty());
  17082. EXPECT_FALSE(has_content_length);
  17083. EXPECT_FALSE(has_transfer_encoding);
  17084. // Nothing of the original body may be left on the connection
  17085. auto res2 = cli.Get("/down");
  17086. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17087. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17088. EXPECT_EQ("ok", res2->body);
  17089. EXPECT_EQ(0, bad_requests);
  17090. };
  17091. // With content length
  17092. {
  17093. Client cli(HOST, port);
  17094. cli.set_keep_alive(true);
  17095. cli.set_follow_location(true);
  17096. auto res = cli.Post(
  17097. "/up", payload.size(),
  17098. [&](size_t offset, size_t length, DataSink &sink) {
  17099. return sink.write(payload.data() + offset, length);
  17100. },
  17101. "text/plain");
  17102. check(cli, res);
  17103. }
  17104. // Without content length (chunked)
  17105. {
  17106. Client cli(HOST, port);
  17107. cli.set_keep_alive(true);
  17108. cli.set_follow_location(true);
  17109. auto res = cli.Post(
  17110. "/up",
  17111. [&](size_t /*offset*/, DataSink &sink) {
  17112. sink.write(payload.data(), payload.size());
  17113. sink.done();
  17114. return true;
  17115. },
  17116. "text/plain");
  17117. check(cli, res);
  17118. }
  17119. }
  17120. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17121. Server svr;
  17122. std::string target;
  17123. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17124. // Echo the still-encoded name back in the Location
  17125. const std::string prefix = "/start/";
  17126. res.status = StatusCode::Found_302;
  17127. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17128. });
  17129. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17130. target = req.target;
  17131. res.set_content("ok", "text/plain");
  17132. });
  17133. auto port = svr.bind_to_any_port(HOST);
  17134. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17135. auto se = detail::scope_exit([&] {
  17136. svr.stop();
  17137. thread.join();
  17138. ASSERT_FALSE(svr.is_running());
  17139. });
  17140. svr.wait_until_ready();
  17141. // Decoding the Location path would turn the first four into a path
  17142. // separator, a query delimiter, a fragment delimiter and a different
  17143. // percent-encoded octet. The rest must keep reaching the server as they are.
  17144. const std::vector<std::string> names = {
  17145. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17146. };
  17147. for (auto path_encode : {true, false}) {
  17148. Client cli(HOST, port);
  17149. cli.set_follow_location(true);
  17150. cli.set_path_encode(path_encode);
  17151. for (const auto &name : names) {
  17152. target.clear();
  17153. auto res = cli.Get("/start/" + name);
  17154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17155. EXPECT_EQ(StatusCode::OK_200, res->status);
  17156. EXPECT_EQ("/dest/" + name, target);
  17157. }
  17158. }
  17159. }
  17160. TEST(RedirectTest, NotModifiedIsReturned) {
  17161. Server svr;
  17162. svr.Get("/cached", [](const Request &, Response &res) {
  17163. res.status = StatusCode::NotModified_304;
  17164. });
  17165. auto port = svr.bind_to_any_port(HOST);
  17166. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17167. auto se = detail::scope_exit([&] {
  17168. svr.stop();
  17169. thread.join();
  17170. ASSERT_FALSE(svr.is_running());
  17171. });
  17172. svr.wait_until_ready();
  17173. Client cli(HOST, port);
  17174. cli.set_follow_location(true);
  17175. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17177. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17178. }
  17179. TEST(RedirectTest, NoLocationIsReturned) {
  17180. Server svr;
  17181. svr.Get("/no-location", [](const Request &, Response &res) {
  17182. res.status = StatusCode::Found_302;
  17183. res.set_content("no location", "text/plain");
  17184. });
  17185. auto port = svr.bind_to_any_port(HOST);
  17186. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17187. auto se = detail::scope_exit([&] {
  17188. svr.stop();
  17189. thread.join();
  17190. ASSERT_FALSE(svr.is_running());
  17191. });
  17192. svr.wait_until_ready();
  17193. Client cli(HOST, port);
  17194. cli.set_follow_location(true);
  17195. auto res = cli.Get("/no-location");
  17196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17197. EXPECT_EQ(StatusCode::Found_302, res->status);
  17198. EXPECT_EQ("no location", res->body);
  17199. // The callbacks see the body of the response that is returned
  17200. auto handler_called = false;
  17201. auto progress_called = false;
  17202. std::string body;
  17203. auto res2 = cli.Get(
  17204. "/no-location",
  17205. [&](const Response &) {
  17206. handler_called = true;
  17207. return true;
  17208. },
  17209. [&](const char *data, size_t data_length) {
  17210. body.append(data, data_length);
  17211. return true;
  17212. },
  17213. [&](size_t, size_t) {
  17214. progress_called = true;
  17215. return true;
  17216. });
  17217. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17218. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17219. EXPECT_TRUE(handler_called);
  17220. EXPECT_TRUE(progress_called);
  17221. EXPECT_EQ("no location", body);
  17222. }
  17223. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17224. Server svr;
  17225. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17226. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17227. });
  17228. svr.Get("/hello", [](const Request &req, Response &res) {
  17229. res.set_content(req.get_param_value("key"), "text/plain");
  17230. });
  17231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17232. auto se = detail::scope_exit([&] {
  17233. svr.stop();
  17234. thread.join();
  17235. ASSERT_FALSE(svr.is_running());
  17236. });
  17237. svr.wait_until_ready();
  17238. {
  17239. Client cli(HOST, PORT);
  17240. cli.set_follow_location(true);
  17241. auto res = cli.Get("/");
  17242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17243. EXPECT_EQ(StatusCode::OK_200, res->status);
  17244. EXPECT_EQ("val&key2=val2", res->body);
  17245. }
  17246. }
  17247. #endif
  17248. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17249. Server svr;
  17250. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17251. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17252. });
  17253. svr.Get("/hello", [](const Request &req, Response &res) {
  17254. res.set_content(req.get_param_value("key"), "text/plain");
  17255. });
  17256. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17257. auto se = detail::scope_exit([&] {
  17258. svr.stop();
  17259. thread.join();
  17260. ASSERT_FALSE(svr.is_running());
  17261. });
  17262. svr.wait_until_ready();
  17263. {
  17264. Client cli(HOST, PORT);
  17265. cli.set_follow_location(true);
  17266. auto res = cli.Get("/");
  17267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17268. EXPECT_EQ(StatusCode::OK_200, res->status);
  17269. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17270. }
  17271. }
  17272. TEST(RedirectTest, RedirectWithPlusInPath) {
  17273. Server svr;
  17274. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17275. res.set_redirect("/a+b");
  17276. });
  17277. // Route pattern uses regex; escape + as \\+
  17278. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17279. res.set_content(req.path, "text/plain");
  17280. });
  17281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17282. auto se = detail::scope_exit([&] {
  17283. svr.stop();
  17284. thread.join();
  17285. ASSERT_FALSE(svr.is_running());
  17286. });
  17287. svr.wait_until_ready();
  17288. {
  17289. Client cli(HOST, PORT);
  17290. cli.set_follow_location(true);
  17291. auto res = cli.Get("/");
  17292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17293. EXPECT_EQ(StatusCode::OK_200, res->status);
  17294. EXPECT_EQ("/a+b", res->body);
  17295. }
  17296. }
  17297. TEST(RedirectTest, ResolveRelativeLocation) {
  17298. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17299. const std::vector<std::pair<std::string, std::string>> cases = {
  17300. {"g", "/b/c/g"},
  17301. {"./g", "/b/c/g"},
  17302. {"g/", "/b/c/g/"},
  17303. {"?y", "/b/c/d;p?y"},
  17304. {"g?y", "/b/c/g?y"},
  17305. {"#s", "/b/c/d;p?q#s"},
  17306. {"g#s", "/b/c/g#s"},
  17307. {"g?y#s", "/b/c/g?y#s"},
  17308. {";x", "/b/c/;x"},
  17309. {"g;x", "/b/c/g;x"},
  17310. {".", "/b/c/"},
  17311. {"./", "/b/c/"},
  17312. {"..", "/b/"},
  17313. {"../", "/b/"},
  17314. {"../g", "/b/g"},
  17315. {"../..", "/"},
  17316. {"../../", "/"},
  17317. {"../../g", "/g"},
  17318. {"../../../g", "/g"},
  17319. {"g.", "/b/c/g."},
  17320. {".g", "/b/c/.g"},
  17321. {"g..", "/b/c/g.."},
  17322. {"..g", "/b/c/..g"},
  17323. {"./../g", "/b/g"},
  17324. {"./g/.", "/b/c/g/"},
  17325. {"g/./h", "/b/c/g/h"},
  17326. {"g/../h", "/b/c/h"},
  17327. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17328. {"g;x=1/../y", "/b/c/y"},
  17329. {"g?y/./x", "/b/c/g?y/./x"},
  17330. {"g#s/../x", "/b/c/g#s/../x"},
  17331. // Not relative-path references, so left for parse_url.
  17332. {"/g", "/g"},
  17333. {"//g", "//g"},
  17334. {"http://g/x", "http://g/x"},
  17335. {"g:h", "g:h"},
  17336. };
  17337. for (const auto &c : cases) {
  17338. EXPECT_EQ(c.second,
  17339. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17340. << c.first;
  17341. }
  17342. }
  17343. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17344. Server svr;
  17345. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17346. res.set_redirect(req.get_param_value("to"));
  17347. });
  17348. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17349. res.set_content(req.target, "text/plain");
  17350. });
  17351. svr.Get("/other", [](const Request &req, Response &res) {
  17352. res.set_content(req.target, "text/plain");
  17353. });
  17354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17355. auto se = detail::scope_exit([&] {
  17356. svr.stop();
  17357. thread.join();
  17358. ASSERT_FALSE(svr.is_running());
  17359. });
  17360. svr.wait_until_ready();
  17361. const std::vector<std::pair<std::string, std::string>> cases = {
  17362. {"next", "/dir/next"},
  17363. {"./next?x=1", "/dir/next?x=1"},
  17364. {"../other", "/other"},
  17365. };
  17366. for (const auto &c : cases) {
  17367. Client cli(HOST, PORT);
  17368. cli.set_follow_location(true);
  17369. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17370. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17371. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17372. EXPECT_EQ(c.second, res->body) << c.first;
  17373. }
  17374. }
  17375. #ifdef CPPHTTPLIB_SSL_ENABLED
  17376. TEST(RedirectTest, Issue2185_Online) {
  17377. SSLClient client("github.com");
  17378. client.set_follow_location(true);
  17379. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17380. "Coollab-Windows.zip");
  17381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17382. EXPECT_EQ(StatusCode::OK_200, res->status);
  17383. EXPECT_EQ(9920427U, res->body.size());
  17384. }
  17385. #endif
  17386. TEST(VulnerabilityTest, CRLFInjection) {
  17387. Server svr;
  17388. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17389. res.set_content("Hello 1", "text/plain");
  17390. });
  17391. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17392. res.set_content("Hello 2", "text/plain");
  17393. });
  17394. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17395. res.set_content("Hello 3", "text/plain");
  17396. });
  17397. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17398. res.set_content("Hello 4", "text/plain");
  17399. });
  17400. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17401. for (const auto &x : req.headers) {
  17402. auto key = x.first;
  17403. EXPECT_STRNE("evil", key.c_str());
  17404. }
  17405. });
  17406. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17407. auto se = detail::scope_exit([&] {
  17408. svr.stop();
  17409. thread.join();
  17410. ASSERT_FALSE(svr.is_running());
  17411. });
  17412. svr.wait_until_ready();
  17413. {
  17414. Client cli(HOST, PORT);
  17415. cli.Post("/test1", "A=B",
  17416. "application/x-www-form-urlencoded\r\nevil: hello1");
  17417. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17418. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17419. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17420. }
  17421. }
  17422. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17423. auto server_thread = std::thread([] {
  17424. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17425. default_socket_options(srv);
  17426. sockaddr_in addr{};
  17427. addr.sin_family = AF_INET;
  17428. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17429. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17430. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17431. ::listen(srv, 1);
  17432. sockaddr_in cli_addr{};
  17433. socklen_t cli_len = sizeof(cli_addr);
  17434. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17435. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17436. std::string buf_all;
  17437. char buf[2048];
  17438. ssize_t n;
  17439. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17440. buf_all.append(buf, static_cast<size_t>(n));
  17441. size_t pos;
  17442. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17443. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17444. auto e = request_block.find("\r\n");
  17445. if (e != std::string::npos) {
  17446. auto request_line = request_block.substr(0, e);
  17447. std::string msg =
  17448. "CRLF injection detected in request line: '" + request_line + "'";
  17449. EXPECT_FALSE(true) << msg;
  17450. }
  17451. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17452. ::send(cli,
  17453. #ifdef _WIN32
  17454. static_cast<const char *>(resp.c_str()),
  17455. static_cast<int>(resp.size()),
  17456. #else
  17457. resp.c_str(), resp.size(),
  17458. #endif
  17459. 0);
  17460. buf_all.erase(0, pos + 4);
  17461. }
  17462. }
  17463. detail::close_socket(cli);
  17464. detail::close_socket(srv);
  17465. });
  17466. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17467. auto cli = Client("127.0.0.1", PORT + 1);
  17468. auto headers = Headers{
  17469. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17470. {"Connection", "keep-alive"}};
  17471. auto res = cli.Get("/hi", headers);
  17472. EXPECT_FALSE(res);
  17473. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17474. server_thread.join();
  17475. }
  17476. // A request rejected before any byte reaches the socket must fail right away
  17477. // instead of waiting for a response the server will never send.
  17478. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17479. // The kernel completes the TCP handshake from the listen backlog, so the
  17480. // client connects, but nothing ever reads, responds or closes.
  17481. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17482. default_socket_options(srv);
  17483. sockaddr_in addr{};
  17484. addr.sin_family = AF_INET;
  17485. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17487. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17488. ASSERT_EQ(0, ::listen(srv, 8));
  17489. auto cli = Client("127.0.0.1", PORT + 1);
  17490. cli.set_read_timeout(10, 0);
  17491. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17492. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17493. std::chrono::steady_clock::now() - start)
  17494. .count();
  17495. };
  17496. {
  17497. Request req;
  17498. req.method = "GE T";
  17499. req.path = "/";
  17500. auto start = std::chrono::steady_clock::now();
  17501. auto res = cli.send(req);
  17502. EXPECT_FALSE(res);
  17503. EXPECT_EQ(Error::Write, res.error());
  17504. EXPECT_LT(elapsed_ms(start), 1000);
  17505. }
  17506. {
  17507. auto start = std::chrono::steady_clock::now();
  17508. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17509. EXPECT_FALSE(res);
  17510. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17511. EXPECT_LT(elapsed_ms(start), 1000);
  17512. }
  17513. EXPECT_FALSE(cli.is_socket_open());
  17514. detail::close_socket(srv);
  17515. }
  17516. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17517. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17518. default_socket_options(srv);
  17519. sockaddr_in addr{};
  17520. addr.sin_family = AF_INET;
  17521. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17522. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17523. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17524. ASSERT_EQ(0, ::listen(srv, 1));
  17525. std::string received;
  17526. auto server_thread = std::thread([&] {
  17527. auto sock = ::accept(srv, nullptr, nullptr);
  17528. if (sock == INVALID_SOCKET) { return; }
  17529. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17530. char buf[2048];
  17531. ssize_t n;
  17532. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17533. received.append(buf, static_cast<size_t>(n));
  17534. }
  17535. detail::close_socket(sock);
  17536. });
  17537. {
  17538. auto cli = Client("127.0.0.1", PORT + 1);
  17539. // "Z" sorts after the default headers, so writing straight to the socket
  17540. // would have sent the request line and those headers before the rejection.
  17541. auto handle =
  17542. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17543. EXPECT_FALSE(handle.is_valid());
  17544. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17545. }
  17546. server_thread.join();
  17547. detail::close_socket(srv);
  17548. EXPECT_TRUE(received.empty()) << received;
  17549. }
  17550. TEST(PathParamsTest, StaticMatch) {
  17551. const auto pattern = "/users/all";
  17552. detail::PathParamsMatcher matcher(pattern);
  17553. Request request;
  17554. request.path = "/users/all";
  17555. ASSERT_TRUE(matcher.match(request));
  17556. std::unordered_map<std::string, std::string> expected_params = {};
  17557. EXPECT_EQ(request.path_params, expected_params);
  17558. }
  17559. TEST(PathParamsTest, StaticMismatch) {
  17560. const auto pattern = "/users/all";
  17561. detail::PathParamsMatcher matcher(pattern);
  17562. Request request;
  17563. request.path = "/users/1";
  17564. ASSERT_FALSE(matcher.match(request));
  17565. }
  17566. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17567. const auto pattern = "/users/:id/subscriptions";
  17568. detail::PathParamsMatcher matcher(pattern);
  17569. Request request;
  17570. request.path = "/users/42/subscriptions";
  17571. ASSERT_TRUE(matcher.match(request));
  17572. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17573. EXPECT_EQ(request.path_params, expected_params);
  17574. }
  17575. TEST(PathParamsTest, SingleParamInTheEnd) {
  17576. const auto pattern = "/users/:id";
  17577. detail::PathParamsMatcher matcher(pattern);
  17578. Request request;
  17579. request.path = "/users/24";
  17580. ASSERT_TRUE(matcher.match(request));
  17581. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17582. EXPECT_EQ(request.path_params, expected_params);
  17583. }
  17584. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17585. const auto pattern = "/users/:id/";
  17586. detail::PathParamsMatcher matcher(pattern);
  17587. Request request;
  17588. request.path = "/users/42/";
  17589. ASSERT_TRUE(matcher.match(request));
  17590. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17591. EXPECT_EQ(request.path_params, expected_params);
  17592. }
  17593. TEST(PathParamsTest, EmptyParam) {
  17594. const auto pattern = "/users/:id/";
  17595. detail::PathParamsMatcher matcher(pattern);
  17596. Request request;
  17597. request.path = "/users//";
  17598. ASSERT_TRUE(matcher.match(request));
  17599. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17600. EXPECT_EQ(request.path_params, expected_params);
  17601. }
  17602. TEST(PathParamsTest, FragmentMismatch) {
  17603. const auto pattern = "/users/:id/";
  17604. detail::PathParamsMatcher matcher(pattern);
  17605. Request request;
  17606. request.path = "/admins/24/";
  17607. ASSERT_FALSE(matcher.match(request));
  17608. }
  17609. TEST(PathParamsTest, ExtraFragments) {
  17610. const auto pattern = "/users/:id";
  17611. detail::PathParamsMatcher matcher(pattern);
  17612. Request request;
  17613. request.path = "/users/42/subscriptions";
  17614. ASSERT_FALSE(matcher.match(request));
  17615. }
  17616. TEST(PathParamsTest, MissingTrailingParam) {
  17617. const auto pattern = "/users/:id";
  17618. detail::PathParamsMatcher matcher(pattern);
  17619. Request request;
  17620. request.path = "/users";
  17621. ASSERT_FALSE(matcher.match(request));
  17622. }
  17623. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17624. const auto pattern = "/users/:id/subscriptions";
  17625. detail::PathParamsMatcher matcher(pattern);
  17626. Request request;
  17627. request.path = "/users/subscriptions";
  17628. ASSERT_FALSE(matcher.match(request));
  17629. }
  17630. TEST(PathParamsTest, MultipleParams) {
  17631. const auto pattern = "/users/:userid/subscriptions/:subid";
  17632. detail::PathParamsMatcher matcher(pattern);
  17633. Request request;
  17634. request.path = "/users/42/subscriptions/2";
  17635. ASSERT_TRUE(matcher.match(request));
  17636. std::unordered_map<std::string, std::string> expected_params = {
  17637. {"userid", "42"}, {"subid", "2"}};
  17638. EXPECT_EQ(request.path_params, expected_params);
  17639. }
  17640. TEST(PathParamsTest, SequenceOfParams) {
  17641. const auto pattern = "/values/:x/:y/:z";
  17642. detail::PathParamsMatcher matcher(pattern);
  17643. Request request;
  17644. request.path = "/values/1/2/3";
  17645. ASSERT_TRUE(matcher.match(request));
  17646. std::unordered_map<std::string, std::string> expected_params = {
  17647. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17648. EXPECT_EQ(request.path_params, expected_params);
  17649. }
  17650. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17651. const auto pattern = "/prefix:suffix";
  17652. detail::PathParamsMatcher matcher(pattern);
  17653. Request request;
  17654. request.path = "/prefix:suffix";
  17655. ASSERT_TRUE(matcher.match(request));
  17656. const std::unordered_map<std::string, std::string> expected_params = {};
  17657. EXPECT_EQ(request.path_params, expected_params);
  17658. }
  17659. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17660. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17661. // calling thread's stack on a long enough path for a quantified pattern;
  17662. // RegexMatcher must refuse to run regex matching on paths beyond
  17663. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17664. detail::RegexMatcher matcher("/files/(.*)");
  17665. Request within_limit;
  17666. within_limit.path = "/files/" + std::string(10, 'A');
  17667. EXPECT_TRUE(matcher.match(within_limit));
  17668. Request over_limit;
  17669. over_limit.path =
  17670. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17671. EXPECT_FALSE(matcher.match(over_limit));
  17672. }
  17673. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17674. Server svr;
  17675. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17676. res.set_content("ok", "text/plain");
  17677. });
  17678. auto port = svr.bind_to_any_port(HOST);
  17679. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17680. auto se = detail::scope_exit([&] {
  17681. svr.stop();
  17682. thread.join();
  17683. ASSERT_FALSE(svr.is_running());
  17684. });
  17685. svr.wait_until_ready();
  17686. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17687. // request URI limit; this used to be able to crash the process.
  17688. std::string path =
  17689. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17690. std::string req = "GET " + path +
  17691. " HTTP/1.1\r\n"
  17692. "Host: " +
  17693. std::string(HOST) + ":" + std::to_string(port) +
  17694. "\r\n"
  17695. "Connection: close\r\n"
  17696. "\r\n";
  17697. std::string response;
  17698. ASSERT_TRUE(send_request(5, req, &response, port));
  17699. EXPECT_NE(std::string::npos, response.find("404"));
  17700. }
  17701. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17702. Server svr;
  17703. auto handler = [](const Request & /*req*/, Response &res) {
  17704. res.set_content("hit", "text/plain");
  17705. };
  17706. // No regex metacharacter, so this one is compared literally
  17707. svr.Get("/literal/route", handler);
  17708. // '.' is a regex metacharacter, so this one must keep regex semantics
  17709. svr.Get("/a.c", handler);
  17710. auto port = svr.bind_to_any_port(HOST);
  17711. std::thread t([&]() { svr.listen_after_bind(); });
  17712. auto se = detail::scope_exit([&] {
  17713. svr.stop();
  17714. t.join();
  17715. ASSERT_FALSE(svr.is_running());
  17716. });
  17717. svr.wait_until_ready();
  17718. Client cli(HOST, port);
  17719. struct {
  17720. const char *path;
  17721. int status;
  17722. } cases[] = {
  17723. {"/literal/route", StatusCode::OK_200},
  17724. {"/literal/routes", StatusCode::NotFound_404},
  17725. {"/literal/rout", StatusCode::NotFound_404},
  17726. {"/abc", StatusCode::OK_200},
  17727. {"/a.c", StatusCode::OK_200},
  17728. };
  17729. for (const auto &x : cases) {
  17730. auto res = cli.Get(x.path);
  17731. ASSERT_TRUE(res) << x.path;
  17732. EXPECT_EQ(x.status, res->status) << x.path;
  17733. }
  17734. }
  17735. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17736. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17737. // from exhausting the stack, so it must only constrain routes that actually
  17738. // run a regular expression. A literal route is matched by comparison and
  17739. // stays usable at any length.
  17740. Server svr;
  17741. const std::string pattern =
  17742. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17743. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17744. res.set_content("hit", "text/plain");
  17745. });
  17746. auto port = svr.bind_to_any_port(HOST);
  17747. std::thread t([&]() { svr.listen_after_bind(); });
  17748. auto se = detail::scope_exit([&] {
  17749. svr.stop();
  17750. t.join();
  17751. ASSERT_FALSE(svr.is_running());
  17752. });
  17753. svr.wait_until_ready();
  17754. Client cli(HOST, port);
  17755. auto res = cli.Get(pattern);
  17756. ASSERT_TRUE(res);
  17757. EXPECT_EQ(StatusCode::OK_200, res->status);
  17758. }
  17759. TEST(ParseUrlTest, VariousPatterns) {
  17760. {
  17761. detail::UrlComponents uc;
  17762. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17763. EXPECT_EQ("http", uc.scheme);
  17764. EXPECT_EQ("example.com", uc.host);
  17765. EXPECT_EQ("8080", uc.port);
  17766. EXPECT_EQ("/path", uc.path);
  17767. EXPECT_EQ("?q=1", uc.query);
  17768. }
  17769. {
  17770. detail::UrlComponents uc;
  17771. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17772. EXPECT_EQ("https", uc.scheme);
  17773. EXPECT_EQ("example.com", uc.host);
  17774. EXPECT_TRUE(uc.port.empty());
  17775. EXPECT_EQ("/path", uc.path);
  17776. }
  17777. {
  17778. detail::UrlComponents uc;
  17779. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17780. EXPECT_EQ("::1", uc.host);
  17781. EXPECT_EQ("8080", uc.port);
  17782. EXPECT_EQ("/path", uc.path);
  17783. }
  17784. {
  17785. detail::UrlComponents uc;
  17786. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17787. }
  17788. {
  17789. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17790. // the path while the connection still targets the bracketed host.
  17791. detail::UrlComponents uc;
  17792. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17793. }
  17794. {
  17795. detail::UrlComponents uc;
  17796. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17797. }
  17798. {
  17799. detail::UrlComponents uc;
  17800. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17801. EXPECT_EQ("::1", uc.host);
  17802. EXPECT_TRUE(uc.port.empty());
  17803. EXPECT_EQ("/path", uc.path);
  17804. }
  17805. {
  17806. detail::UrlComponents uc;
  17807. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17808. EXPECT_TRUE(uc.scheme.empty());
  17809. EXPECT_EQ("example.com", uc.host);
  17810. EXPECT_EQ("/path", uc.path);
  17811. EXPECT_EQ("?q=1", uc.query);
  17812. }
  17813. {
  17814. detail::UrlComponents uc;
  17815. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17816. EXPECT_TRUE(uc.host.empty());
  17817. EXPECT_EQ("/path", uc.path);
  17818. EXPECT_EQ("?q=1", uc.query);
  17819. }
  17820. {
  17821. detail::UrlComponents uc;
  17822. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17823. EXPECT_EQ("example.com", uc.host);
  17824. EXPECT_EQ("8080", uc.port);
  17825. }
  17826. {
  17827. // Unix socket path — must not be parsed as host
  17828. detail::UrlComponents uc;
  17829. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17830. EXPECT_TRUE(uc.host.empty());
  17831. }
  17832. {
  17833. detail::UrlComponents uc;
  17834. ASSERT_TRUE(detail::parse_url("", uc));
  17835. EXPECT_TRUE(uc.host.empty());
  17836. EXPECT_TRUE(uc.path.empty());
  17837. }
  17838. {
  17839. detail::UrlComponents uc;
  17840. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17841. }
  17842. {
  17843. detail::UrlComponents uc;
  17844. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17845. }
  17846. {
  17847. // Accepted by parse_url; callers restrict to http/https
  17848. detail::UrlComponents uc;
  17849. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17850. EXPECT_EQ("ftp", uc.scheme);
  17851. }
  17852. {
  17853. detail::UrlComponents uc;
  17854. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17855. }
  17856. {
  17857. detail::UrlComponents uc;
  17858. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17859. }
  17860. }
  17861. TEST(ParseUrlTest, FragmentHandling) {
  17862. {
  17863. detail::UrlComponents uc;
  17864. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17865. EXPECT_EQ("/path", uc.path);
  17866. EXPECT_TRUE(uc.query.empty());
  17867. }
  17868. {
  17869. detail::UrlComponents uc;
  17870. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17871. EXPECT_TRUE(uc.path.empty());
  17872. EXPECT_TRUE(uc.query.empty());
  17873. }
  17874. }
  17875. TEST(ParseUrlTest, UserinfoHandling) {
  17876. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17877. // parsers would see evil.com as the host.
  17878. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17879. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17880. for (auto url : urls) {
  17881. detail::UrlComponents uc;
  17882. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17883. }
  17884. }
  17885. TEST(ParseUrlTest, IPv6EdgeCases) {
  17886. {
  17887. detail::UrlComponents uc;
  17888. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17889. EXPECT_TRUE(uc.scheme.empty());
  17890. EXPECT_EQ("::1", uc.host);
  17891. EXPECT_EQ("8080", uc.port);
  17892. }
  17893. {
  17894. // Zone ID '%25' is not in [a-fA-F0-9:]
  17895. detail::UrlComponents uc;
  17896. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17897. }
  17898. }
  17899. TEST(ParseUrlTest, SchemeEdgeCases) {
  17900. {
  17901. detail::UrlComponents uc;
  17902. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17903. }
  17904. {
  17905. detail::UrlComponents uc;
  17906. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17907. }
  17908. {
  17909. detail::UrlComponents uc;
  17910. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17911. }
  17912. }
  17913. TEST(ParseUrlTest, PortEdgeCases) {
  17914. {
  17915. detail::UrlComponents uc;
  17916. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17917. EXPECT_TRUE(uc.port.empty());
  17918. EXPECT_EQ("/path", uc.path);
  17919. }
  17920. {
  17921. // parse_url accepts any port string; validation is done by parse_port
  17922. detail::UrlComponents uc;
  17923. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17924. EXPECT_EQ("abc", uc.port);
  17925. }
  17926. }
  17927. TEST(ParseUrlTest, WebSocketPatterns) {
  17928. {
  17929. detail::UrlComponents uc;
  17930. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17931. EXPECT_EQ("ws", uc.scheme);
  17932. EXPECT_EQ("echo.example.com", uc.host);
  17933. EXPECT_EQ("8080", uc.port);
  17934. EXPECT_EQ("/ws", uc.path);
  17935. }
  17936. {
  17937. detail::UrlComponents uc;
  17938. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17939. EXPECT_EQ("wss", uc.scheme);
  17940. EXPECT_EQ("echo.example.com", uc.host);
  17941. EXPECT_TRUE(uc.port.empty());
  17942. EXPECT_EQ("/ws", uc.path);
  17943. }
  17944. }
  17945. TEST(ParseUrlTest, QueryOnly) {
  17946. detail::UrlComponents uc;
  17947. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17948. EXPECT_TRUE(uc.host.empty());
  17949. EXPECT_TRUE(uc.path.empty());
  17950. EXPECT_EQ("?q=1&r=2", uc.query);
  17951. }
  17952. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17953. detail::UrlComponents uc;
  17954. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17955. EXPECT_TRUE(uc.scheme.empty());
  17956. EXPECT_EQ("example.com", uc.host);
  17957. EXPECT_EQ("443", uc.port);
  17958. EXPECT_EQ("/path", uc.path);
  17959. }
  17960. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17961. // If ipv6 regex working, regex match codepath is taken.
  17962. // else port will default to 80 in Client impl
  17963. int clientImplMagicPort = 80;
  17964. int port = 4321;
  17965. // above ports must be different to avoid false negative
  17966. EXPECT_NE(clientImplMagicPort, port);
  17967. std::string ipV6TestURL = "http://[ff06::c3]";
  17968. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17969. CLIENT_PRIVATE_KEY_FILE);
  17970. EXPECT_EQ(cli.port(), port);
  17971. }
  17972. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17973. auto file_path = "./www/dir/index.html";
  17974. auto dir_path = "./www/dir";
  17975. detail::FileStat stat_file(file_path);
  17976. EXPECT_TRUE(stat_file.is_file());
  17977. EXPECT_FALSE(stat_file.is_dir());
  17978. detail::FileStat stat_dir(dir_path);
  17979. EXPECT_FALSE(stat_dir.is_file());
  17980. EXPECT_TRUE(stat_dir.is_dir());
  17981. }
  17982. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17983. // IPv4 with default HTTP port (80)
  17984. EXPECT_EQ("example.com",
  17985. detail::make_host_and_port_string("example.com", 80, false));
  17986. // IPv4 with default HTTPS port (443)
  17987. EXPECT_EQ("example.com",
  17988. detail::make_host_and_port_string("example.com", 443, true));
  17989. // IPv4 with non-default HTTP port
  17990. EXPECT_EQ("example.com:8080",
  17991. detail::make_host_and_port_string("example.com", 8080, false));
  17992. // IPv4 with non-default HTTPS port
  17993. EXPECT_EQ("example.com:8443",
  17994. detail::make_host_and_port_string("example.com", 8443, true));
  17995. // IPv6 with default HTTP port (80)
  17996. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17997. // IPv6 with default HTTPS port (443)
  17998. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17999. // IPv6 with non-default HTTP port
  18000. EXPECT_EQ("[::1]:8080",
  18001. detail::make_host_and_port_string("::1", 8080, false));
  18002. // IPv6 with non-default HTTPS port
  18003. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18004. // IPv6 full address with default port
  18005. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18006. detail::make_host_and_port_string(
  18007. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18008. // IPv6 full address with non-default port
  18009. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18010. detail::make_host_and_port_string(
  18011. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18012. // IPv6 localhost with non-default port
  18013. EXPECT_EQ("[::1]:3000",
  18014. detail::make_host_and_port_string("::1", 3000, false));
  18015. // IPv6 with zone ID (link-local address) with default port
  18016. EXPECT_EQ("[fe80::1%eth0]",
  18017. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18018. // IPv6 with zone ID (link-local address) with non-default port
  18019. EXPECT_EQ("[fe80::1%eth0]:8080",
  18020. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18021. // Edge case: Port 443 with is_ssl=false (should add port)
  18022. EXPECT_EQ("example.com:443",
  18023. detail::make_host_and_port_string("example.com", 443, false));
  18024. // Edge case: Port 80 with is_ssl=true (should add port)
  18025. EXPECT_EQ("example.com:80",
  18026. detail::make_host_and_port_string("example.com", 80, true));
  18027. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18028. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18029. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18030. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18031. // Security fix: Already bracketed IPv6 should not get double brackets
  18032. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18033. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18034. EXPECT_EQ("[::1]:8080",
  18035. detail::make_host_and_port_string("[::1]", 8080, false));
  18036. EXPECT_EQ("[2001:db8::1]:8080",
  18037. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18038. EXPECT_EQ("[fe80::1%eth0]",
  18039. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18040. EXPECT_EQ("[fe80::1%eth0]:8080",
  18041. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18042. // Edge case: Empty host (should return as-is)
  18043. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18044. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18045. // This is a known limitation but shouldn't crash
  18046. EXPECT_EQ("[host:name]",
  18047. detail::make_host_and_port_string("host:name", 80, false));
  18048. // Port number edge cases (no validation, but should not crash)
  18049. EXPECT_EQ("example.com:0",
  18050. detail::make_host_and_port_string("example.com", 0, false));
  18051. EXPECT_EQ("example.com:-1",
  18052. detail::make_host_and_port_string("example.com", -1, false));
  18053. EXPECT_EQ("example.com:65535",
  18054. detail::make_host_and_port_string("example.com", 65535, false));
  18055. EXPECT_EQ("example.com:65536",
  18056. detail::make_host_and_port_string("example.com", 65536, false));
  18057. }
  18058. #ifdef CPPHTTPLIB_SSL_ENABLED
  18059. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18060. httplib::SSLClient cli("roblox.com", 443);
  18061. cli.set_follow_location(true);
  18062. auto res = cli.Get("/");
  18063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18064. EXPECT_EQ(StatusCode::OK_200, res->status);
  18065. }
  18066. #endif
  18067. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18068. Server svr;
  18069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18070. EXPECT_EQ(res.status, 400);
  18071. });
  18072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18073. auto se = detail::scope_exit([&] {
  18074. svr.stop();
  18075. thread.join();
  18076. ASSERT_FALSE(svr.is_running());
  18077. });
  18078. svr.wait_until_ready();
  18079. Client cli(HOST, PORT);
  18080. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18081. }
  18082. TEST(InvalidHeaderCharsTest, is_field_name) {
  18083. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18084. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18085. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18086. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18087. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18088. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18089. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18090. EXPECT_FALSE(detail::fields::is_field_name(""));
  18091. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18092. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18093. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18094. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18095. }
  18096. TEST(InvalidHeaderCharsTest, is_field_value) {
  18097. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18098. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18099. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18100. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18101. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18102. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18103. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18104. EXPECT_TRUE(detail::fields::is_field_value(""));
  18105. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18106. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18107. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18108. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18109. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18110. }
  18111. TEST(InvalidHeaderCharsTest, OnServer) {
  18112. Server svr;
  18113. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18114. std::string header = "Not Set";
  18115. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18116. res.set_header(header, "value");
  18117. res.set_content("Page Content Page Content", "text/plain");
  18118. });
  18119. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18120. std::string header = "Not Set";
  18121. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18122. res.set_header("X-Test", header);
  18123. res.set_content("Page Content Page Content", "text/plain");
  18124. });
  18125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18126. auto se = detail::scope_exit([&] {
  18127. svr.stop();
  18128. thread.join();
  18129. ASSERT_FALSE(svr.is_running());
  18130. });
  18131. svr.wait_until_ready();
  18132. Client cli(HOST, PORT);
  18133. {
  18134. auto res = cli.Get(
  18135. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18137. EXPECT_EQ("Page Content Page Content", res->body);
  18138. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18139. }
  18140. {
  18141. auto res = cli.Get(
  18142. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18144. EXPECT_EQ("Page Content Page Content", res->body);
  18145. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18146. }
  18147. }
  18148. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18149. auto handled = false;
  18150. Server svr;
  18151. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18152. thread t = thread([&] { svr.listen(HOST, PORT); });
  18153. auto se = detail::scope_exit([&] {
  18154. svr.stop();
  18155. t.join();
  18156. ASSERT_FALSE(svr.is_running());
  18157. ASSERT_FALSE(handled);
  18158. });
  18159. svr.wait_until_ready();
  18160. auto req = "POST /test HTTP/1.1\r\n"
  18161. "Content-Length: x\r\n"
  18162. "\r\n";
  18163. std::string response;
  18164. ASSERT_TRUE(send_request(1, req, &response));
  18165. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18166. response.substr(0, response.find("\r\n")));
  18167. }
  18168. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18169. // case-insensitive, and a server that receives a 100-continue expectation in
  18170. // an HTTP/1.0 request MUST ignore it.
  18171. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18172. std::string response;
  18173. ASSERT_TRUE(send_request(1, req, &response, port));
  18174. *got_100 = response.find("100 Continue") != std::string::npos;
  18175. }
  18176. class ExpectTokenTest : public ::testing::Test {
  18177. protected:
  18178. void SetUp() override {
  18179. svr_.Post("/p", [](const Request &, Response &res) {
  18180. res.set_content("ok", "text/plain");
  18181. });
  18182. port_ = svr_.bind_to_any_port(HOST);
  18183. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18184. svr_.wait_until_ready();
  18185. }
  18186. void TearDown() override {
  18187. svr_.stop();
  18188. if (thread_.joinable()) { thread_.join(); }
  18189. }
  18190. std::string request(const char *version, const char *expect_value) const {
  18191. return std::string("POST /p ") + version +
  18192. "\r\n"
  18193. "Host: localhost\r\n"
  18194. "Content-Length: 2\r\n"
  18195. "Connection: close\r\n"
  18196. "Expect: " +
  18197. expect_value +
  18198. "\r\n"
  18199. "\r\n"
  18200. "hi";
  18201. }
  18202. Server svr_;
  18203. int port_ = 0;
  18204. thread thread_;
  18205. };
  18206. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18207. bool got_100 = false;
  18208. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18209. EXPECT_TRUE(got_100);
  18210. }
  18211. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18212. bool got_100 = true;
  18213. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18214. EXPECT_FALSE(got_100);
  18215. }
  18216. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18217. bool got_100 = false;
  18218. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18219. EXPECT_TRUE(got_100);
  18220. }
  18221. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18222. bool got_100 = false;
  18223. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18224. EXPECT_TRUE(got_100);
  18225. }
  18226. // `100 Continue` is sent only when the server starts reading the body, so a
  18227. // request rejected before that never invites the client to send it. The
  18228. // requests below carry the expectation but withhold the body, as a client
  18229. // waiting for `100 Continue` would.
  18230. // A POST that expects `100 Continue` and withholds its two-byte body.
  18231. static std::string expect_headers_only(const std::string &path) {
  18232. return "POST " + path +
  18233. " HTTP/1.1\r\n"
  18234. "Host: localhost\r\n"
  18235. "Content-Length: 2\r\n"
  18236. "Expect: 100-continue\r\n"
  18237. "\r\n";
  18238. }
  18239. class ExpectLazyContinueTest : public ::testing::Test {
  18240. protected:
  18241. void SetUp() override {
  18242. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18243. if (req.path == "/pre-routing") {
  18244. res.status = StatusCode::Unauthorized_401;
  18245. return Server::HandlerResponse::Handled;
  18246. }
  18247. return Server::HandlerResponse::Unhandled;
  18248. });
  18249. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18250. if (req.matched_route == "/pre-request") {
  18251. res.status = StatusCode::Forbidden_403;
  18252. return Server::HandlerResponse::Handled;
  18253. }
  18254. return Server::HandlerResponse::Unhandled;
  18255. });
  18256. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18257. res.set_content("ok", "text/plain");
  18258. });
  18259. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18260. res.set_content("ok", "text/plain");
  18261. });
  18262. svr_.Post("/reader-used", [](const Request &, Response &res,
  18263. const ContentReader &content_reader) {
  18264. std::string body;
  18265. content_reader([&](const char *data, size_t len) {
  18266. body.append(data, len);
  18267. return true;
  18268. });
  18269. res.set_content(body, "text/plain");
  18270. });
  18271. svr_.Post("/reader-unused",
  18272. [](const Request &, Response &res, const ContentReader &) {
  18273. res.set_content("ignored", "text/plain");
  18274. });
  18275. port_ = svr_.bind_to_any_port(HOST);
  18276. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18277. svr_.wait_until_ready();
  18278. }
  18279. void TearDown() override {
  18280. svr_.stop();
  18281. if (thread_.joinable()) { thread_.join(); }
  18282. }
  18283. // Sends `req` and reads until the server closes the connection. Returns
  18284. // false if the read had to wait for the client-side timeout instead.
  18285. bool send_until_closed(const std::string &req, std::string *resp) const {
  18286. auto start = std::chrono::steady_clock::now();
  18287. if (!send_request(3, req, resp, port_)) { return false; }
  18288. auto elapsed = std::chrono::steady_clock::now() - start;
  18289. return elapsed < std::chrono::seconds(2);
  18290. }
  18291. // The final response comes without `100 Continue`, and the server closes
  18292. // the connection since the body may or may not follow.
  18293. void expect_final_without_interim(const std::string &path,
  18294. const char *status_line) const {
  18295. std::string resp;
  18296. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18297. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18298. EXPECT_EQ(0u, resp.find(status_line));
  18299. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18300. }
  18301. Server svr_;
  18302. int port_ = 0;
  18303. thread thread_;
  18304. };
  18305. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18306. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18307. }
  18308. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18309. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18310. }
  18311. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18312. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18313. }
  18314. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18315. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18316. }
  18317. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18318. // The body follows once `100 Continue` has had time to arrive.
  18319. auto req = expect_headers_only("/reader-used");
  18320. req.insert(req.size() - 2, "Connection: close\r\n");
  18321. std::string resp;
  18322. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18323. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18324. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18325. EXPECT_NE(std::string::npos, resp.find("hi"));
  18326. }
  18327. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18328. // Large enough for the client to add `Expect: 100-continue` itself.
  18329. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18330. std::atomic<bool> body_sent{false};
  18331. Client cli(HOST, port_);
  18332. auto res = cli.Post(
  18333. "/pre-request", length,
  18334. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18335. body_sent = true;
  18336. std::string chunk(len, 'x');
  18337. sink.write(chunk.data(), chunk.size());
  18338. return true;
  18339. },
  18340. "application/octet-stream");
  18341. ASSERT_TRUE(res);
  18342. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18343. EXPECT_FALSE(body_sent);
  18344. }
  18345. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18346. Server svr;
  18347. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18348. return StatusCode::ExpectationFailed_417;
  18349. });
  18350. svr.Post("/p", [](const Request &, Response &res) {
  18351. res.set_content("ok", "text/plain");
  18352. });
  18353. auto port = svr.bind_to_any_port(HOST);
  18354. thread t = thread([&] { svr.listen_after_bind(); });
  18355. auto se = detail::scope_exit([&] {
  18356. svr.stop();
  18357. t.join();
  18358. });
  18359. svr.wait_until_ready();
  18360. std::string resp;
  18361. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18362. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18363. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18364. // Exactly one response: the route handler must not run after the 417.
  18365. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18366. }
  18367. #ifndef _WIN32
  18368. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18369. static constexpr char reject[] = "Unauthorized";
  18370. static constexpr char accept[] = "Upload accepted";
  18371. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18372. Server svr;
  18373. svr.set_expect_100_continue_handler(
  18374. [](const Request & /*req*/, Response &res) {
  18375. res.status = StatusCode::Unauthorized_401;
  18376. res.set_content(reject, "text/plain");
  18377. return res.status;
  18378. });
  18379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18380. res.set_content(accept, "text/plain");
  18381. });
  18382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. thread.join();
  18386. ASSERT_FALSE(svr.is_running());
  18387. });
  18388. svr.wait_until_ready();
  18389. {
  18390. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18391. curl_easy_init(), &curl_easy_cleanup};
  18392. ASSERT_NE(curl, nullptr);
  18393. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18394. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18395. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18396. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18397. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18398. &curl_slist_free_all};
  18399. ASSERT_NE(list, nullptr);
  18400. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18401. struct read_data {
  18402. uint64_t read_size;
  18403. uint64_t total_size;
  18404. } data = {0, total_size};
  18405. using read_callback_t =
  18406. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18407. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18408. void *userdata) -> size_t {
  18409. read_data *d = (read_data *)userdata;
  18410. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18411. std::fill_n(ptr, size * nmemb, 'A');
  18412. d->read_size += size * nmemb;
  18413. return size * nmemb;
  18414. };
  18415. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18416. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18417. std::vector<char> buffer;
  18418. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18419. using write_callback_t =
  18420. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18421. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18422. void *userdata) -> size_t {
  18423. std::vector<char> *buf = (std::vector<char> *)userdata;
  18424. buf->reserve(buf->size() + size * nmemb + 1);
  18425. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18426. return size * nmemb;
  18427. };
  18428. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18429. {
  18430. const auto res = curl_easy_perform(curl.get());
  18431. ASSERT_EQ(res, CURLE_OK);
  18432. }
  18433. {
  18434. auto response_code = long{};
  18435. const auto res =
  18436. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18437. ASSERT_EQ(res, CURLE_OK);
  18438. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18439. }
  18440. {
  18441. auto dl = curl_off_t{};
  18442. const auto res =
  18443. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18444. ASSERT_EQ(res, CURLE_OK);
  18445. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18446. }
  18447. {
  18448. buffer.push_back('\0');
  18449. ASSERT_STRCASEEQ(buffer.data(), reject);
  18450. }
  18451. }
  18452. }
  18453. #endif
  18454. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18455. // Regression test for #2458.
  18456. //
  18457. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18458. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18459. // ticket can make the client socket spuriously readable during the
  18460. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18461. // the client withholds the body and then blocks reading a response that never
  18462. // comes, failing with `Failed to read connection`.
  18463. //
  18464. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18465. // within the timeout. This raw OpenSSL server deliberately never sends
  18466. // `100 Continue`; the client must still deliver the body and receive 200.
  18467. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18468. signal(SIGPIPE, SIG_IGN);
  18469. const auto port = PORT + 4;
  18470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18471. ASSERT_NE(srv, INVALID_SOCKET);
  18472. int opt = 1;
  18473. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18474. sockaddr_in addr{};
  18475. addr.sin_family = AF_INET;
  18476. addr.sin_port = htons(static_cast<uint16_t>(port));
  18477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18478. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18479. ASSERT_EQ(0, ::listen(srv, 1));
  18480. std::atomic<size_t> server_body_bytes{0};
  18481. auto server_thread = std::thread([&] {
  18482. sockaddr_in cli_addr{};
  18483. socklen_t cli_len = sizeof(cli_addr);
  18484. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18485. if (cli == INVALID_SOCKET) { return; }
  18486. // Bound the lifetime of the server side so a buggy client (which never
  18487. // sends the body) cannot make this thread block forever on join.
  18488. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18489. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18490. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18491. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18492. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18493. SSL *ssl = SSL_new(ctx);
  18494. SSL_set_fd(ssl, static_cast<int>(cli));
  18495. if (SSL_accept(ssl) > 0) {
  18496. // Read the request headers. Reading here also flushes the TLS 1.3
  18497. // session tickets to the client. Deliberately do NOT send
  18498. // `100 Continue`.
  18499. std::string buf;
  18500. char tmp[1024];
  18501. while (buf.find("\r\n\r\n") == std::string::npos) {
  18502. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18503. if (n <= 0) { break; }
  18504. buf.append(tmp, static_cast<size_t>(n));
  18505. }
  18506. // A correct client sends the body now; count what arrives.
  18507. auto pos = buf.find("\r\n\r\n");
  18508. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18509. while (body < 4096) {
  18510. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18511. if (n <= 0) { break; }
  18512. body += static_cast<size_t>(n);
  18513. }
  18514. server_body_bytes = body;
  18515. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18516. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18517. SSL_shutdown(ssl);
  18518. }
  18519. SSL_free(ssl);
  18520. detail::close_socket(cli);
  18521. SSL_CTX_free(ctx);
  18522. });
  18523. auto se = detail::scope_exit([&] {
  18524. server_thread.join();
  18525. detail::close_socket(srv);
  18526. });
  18527. SSLClient cli("127.0.0.1", port);
  18528. cli.enable_server_certificate_verification(false);
  18529. cli.set_connection_timeout(5, 0);
  18530. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18531. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18532. std::string body(4096, 'A');
  18533. auto res = cli.Put("/api/test", body, "application/json");
  18534. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18535. EXPECT_EQ(StatusCode::OK_200, res->status);
  18536. EXPECT_EQ(body.size(), server_body_bytes.load());
  18537. }
  18538. #endif
  18539. template <typename S, typename C>
  18540. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18541. svr.Get("/stream", [&](const Request &, Response &res) {
  18542. auto data = new std::string("01234567890123456789");
  18543. res.set_content_provider(
  18544. data->size(), "text/plain",
  18545. [&, data](size_t offset, size_t length, DataSink &sink) {
  18546. const size_t DATA_CHUNK_SIZE = 4;
  18547. const auto &d = *data;
  18548. std::this_thread::sleep_for(std::chrono::seconds(1));
  18549. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18550. return true;
  18551. },
  18552. [data](bool success) {
  18553. EXPECT_FALSE(success);
  18554. delete data;
  18555. });
  18556. });
  18557. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18558. auto i = new size_t(0);
  18559. res.set_content_provider(
  18560. "text/plain",
  18561. [i](size_t, DataSink &sink) {
  18562. if (*i < 5) {
  18563. std::this_thread::sleep_for(std::chrono::seconds(1));
  18564. sink.write("abcd", 4);
  18565. (*i)++;
  18566. } else {
  18567. sink.done();
  18568. }
  18569. return true;
  18570. },
  18571. [i](bool success) {
  18572. EXPECT_FALSE(success);
  18573. delete i;
  18574. });
  18575. });
  18576. svr.Get("/chunked", [&](const Request &, Response &res) {
  18577. auto i = new size_t(0);
  18578. res.set_chunked_content_provider(
  18579. "text/plain",
  18580. [i](size_t, DataSink &sink) {
  18581. if (*i < 5) {
  18582. std::this_thread::sleep_for(std::chrono::seconds(1));
  18583. sink.os << "abcd";
  18584. (*i)++;
  18585. } else {
  18586. sink.done();
  18587. }
  18588. return true;
  18589. },
  18590. [i](bool success) {
  18591. EXPECT_FALSE(success);
  18592. delete i;
  18593. });
  18594. });
  18595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18596. auto se = detail::scope_exit([&] {
  18597. svr.stop();
  18598. listen_thread.join();
  18599. ASSERT_FALSE(svr.is_running());
  18600. });
  18601. svr.wait_until_ready();
  18602. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18603. {
  18604. auto start = std::chrono::steady_clock::now();
  18605. auto res = cli.Get("/stream");
  18606. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18607. std::chrono::steady_clock::now() - start)
  18608. .count();
  18609. ASSERT_FALSE(res);
  18610. EXPECT_EQ(Error::Read, res.error());
  18611. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18612. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18613. }
  18614. {
  18615. auto start = std::chrono::steady_clock::now();
  18616. auto res = cli.Get("/stream_without_length");
  18617. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18618. std::chrono::steady_clock::now() - start)
  18619. .count();
  18620. ASSERT_FALSE(res);
  18621. EXPECT_EQ(Error::Read, res.error());
  18622. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18623. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18624. }
  18625. {
  18626. auto start = std::chrono::steady_clock::now();
  18627. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18628. EXPECT_EQ("abcd", string(data, data_length));
  18629. return true;
  18630. });
  18631. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18632. std::chrono::steady_clock::now() - start)
  18633. .count();
  18634. ASSERT_FALSE(res);
  18635. EXPECT_EQ(Error::Read, res.error());
  18636. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18637. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18638. }
  18639. }
  18640. TEST(MaxTimeoutTest, ContentStream) {
  18641. time_t timeout = 2000;
  18642. time_t threshold = 200;
  18643. Server svr;
  18644. Client cli("localhost", PORT);
  18645. max_timeout_test(svr, cli, timeout, threshold);
  18646. }
  18647. #ifdef CPPHTTPLIB_SSL_ENABLED
  18648. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18649. time_t timeout = 2000;
  18650. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18652. SSLClient cli("localhost", PORT);
  18653. cli.enable_server_certificate_verification(false);
  18654. max_timeout_test(svr, cli, timeout, threshold);
  18655. }
  18656. #endif
  18657. class EventDispatcher {
  18658. public:
  18659. EventDispatcher() {}
  18660. bool wait_event(DataSink *sink) {
  18661. unique_lock<mutex> lk(m_);
  18662. int id = id_;
  18663. // Wait with timeout to prevent hanging if client disconnects
  18664. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18665. [&] { return cid_ == id; })) {
  18666. return false; // Timeout occurred
  18667. }
  18668. sink->write(message_.data(), message_.size());
  18669. return true;
  18670. }
  18671. void send_event(const string &message) {
  18672. lock_guard<mutex> lk(m_);
  18673. cid_ = id_++;
  18674. message_ = message;
  18675. cv_.notify_all();
  18676. }
  18677. private:
  18678. mutex m_;
  18679. condition_variable cv_;
  18680. atomic_int id_{0};
  18681. atomic_int cid_{-1};
  18682. string message_;
  18683. };
  18684. TEST(ClientInThreadTest, Issue2068) {
  18685. EventDispatcher ed;
  18686. Server svr;
  18687. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18688. res.set_chunked_content_provider("text/event-stream",
  18689. [&](size_t /*offset*/, DataSink &sink) {
  18690. return ed.wait_event(&sink);
  18691. });
  18692. });
  18693. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18694. svr.wait_until_ready();
  18695. thread event_thread([&] {
  18696. int id = 0;
  18697. while (svr.is_running()) {
  18698. this_thread::sleep_for(chrono::milliseconds(500));
  18699. std::stringstream ss;
  18700. ss << "data: " << id << "\n\n";
  18701. ed.send_event(ss.str());
  18702. id++;
  18703. }
  18704. });
  18705. auto se = detail::scope_exit([&] {
  18706. svr.stop();
  18707. listen_thread.join();
  18708. event_thread.join();
  18709. ASSERT_FALSE(svr.is_running());
  18710. });
  18711. {
  18712. auto client = detail::make_unique<Client>(HOST, PORT);
  18713. client->set_read_timeout(std::chrono::minutes(10));
  18714. std::atomic<bool> stop{false};
  18715. std::thread t([&] {
  18716. client->Get("/event1",
  18717. [&](const char *, size_t) -> bool { return !stop; });
  18718. });
  18719. std::this_thread::sleep_for(std::chrono::seconds(2));
  18720. stop = true;
  18721. client->stop();
  18722. t.join();
  18723. // Reset client after thread has finished
  18724. client.reset();
  18725. }
  18726. }
  18727. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18728. auto handled = false;
  18729. Server svr;
  18730. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18731. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18732. auto se = detail::scope_exit([&] {
  18733. svr.stop();
  18734. t.join();
  18735. ASSERT_FALSE(svr.is_running());
  18736. ASSERT_FALSE(handled);
  18737. });
  18738. svr.wait_until_ready();
  18739. // Two Content-Length headers with different values — must be rejected
  18740. auto req = "POST /test HTTP/1.1\r\n"
  18741. "Content-Length: 5\r\n"
  18742. "Content-Length: 10\r\n"
  18743. "\r\n"
  18744. "hello";
  18745. std::string response;
  18746. ASSERT_TRUE(send_request(1, req, &response));
  18747. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18748. response.substr(0, response.find("\r\n")));
  18749. }
  18750. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18751. auto handled = false;
  18752. Server svr;
  18753. svr.Post("/test", [&](const Request &, Response &res) {
  18754. handled = true;
  18755. res.set_content("ok", "text/plain");
  18756. });
  18757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18758. auto se = detail::scope_exit([&] {
  18759. svr.stop();
  18760. t.join();
  18761. ASSERT_FALSE(svr.is_running());
  18762. ASSERT_TRUE(handled);
  18763. });
  18764. svr.wait_until_ready();
  18765. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18766. auto req = "POST /test HTTP/1.1\r\n"
  18767. "Host: localhost\r\n"
  18768. "Content-Length: 5\r\n"
  18769. "Content-Length: 5\r\n"
  18770. "\r\n"
  18771. "hello";
  18772. std::string response;
  18773. ASSERT_TRUE(send_request(1, req, &response));
  18774. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18775. }
  18776. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18777. Server svr;
  18778. svr.Get("/test", [](const Request &, Response &res) {
  18779. res.set_content("ok", "text/plain");
  18780. });
  18781. auto port = svr.bind_to_any_port(HOST);
  18782. thread t = thread([&] { svr.listen_after_bind(); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. auto status_line = [&](const std::string &host_lines) {
  18790. std::string res;
  18791. send_request(
  18792. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18793. &res, port);
  18794. return res.substr(0, res.find("\r\n"));
  18795. };
  18796. const char *accepted[] = {
  18797. "Host: localhost\r\n",
  18798. "Host: a.example:8080\r\n",
  18799. "Host: my_service\r\n",
  18800. "Host: [::1]:8080\r\n",
  18801. "Host: [fe80::1%25eth0]\r\n",
  18802. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18803. };
  18804. for (auto host_lines : accepted) {
  18805. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18806. }
  18807. const char *rejected[] = {
  18808. "Host: a.example\r\nHost: b.example\r\n",
  18809. "Host: a.example\r\nHost: a.example\r\n",
  18810. "Host: a@b.example\r\n",
  18811. "Host: a.example/b\r\n",
  18812. "Host: a.example\\b\r\n",
  18813. "Host: a.example?b\r\n",
  18814. "Host: a.example#b\r\n",
  18815. "Host: a.example b.example\r\n",
  18816. };
  18817. for (auto host_lines : rejected) {
  18818. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18819. << host_lines;
  18820. }
  18821. }
  18822. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18823. Server svr;
  18824. svr.Get("/", [](const Request &req, Response &res) {
  18825. EXPECT_EQ(2U, req.trailers.size());
  18826. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18827. // Denied
  18828. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18829. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18830. // Accepted
  18831. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18832. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18833. EXPECT_TRUE(req.has_trailer("X-World"));
  18834. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18835. res.set_content("ok", "text/plain");
  18836. });
  18837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18838. auto se = detail::scope_exit([&] {
  18839. svr.stop();
  18840. t.join();
  18841. ASSERT_FALSE(svr.is_running());
  18842. });
  18843. svr.wait_until_ready();
  18844. const std::string req = "GET / HTTP/1.1\r\n"
  18845. "Transfer-Encoding: chunked\r\n"
  18846. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18847. "\r\n"
  18848. "0\r\n"
  18849. "Content-Length: 10\r\n"
  18850. "Host: internal.local\r\n"
  18851. "Content-Type: malicious/content\r\n"
  18852. "Cookie: any\r\n"
  18853. "Set-Cookie: any\r\n"
  18854. "X-Forwarded-For: attacker.com\r\n"
  18855. "X-Real-Ip: 1.1.1.1\r\n"
  18856. "X-Hello: hello\r\n"
  18857. "X-World: world\r\n"
  18858. "\r\n";
  18859. std::string res;
  18860. ASSERT_TRUE(send_request(1, req, &res));
  18861. }
  18862. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18863. // several field lines, and the combined value is what has to be parsed. A
  18864. // Trailer field split across lines therefore declares every name it lists;
  18865. // reading only the first line silently drops the trailers the later lines
  18866. // declare. The prohibited-trailer filter still applies to every line.
  18867. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18868. Server svr;
  18869. size_t observed_trailer_count = 0;
  18870. std::string observed_hello;
  18871. std::string observed_world;
  18872. bool observed_content_length = true;
  18873. svr.Get("/", [&](const Request &req, Response &res) {
  18874. observed_trailer_count = req.trailers.size();
  18875. observed_hello = req.get_trailer_value("X-Hello");
  18876. observed_world = req.get_trailer_value("X-World");
  18877. observed_content_length = req.has_trailer("Content-Length");
  18878. res.set_content("ok", "text/plain");
  18879. });
  18880. auto port = svr.bind_to_any_port(HOST);
  18881. thread t = thread([&]() { svr.listen_after_bind(); });
  18882. auto se = detail::scope_exit([&] {
  18883. svr.stop();
  18884. t.join();
  18885. ASSERT_FALSE(svr.is_running());
  18886. });
  18887. svr.wait_until_ready();
  18888. const std::string req = "GET / HTTP/1.1\r\n"
  18889. "Host: localhost\r\n"
  18890. "Transfer-Encoding: chunked\r\n"
  18891. "Trailer: X-Hello\r\n"
  18892. "Trailer: X-World, Content-Length\r\n"
  18893. "\r\n"
  18894. "0\r\n"
  18895. "X-Hello: hello\r\n"
  18896. "X-World: world\r\n"
  18897. "Content-Length: 10\r\n"
  18898. "\r\n";
  18899. std::string res;
  18900. ASSERT_TRUE(send_request(1, req, &res, port));
  18901. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18902. // Accepted: both field lines contribute to the declared set
  18903. EXPECT_EQ(2U, observed_trailer_count);
  18904. EXPECT_EQ(observed_hello, "hello");
  18905. EXPECT_EQ(observed_world, "world");
  18906. // Denied: a prohibited name stays prohibited on a later field line
  18907. EXPECT_FALSE(observed_content_length);
  18908. }
  18909. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18910. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18911. // unbounded run of fields that are never declared, because the counter would
  18912. // only advance for declared fields.
  18913. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18914. Server svr;
  18915. bool handler_called = false;
  18916. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18917. handler_called = true;
  18918. res.set_content("ok", "text/plain");
  18919. });
  18920. auto port = svr.bind_to_any_port(HOST);
  18921. thread t = thread([&]() { svr.listen_after_bind(); });
  18922. auto se = detail::scope_exit([&] {
  18923. svr.stop();
  18924. t.join();
  18925. ASSERT_FALSE(svr.is_running());
  18926. });
  18927. svr.wait_until_ready();
  18928. // Declare nothing, then send far more undeclared trailer fields than the
  18929. // header-count limit. Parsing must stop and reject the request rather than
  18930. // read every line.
  18931. std::string req = "GET / HTTP/1.1\r\n"
  18932. "Transfer-Encoding: chunked\r\n"
  18933. "\r\n"
  18934. "0\r\n";
  18935. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18936. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18937. }
  18938. req += "\r\n";
  18939. std::string res;
  18940. ASSERT_TRUE(send_request(1, req, &res, port));
  18941. // The request is rejected before the handler runs.
  18942. EXPECT_FALSE(handler_called);
  18943. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18944. }
  18945. // The set of declared trailer names is capped so a peer cannot grow it without
  18946. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18947. // declared past the cap is not honored, even if the field is actually sent.
  18948. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18949. Server svr;
  18950. // One name inside the cap and one past it, so the test tracks the cap rather
  18951. // than a fixed count.
  18952. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18953. const std::string within_cap_name = "X-T-0";
  18954. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18955. bool observed_within_cap = false;
  18956. bool observed_past_cap = false;
  18957. svr.Get("/", [&](const Request &req, Response &res) {
  18958. observed_within_cap = req.has_trailer(within_cap_name);
  18959. observed_past_cap = req.has_trailer(past_cap_name);
  18960. res.set_content("ok", "text/plain");
  18961. });
  18962. auto port = svr.bind_to_any_port(HOST);
  18963. thread t = thread([&]() { svr.listen_after_bind(); });
  18964. auto se = detail::scope_exit([&] {
  18965. svr.stop();
  18966. t.join();
  18967. ASSERT_FALSE(svr.is_running());
  18968. });
  18969. svr.wait_until_ready();
  18970. // Declare more trailer names than the cap in a single Trailer field, then
  18971. // actually send the first (within the cap) and the last (past it).
  18972. std::string trailer_decl = "Trailer: ";
  18973. for (int i = 0; i < declared_count; i++) {
  18974. if (i != 0) { trailer_decl += ", "; }
  18975. trailer_decl += "X-T-" + std::to_string(i);
  18976. }
  18977. trailer_decl += "\r\n";
  18978. const std::string req = "GET / HTTP/1.1\r\n"
  18979. "Host: localhost\r\n"
  18980. "Transfer-Encoding: chunked\r\n" +
  18981. trailer_decl +
  18982. "\r\n"
  18983. "0\r\n" +
  18984. within_cap_name + ": a\r\n" + past_cap_name +
  18985. ": b\r\n"
  18986. "\r\n";
  18987. std::string res;
  18988. ASSERT_TRUE(send_request(1, req, &res, port));
  18989. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18990. // A name within the cap is honored; one declared past the cap is dropped.
  18991. EXPECT_TRUE(observed_within_cap);
  18992. EXPECT_FALSE(observed_past_cap);
  18993. }
  18994. // A direct client that is not listed in trusted_proxies must not be able to
  18995. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18996. // the peer address on the actual TCP connection determines whether the
  18997. // header is honored.
  18998. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18999. Server svr;
  19000. // Deliberately does NOT include the loopback address the test client
  19001. // actually connects from, so the direct connection is not a trusted proxy.
  19002. svr.set_trusted_proxies({"203.0.113.66"});
  19003. std::string observed_remote_addr;
  19004. svr.Get("/ip", [&](const Request &req, Response &res) {
  19005. observed_remote_addr = req.remote_addr;
  19006. res.set_content("ok", "text/plain");
  19007. });
  19008. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19009. auto se = detail::scope_exit([&] {
  19010. svr.stop();
  19011. t.join();
  19012. ASSERT_FALSE(svr.is_running());
  19013. });
  19014. svr.wait_until_ready();
  19015. Client cli(HOST, PORT);
  19016. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19018. EXPECT_EQ(StatusCode::OK_200, res->status);
  19019. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19020. // ignored entirely and the real connection-level address retained.
  19021. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19022. observed_remote_addr == "127.0.0.1");
  19023. }
  19024. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19025. Server svr;
  19026. std::string observed_remote_addr;
  19027. std::string observed_xff;
  19028. svr.Get("/ip", [&](const Request &req, Response &res) {
  19029. observed_remote_addr = req.remote_addr;
  19030. observed_xff = req.get_header_value("X-Forwarded-For");
  19031. res.set_content("ok", "text/plain");
  19032. });
  19033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19034. auto se = detail::scope_exit([&] {
  19035. svr.stop();
  19036. t.join();
  19037. ASSERT_FALSE(svr.is_running());
  19038. });
  19039. svr.wait_until_ready();
  19040. Client cli(HOST, PORT);
  19041. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19043. EXPECT_EQ(StatusCode::OK_200, res->status);
  19044. EXPECT_EQ(observed_xff, "203.0.113.66");
  19045. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19046. observed_remote_addr == "127.0.0.1");
  19047. }
  19048. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19049. Server svr;
  19050. svr.set_trusted_proxies({"203.0.113.66"});
  19051. std::string observed_remote_addr;
  19052. std::string observed_xff;
  19053. svr.Get("/ip", [&](const Request &req, Response &res) {
  19054. observed_remote_addr = req.remote_addr;
  19055. observed_xff = req.get_header_value("X-Forwarded-For");
  19056. res.set_content("ok", "text/plain");
  19057. });
  19058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19059. auto se = detail::scope_exit([&] {
  19060. svr.stop();
  19061. t.join();
  19062. ASSERT_FALSE(svr.is_running());
  19063. });
  19064. svr.wait_until_ready();
  19065. Client cli(HOST, PORT);
  19066. auto res = cli.Get("/ip");
  19067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19068. EXPECT_EQ(StatusCode::OK_200, res->status);
  19069. EXPECT_EQ(observed_xff, "");
  19070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19071. observed_remote_addr == "127.0.0.1");
  19072. }
  19073. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19074. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19075. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19076. Server svr;
  19077. svr.set_trusted_proxies({"127.0.0.1"});
  19078. svr.Get("/ip", [](const Request &req, Response &res) {
  19079. res.set_content(req.remote_addr, "text/plain");
  19080. });
  19081. auto port = svr.bind_to_any_port("::");
  19082. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19083. thread t = thread([&] { svr.listen_after_bind(); });
  19084. auto se = detail::scope_exit([&] {
  19085. svr.stop();
  19086. t.join();
  19087. ASSERT_FALSE(svr.is_running());
  19088. });
  19089. svr.wait_until_ready();
  19090. Client cli("127.0.0.1", port);
  19091. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19093. EXPECT_EQ("198.51.100.23", res->body);
  19094. }
  19095. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19096. Server svr;
  19097. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19098. svr.Get("/ip", [](const Request &req, Response &res) {
  19099. res.set_content(req.remote_addr, "text/plain");
  19100. });
  19101. auto port = svr.bind_to_any_port(HOST);
  19102. ASSERT_GT(port, 0);
  19103. thread t = thread([&] { svr.listen_after_bind(); });
  19104. auto se = detail::scope_exit([&] {
  19105. svr.stop();
  19106. t.join();
  19107. ASSERT_FALSE(svr.is_running());
  19108. });
  19109. svr.wait_until_ready();
  19110. Client cli(HOST, port);
  19111. auto res = cli.Get(
  19112. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19114. EXPECT_EQ("198.51.100.23", res->body);
  19115. }
  19116. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19117. Server svr;
  19118. // Include the loopback address the test client actually connects from, so
  19119. // the direct connection itself is recognized as the trusted proxy hop.
  19120. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19121. std::string observed_remote_addr;
  19122. std::string observed_xff;
  19123. svr.Get("/ip", [&](const Request &req, Response &res) {
  19124. observed_remote_addr = req.remote_addr;
  19125. observed_xff = req.get_header_value("X-Forwarded-For");
  19126. res.set_content("ok", "text/plain");
  19127. });
  19128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19129. auto se = detail::scope_exit([&] {
  19130. svr.stop();
  19131. t.join();
  19132. ASSERT_FALSE(svr.is_running());
  19133. });
  19134. svr.wait_until_ready();
  19135. Client cli(HOST, PORT);
  19136. auto res = cli.Get(
  19137. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19139. EXPECT_EQ(StatusCode::OK_200, res->status);
  19140. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19141. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19142. }
  19143. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19144. Server svr;
  19145. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19146. std::string observed_remote_addr;
  19147. std::string observed_xff;
  19148. svr.Get("/ip", [&](const Request &req, Response &res) {
  19149. observed_remote_addr = req.remote_addr;
  19150. observed_xff = req.get_header_value("X-Forwarded-For");
  19151. res.set_content("ok", "text/plain");
  19152. });
  19153. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19154. auto se = detail::scope_exit([&] {
  19155. svr.stop();
  19156. t.join();
  19157. ASSERT_FALSE(svr.is_running());
  19158. });
  19159. svr.wait_until_ready();
  19160. Client cli(HOST, PORT);
  19161. auto res = cli.Get(
  19162. "/ip",
  19163. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19165. EXPECT_EQ(StatusCode::OK_200, res->status);
  19166. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19167. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19168. }
  19169. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19170. Server svr;
  19171. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19172. std::string observed_remote_addr;
  19173. std::string observed_xff;
  19174. svr.Get("/ip", [&](const Request &req, Response &res) {
  19175. observed_remote_addr = req.remote_addr;
  19176. observed_xff = req.get_header_value("X-Forwarded-For");
  19177. res.set_content("ok", "text/plain");
  19178. });
  19179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19180. auto se = detail::scope_exit([&] {
  19181. svr.stop();
  19182. t.join();
  19183. ASSERT_FALSE(svr.is_running());
  19184. });
  19185. svr.wait_until_ready();
  19186. Client cli(HOST, PORT);
  19187. auto res = cli.Get(
  19188. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19190. EXPECT_EQ(StatusCode::OK_200, res->status);
  19191. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19192. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19193. // and must not be selected.
  19194. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19195. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19196. }
  19197. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19198. Server svr;
  19199. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19200. std::string observed_remote_addr;
  19201. svr.Get("/ip", [&](const Request &req, Response &res) {
  19202. observed_remote_addr = req.remote_addr;
  19203. res.set_content("ok", "text/plain");
  19204. });
  19205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19206. auto se = detail::scope_exit([&] {
  19207. svr.stop();
  19208. t.join();
  19209. ASSERT_FALSE(svr.is_running());
  19210. });
  19211. svr.wait_until_ready();
  19212. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19213. // a forged address and the trusted proxy's own address; the forged value must
  19214. // not win over the address the trusted proxy actually recorded.
  19215. Client cli(HOST, PORT);
  19216. auto res = cli.Get(
  19217. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19219. EXPECT_EQ(StatusCode::OK_200, res->status);
  19220. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19221. }
  19222. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19223. Server svr;
  19224. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19225. std::string observed_remote_addr;
  19226. std::string observed_xff;
  19227. svr.Get("/ip", [&](const Request &req, Response &res) {
  19228. observed_remote_addr = req.remote_addr;
  19229. observed_xff = req.get_header_value("X-Forwarded-For");
  19230. res.set_content("ok", "text/plain");
  19231. });
  19232. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19233. auto se = detail::scope_exit([&] {
  19234. svr.stop();
  19235. t.join();
  19236. ASSERT_FALSE(svr.is_running());
  19237. });
  19238. svr.wait_until_ready();
  19239. Client cli(HOST, PORT);
  19240. auto res = cli.Get(
  19241. "/ip",
  19242. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19244. EXPECT_EQ(StatusCode::OK_200, res->status);
  19245. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19246. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19247. }
  19248. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19249. Server svr;
  19250. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19251. std::string observed_remote_addr;
  19252. std::string observed_xff;
  19253. svr.Get("/ip", [&](const Request &req, Response &res) {
  19254. observed_remote_addr = req.remote_addr;
  19255. observed_xff = req.get_header_value("X-Forwarded-For");
  19256. res.set_content("ok", "text/plain");
  19257. });
  19258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19259. auto se = detail::scope_exit([&] {
  19260. svr.stop();
  19261. t.join();
  19262. ASSERT_FALSE(svr.is_running());
  19263. });
  19264. svr.wait_until_ready();
  19265. std::string raw_req =
  19266. "GET /ip HTTP/1.1\r\n"
  19267. "Host: localhost\r\n"
  19268. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19269. "Connection: close\r\n"
  19270. "\r\n";
  19271. std::string out;
  19272. ASSERT_TRUE(send_request(5, raw_req, &out));
  19273. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19274. // Header parser trims surrounding whitespace of the header value
  19275. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19276. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19277. }
  19278. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19279. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19280. // their own X-Forwarded-For as a separate field line rather than extending the
  19281. // one the client sent, so every occurrence has to be taken into account.
  19282. // Reading only the first one hands back the address the client chose.
  19283. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19284. Server svr;
  19285. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19286. std::string observed_remote_addr;
  19287. size_t observed_xff_count = 0;
  19288. svr.Get("/ip", [&](const Request &req, Response &res) {
  19289. observed_remote_addr = req.remote_addr;
  19290. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19291. res.set_content("ok", "text/plain");
  19292. });
  19293. auto port = svr.bind_to_any_port(HOST);
  19294. thread t = thread([&]() { svr.listen_after_bind(); });
  19295. auto se = detail::scope_exit([&] {
  19296. svr.stop();
  19297. t.join();
  19298. ASSERT_FALSE(svr.is_running());
  19299. });
  19300. svr.wait_until_ready();
  19301. // The client supplies the first field line; the trusted proxy appends the
  19302. // address it observed as a second one.
  19303. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19304. "Host: localhost\r\n"
  19305. "X-Forwarded-For: 1.2.3.4\r\n"
  19306. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19307. "Connection: close\r\n"
  19308. "\r\n";
  19309. std::string out;
  19310. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19311. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19312. EXPECT_EQ(observed_xff_count, 2U);
  19313. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19314. // The same chain spread over one field line per hop derives the same client
  19315. // address, i.e. the split and the comma-joined representations agree.
  19316. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19317. "Host: localhost\r\n"
  19318. "X-Forwarded-For: 1.2.3.4\r\n"
  19319. "X-Forwarded-For: 198.51.100.23\r\n"
  19320. "X-Forwarded-For: 192.0.2.45\r\n"
  19321. "Connection: close\r\n"
  19322. "\r\n";
  19323. out.clear();
  19324. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19325. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19326. EXPECT_EQ(observed_xff_count, 3U);
  19327. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19328. }
  19329. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19330. // crash the server (it used to call front() on an empty vector inside
  19331. // get_client_ip). The connection-level remote address must be retained instead.
  19332. static void run_malformed_xff_test(const std::string &xff_value) {
  19333. Server svr;
  19334. svr.set_trusted_proxies({"192.0.2.45"});
  19335. std::string observed_remote_addr;
  19336. svr.Get("/ip", [&](const Request &req, Response &res) {
  19337. observed_remote_addr = req.remote_addr;
  19338. res.set_content("ok", "text/plain");
  19339. });
  19340. int port = 0;
  19341. thread t = thread([&]() {
  19342. port = svr.bind_to_any_port(HOST);
  19343. svr.listen_after_bind();
  19344. });
  19345. auto se = detail::scope_exit([&] {
  19346. svr.stop();
  19347. t.join();
  19348. ASSERT_FALSE(svr.is_running());
  19349. });
  19350. svr.wait_until_ready();
  19351. Client cli(HOST, port);
  19352. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19354. EXPECT_EQ(StatusCode::OK_200, res->status);
  19355. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19356. observed_remote_addr == "127.0.0.1");
  19357. }
  19358. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19359. run_malformed_xff_test("");
  19360. }
  19361. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19362. run_malformed_xff_test(",");
  19363. }
  19364. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19365. run_malformed_xff_test(", , ,");
  19366. }
  19367. // The same rule applies to Accept: a request whose acceptable types are spread
  19368. // over several field lines must be negotiated against all of them.
  19369. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19370. // case-insensitive connection options. Comparing the whole field value against
  19371. // one option misses a client that sends several of them, and misses every
  19372. // casing but the one written in the comparison.
  19373. //
  19374. // Sends req, reads the response, then reuses the same socket for a second
  19375. // request to find out whether the server kept the connection.
  19376. static void probe_connection_reuse(int port, const std::string &req,
  19377. bool *announced_close, bool *reusable) {
  19378. auto error = Error::Success;
  19379. auto sock = detail::create_client_socket(
  19380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19381. /*connection_timeout_sec=*/5, 0,
  19382. /*read_timeout_sec=*/1, 0,
  19383. /*write_timeout_sec=*/5, 0, std::string(), error);
  19384. ASSERT_NE(sock, INVALID_SOCKET);
  19385. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19386. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19387. "Host: localhost\r\n"
  19388. "Connection: close\r\n"
  19389. "\r\n";
  19390. std::string first_response;
  19391. std::string second_response;
  19392. detail::process_client_socket(
  19393. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19394. [&](Stream &strm) {
  19395. if (strm.write(req.data(), req.size()) !=
  19396. static_cast<ssize_t>(req.size())) {
  19397. return false;
  19398. }
  19399. char buf[512];
  19400. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19401. // Headers plus the two-byte body of the handler below
  19402. while (reader.getline()) {
  19403. first_response += reader.ptr();
  19404. if (first_response.find("ok") != std::string::npos) { break; }
  19405. }
  19406. if (strm.write(second.data(), second.size()) !=
  19407. static_cast<ssize_t>(second.size())) {
  19408. return true;
  19409. }
  19410. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19411. while (reader2.getline()) {
  19412. second_response += reader2.ptr();
  19413. if (second_response.find("ok") != std::string::npos) { break; }
  19414. }
  19415. return true;
  19416. });
  19417. *announced_close =
  19418. first_response.find("Connection: close") != std::string::npos;
  19419. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19420. }
  19421. class ConnectionTokenTest : public ::testing::Test {
  19422. protected:
  19423. void SetUp() override {
  19424. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19425. res.set_content("ok", "text/plain");
  19426. });
  19427. port_ = svr_.bind_to_any_port(HOST);
  19428. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19429. svr_.wait_until_ready();
  19430. }
  19431. void TearDown() override {
  19432. svr_.stop();
  19433. if (thread_.joinable()) { thread_.join(); }
  19434. }
  19435. Server svr_;
  19436. int port_ = 0;
  19437. thread thread_;
  19438. };
  19439. // "close" alongside another option still closes the connection, and the
  19440. // response says so rather than leaving the peer to discover it.
  19441. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19442. bool announced_close = false;
  19443. bool reusable = true;
  19444. probe_connection_reuse(port_,
  19445. "GET /keepalive HTTP/1.1\r\n"
  19446. "Host: localhost\r\n"
  19447. "Connection: keep-alive, close\r\n"
  19448. "\r\n",
  19449. &announced_close, &reusable);
  19450. EXPECT_TRUE(announced_close);
  19451. EXPECT_FALSE(reusable);
  19452. }
  19453. // "close" split over two field lines is the same list, so it is honored too.
  19454. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19455. bool announced_close = false;
  19456. bool reusable = true;
  19457. probe_connection_reuse(port_,
  19458. "GET /keepalive HTTP/1.1\r\n"
  19459. "Host: localhost\r\n"
  19460. "Connection: keep-alive\r\n"
  19461. "Connection: close\r\n"
  19462. "\r\n",
  19463. &announced_close, &reusable);
  19464. EXPECT_TRUE(announced_close);
  19465. EXPECT_FALSE(reusable);
  19466. }
  19467. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19468. // keep-alive in the spelling everyone actually sends keeps its connection.
  19469. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19470. bool announced_close = false;
  19471. bool reusable = false;
  19472. probe_connection_reuse(port_,
  19473. "GET /keepalive HTTP/1.0\r\n"
  19474. "Host: localhost\r\n"
  19475. "Connection: keep-alive\r\n"
  19476. "\r\n",
  19477. &announced_close, &reusable);
  19478. EXPECT_FALSE(announced_close);
  19479. EXPECT_TRUE(reusable);
  19480. }
  19481. // A token the value merely contains is not the token itself.
  19482. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19483. bool announced_close = false;
  19484. bool reusable = false;
  19485. probe_connection_reuse(port_,
  19486. "GET /keepalive HTTP/1.1\r\n"
  19487. "Host: localhost\r\n"
  19488. "Connection: notclose\r\n"
  19489. "\r\n",
  19490. &announced_close, &reusable);
  19491. EXPECT_FALSE(announced_close);
  19492. EXPECT_TRUE(reusable);
  19493. }
  19494. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19495. Server svr;
  19496. std::vector<std::string> observed_types;
  19497. svr.Get("/", [&](const Request &req, Response &res) {
  19498. observed_types = req.accept_content_types;
  19499. res.set_content("ok", "text/plain");
  19500. });
  19501. auto port = svr.bind_to_any_port(HOST);
  19502. thread t = thread([&]() { svr.listen_after_bind(); });
  19503. auto se = detail::scope_exit([&] {
  19504. svr.stop();
  19505. t.join();
  19506. ASSERT_FALSE(svr.is_running());
  19507. });
  19508. svr.wait_until_ready();
  19509. Client cli(HOST, port);
  19510. Headers headers;
  19511. headers.emplace("Accept", "text/plain;q=0.5");
  19512. headers.emplace("Accept", "application/json");
  19513. auto res = cli.Get("/", headers);
  19514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19515. EXPECT_EQ(StatusCode::OK_200, res->status);
  19516. // Sorted by q-value, so the second field line's type comes first
  19517. ASSERT_EQ(2U, observed_types.size());
  19518. EXPECT_EQ("application/json", observed_types[0]);
  19519. EXPECT_EQ("text/plain", observed_types[1]);
  19520. }
  19521. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19522. // empty field line must not contribute a bare comma to the combined value.
  19523. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19524. Server svr;
  19525. std::vector<std::string> observed_types;
  19526. svr.Get("/", [&](const Request &req, Response &res) {
  19527. observed_types = req.accept_content_types;
  19528. res.set_content("ok", "text/plain");
  19529. });
  19530. auto port = svr.bind_to_any_port(HOST);
  19531. thread t = thread([&]() { svr.listen_after_bind(); });
  19532. auto se = detail::scope_exit([&] {
  19533. svr.stop();
  19534. t.join();
  19535. ASSERT_FALSE(svr.is_running());
  19536. });
  19537. svr.wait_until_ready();
  19538. // Empty first field line, then a real one
  19539. std::string raw_req = "GET / HTTP/1.1\r\n"
  19540. "Host: localhost\r\n"
  19541. "Accept:\r\n"
  19542. "Accept: application/json\r\n"
  19543. "Connection: close\r\n"
  19544. "\r\n";
  19545. std::string out;
  19546. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19547. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19548. ASSERT_EQ(1U, observed_types.size());
  19549. EXPECT_EQ("application/json", observed_types[0]);
  19550. }
  19551. // The skip in get_combined_header_value() is what keeps an empty field line
  19552. // from contributing a bare comma. Only a trailing empty field line exercises
  19553. // it: a leading one is already covered by the "combined is still empty" check,
  19554. // and parse_accept_header() now ignores the empty element either way, so the
  19555. // request-level test above can no longer tell the two apart.
  19556. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19557. Headers headers;
  19558. headers.emplace("Accept", "text/html");
  19559. headers.emplace("Accept", "");
  19560. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19561. headers.clear();
  19562. headers.emplace("Accept", "");
  19563. headers.emplace("Accept", "application/json");
  19564. EXPECT_EQ("application/json",
  19565. detail::get_combined_header_value(headers, "Accept"));
  19566. }
  19567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19568. // An encoding offered on a later Accept-Encoding field line is still offered.
  19569. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19570. Server svr;
  19571. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19572. res.set_content(std::string(1024, 'x'), "text/plain");
  19573. });
  19574. auto port = svr.bind_to_any_port(HOST);
  19575. thread t = thread([&]() { svr.listen_after_bind(); });
  19576. auto se = detail::scope_exit([&] {
  19577. svr.stop();
  19578. t.join();
  19579. ASSERT_FALSE(svr.is_running());
  19580. });
  19581. svr.wait_until_ready();
  19582. Client cli(HOST, port);
  19583. cli.set_decompress(false);
  19584. Headers headers;
  19585. headers.emplace("Accept-Encoding", "identity");
  19586. headers.emplace("Accept-Encoding", "gzip");
  19587. auto res = cli.Get("/", headers);
  19588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19589. EXPECT_EQ(StatusCode::OK_200, res->status);
  19590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19591. }
  19592. #endif
  19593. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19594. // Transfer-Encoding is not its body.
  19595. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19596. Server svr;
  19597. svr.set_payload_max_length(8);
  19598. svr.Post("/test", [](const Request &, Response &res) {
  19599. res.set_content("ok", "text/plain");
  19600. });
  19601. auto port = svr.bind_to_any_port(HOST);
  19602. ASSERT_GT(port, 0);
  19603. thread t = thread([&] { svr.listen_after_bind(); });
  19604. auto se = detail::scope_exit([&] {
  19605. svr.stop();
  19606. t.join();
  19607. ASSERT_FALSE(svr.is_running());
  19608. });
  19609. svr.wait_until_ready();
  19610. std::string resp;
  19611. ASSERT_TRUE(send_request(1,
  19612. "POST /test HTTP/1.1\r\n"
  19613. "Host: localhost\r\n"
  19614. "Connection: close\r\n"
  19615. "\r\n" +
  19616. std::string(16, 'X'),
  19617. &resp, port));
  19618. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19619. }
  19620. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19621. Server svr;
  19622. svr.Post("/post", [&](const Request &req, Response &res) {
  19623. res.set_content(req.body, "text/plain");
  19624. });
  19625. svr.Put("/put", [&](const Request &req, Response &res) {
  19626. res.set_content(req.body, "text/plain");
  19627. });
  19628. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19629. res.set_content(req.body, "text/plain");
  19630. });
  19631. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19632. res.set_content(req.body, "text/plain");
  19633. });
  19634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19635. auto se = detail::scope_exit([&] {
  19636. svr.stop();
  19637. t.join();
  19638. ASSERT_FALSE(svr.is_running());
  19639. });
  19640. svr.wait_until_ready();
  19641. std::string resp;
  19642. // POST without Content-Length
  19643. ASSERT_TRUE(send_request(5,
  19644. "POST /post HTTP/1.1\r\n"
  19645. "Host: localhost\r\n"
  19646. "Connection: close\r\n"
  19647. "\r\n",
  19648. &resp));
  19649. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19650. // PUT without Content-Length
  19651. resp.clear();
  19652. ASSERT_TRUE(send_request(5,
  19653. "PUT /put HTTP/1.1\r\n"
  19654. "Host: localhost\r\n"
  19655. "Connection: close\r\n"
  19656. "\r\n",
  19657. &resp));
  19658. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19659. // PATCH without Content-Length
  19660. resp.clear();
  19661. ASSERT_TRUE(send_request(5,
  19662. "PATCH /patch HTTP/1.1\r\n"
  19663. "Host: localhost\r\n"
  19664. "Connection: close\r\n"
  19665. "\r\n",
  19666. &resp));
  19667. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19668. // DELETE without Content-Length
  19669. resp.clear();
  19670. ASSERT_TRUE(send_request(5,
  19671. "DELETE /delete HTTP/1.1\r\n"
  19672. "Host: localhost\r\n"
  19673. "Connection: close\r\n"
  19674. "\r\n",
  19675. &resp));
  19676. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19677. }
  19678. //==============================================================================
  19679. // open_stream() Tests
  19680. //==============================================================================
  19681. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19682. std::string result;
  19683. char buf[8192];
  19684. ssize_t n;
  19685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19686. result.append(buf, static_cast<size_t>(n));
  19687. }
  19688. return result;
  19689. }
  19690. // Mock stream for unit tests
  19691. class MockStream : public Stream {
  19692. public:
  19693. std::string data;
  19694. size_t pos = 0;
  19695. ssize_t error_after = -1; // -1 = no error
  19696. explicit MockStream(const std::string &d, ssize_t err = -1)
  19697. : data(d), error_after(err) {}
  19698. bool is_readable() const override { return true; }
  19699. bool wait_readable() const override { return true; }
  19700. bool wait_writable() const override { return true; }
  19701. ssize_t read(char *ptr, size_t size) override {
  19702. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19703. if (pos >= data.size()) return 0;
  19704. size_t limit =
  19705. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19706. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19707. std::memcpy(ptr, data.data() + pos, to_read);
  19708. pos += to_read;
  19709. return static_cast<ssize_t>(to_read);
  19710. }
  19711. ssize_t write(const char *, size_t) override { return -1; }
  19712. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19713. ip = "127.0.0.1";
  19714. port = 0;
  19715. }
  19716. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19717. ip = "127.0.0.1";
  19718. port = 0;
  19719. }
  19720. socket_t socket() const override { return INVALID_SOCKET; }
  19721. time_t duration() const override { return 0; }
  19722. };
  19723. TEST(StreamHandleTest, Basic) {
  19724. ClientImpl::StreamHandle handle;
  19725. EXPECT_FALSE(handle.is_valid());
  19726. handle.response = detail::make_unique<Response>();
  19727. handle.error = Error::Connection;
  19728. EXPECT_FALSE(handle.is_valid());
  19729. handle.error = Error::Success;
  19730. EXPECT_TRUE(handle.is_valid());
  19731. }
  19732. TEST(BodyReaderTest, Basic) {
  19733. MockStream stream("Hello, World!");
  19734. detail::BodyReader reader;
  19735. reader.stream = &stream;
  19736. reader.content_length = 13;
  19737. char buf[32];
  19738. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19739. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19740. EXPECT_TRUE(reader.eof);
  19741. }
  19742. TEST(BodyReaderTest, NoStream) {
  19743. detail::BodyReader reader;
  19744. char buf[32];
  19745. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19746. EXPECT_EQ(Error::Connection, reader.last_error);
  19747. }
  19748. TEST(BodyReaderTest, Error) {
  19749. MockStream stream("Hello, World!", 5);
  19750. detail::BodyReader reader;
  19751. reader.stream = &stream;
  19752. reader.content_length = 13;
  19753. char buf[32];
  19754. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19755. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19756. EXPECT_EQ(Error::Read, reader.last_error);
  19757. }
  19758. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19759. // Mock-based StreamHandle tests relying on private internals are removed.
  19760. class OpenStreamTest : public ::testing::Test {
  19761. protected:
  19762. void SetUp() override {
  19763. svr_.Get("/hello", [](const Request &, Response &res) {
  19764. res.set_content("Hello World!", "text/plain");
  19765. });
  19766. svr_.Get("/large", [](const Request &, Response &res) {
  19767. res.set_content(std::string(10000, 'X'), "text/plain");
  19768. });
  19769. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19770. res.set_content("Hello World!", "image/jpeg");
  19771. res.set_header("Content-Encoding", "UTF-8");
  19772. });
  19773. svr_.Get("/chunked", [](const Request &, Response &res) {
  19774. res.set_chunked_content_provider("text/plain",
  19775. [](size_t offset, DataSink &sink) {
  19776. if (offset < 15) {
  19777. sink.write("chunk", 5);
  19778. return true;
  19779. }
  19780. sink.done();
  19781. return true;
  19782. });
  19783. });
  19784. svr_.Get("/compressible", [](const Request &, Response &res) {
  19785. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19786. DataSink &sink) {
  19787. if (offset < 100 * 1024) {
  19788. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19789. sink.write(chunk.data(), chunk.size());
  19790. return true;
  19791. }
  19792. sink.done();
  19793. return true;
  19794. });
  19795. });
  19796. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19797. [](const Request & /*req*/, Response &res) {
  19798. auto i = new int(0);
  19799. res.set_header("Trailer", "Content-Length, X-Allowed");
  19800. res.set_chunked_content_provider(
  19801. "text/plain",
  19802. [i](size_t /*offset*/, DataSink &sink) {
  19803. switch (*i) {
  19804. case 0: sink.os << "123"; break;
  19805. case 1: sink.os << "456"; break;
  19806. case 2: sink.os << "789"; break;
  19807. case 3: {
  19808. sink.done_with_trailer(
  19809. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19810. } break;
  19811. }
  19812. (*i)++;
  19813. return true;
  19814. },
  19815. [i](bool success) {
  19816. EXPECT_TRUE(success);
  19817. delete i;
  19818. });
  19819. });
  19820. // Echo headers endpoint for header-related tests
  19821. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19822. std::string body;
  19823. for (const auto &h : req.headers) {
  19824. body.append(h.first);
  19825. body.push_back(':');
  19826. body.append(h.second);
  19827. body.push_back('\n');
  19828. }
  19829. res.set_content(body, "text/plain");
  19830. });
  19831. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19832. std::string body;
  19833. for (const auto &h : req.headers) {
  19834. body.append(h.first);
  19835. body.push_back(':');
  19836. body.append(h.second);
  19837. body.push_back('\n');
  19838. }
  19839. res.set_content(body, "text/plain");
  19840. });
  19841. port_ = svr_.bind_to_any_port("127.0.0.1");
  19842. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19843. svr_.wait_until_ready();
  19844. }
  19845. void TearDown() override {
  19846. svr_.stop();
  19847. if (thread_.joinable()) thread_.join();
  19848. }
  19849. Server svr_;
  19850. std::thread thread_;
  19851. int port_ = 0;
  19852. };
  19853. TEST_F(OpenStreamTest, Basic) {
  19854. Client cli("127.0.0.1", port_);
  19855. auto handle = cli.open_stream("GET", "/hello");
  19856. EXPECT_TRUE(handle.is_valid());
  19857. EXPECT_EQ("Hello World!", read_all(handle));
  19858. }
  19859. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19860. Client cli("127.0.0.1", port_);
  19861. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19862. ASSERT_TRUE(handle.is_valid());
  19863. EXPECT_EQ("Hello World!", read_all(handle));
  19864. }
  19865. TEST_F(OpenStreamTest, SmallBuffer) {
  19866. Client cli("127.0.0.1", port_);
  19867. auto handle = cli.open_stream("GET", "/hello");
  19868. std::string result;
  19869. char buf[4];
  19870. ssize_t n;
  19871. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19872. result.append(buf, static_cast<size_t>(n));
  19873. EXPECT_EQ("Hello World!", result);
  19874. }
  19875. TEST_F(OpenStreamTest, DefaultHeaders) {
  19876. Client cli("127.0.0.1", port_);
  19877. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19878. {
  19879. auto handle = cli.open_stream("GET", "/echo-headers");
  19880. ASSERT_TRUE(handle.is_valid());
  19881. auto body = read_all(handle);
  19882. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19883. std::string::npos);
  19884. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19885. std::string::npos);
  19886. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19887. }
  19888. // open_stream POST with body and no explicit content_type should NOT add
  19889. // text/plain Content-Type (behavior differs from non-streaming path), but
  19890. // should include Content-Length
  19891. {
  19892. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19893. ASSERT_TRUE(handle.is_valid());
  19894. auto body = read_all(handle);
  19895. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19896. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19897. }
  19898. // open_stream POST with explicit Content-Type should preserve it
  19899. {
  19900. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19901. {{"Content-Type", "application/custom"}},
  19902. "{}", "application/custom");
  19903. ASSERT_TRUE(handle.is_valid());
  19904. auto body = read_all(handle);
  19905. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19906. }
  19907. // User-specified User-Agent must not be overwritten for stream API
  19908. {
  19909. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19910. {{"User-Agent", "MyAgent/1.2"}});
  19911. ASSERT_TRUE(handle.is_valid());
  19912. auto body = read_all(handle);
  19913. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19914. }
  19915. }
  19916. TEST_F(OpenStreamTest, Large) {
  19917. Client cli("127.0.0.1", port_);
  19918. auto handle = cli.open_stream("GET", "/large");
  19919. EXPECT_EQ(10000u, read_all(handle).size());
  19920. }
  19921. TEST_F(OpenStreamTest, ConnectionError) {
  19922. Client cli("127.0.0.1", 9999);
  19923. auto handle = cli.open_stream("GET", "/hello");
  19924. EXPECT_FALSE(handle.is_valid());
  19925. }
  19926. TEST_F(OpenStreamTest, Chunked) {
  19927. Client cli("127.0.0.1", port_);
  19928. auto handle = cli.open_stream("GET", "/chunked");
  19929. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19930. "Transfer-Encoding") == "chunked");
  19931. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19932. }
  19933. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19934. Client cli("127.0.0.1", port_);
  19935. auto handle =
  19936. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19937. ASSERT_TRUE(handle.is_valid());
  19938. // Consume body to allow trailers to be received/parsed
  19939. auto body = read_all(handle);
  19940. // Explicitly parse trailers (ensure trailers are available for assertion)
  19941. handle.parse_trailers_if_needed();
  19942. EXPECT_EQ(std::string("123456789"), body);
  19943. // The response should include a Trailer header declaring both names
  19944. ASSERT_TRUE(handle.response);
  19945. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19946. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19947. handle.response->get_header_value("Trailer"));
  19948. // Prohibited trailer must not be present
  19949. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19950. // Allowed trailer should be present
  19951. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19952. EXPECT_EQ(std::string("yes"),
  19953. handle.response->get_trailer_value("X-Allowed"));
  19954. // Verify trailers are NOT present as regular headers
  19955. EXPECT_EQ(std::string(""),
  19956. handle.response->get_header_value("Content-Length"));
  19957. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19958. }
  19959. // Accepts one connection on an OS-assigned port, which it hands over through
  19960. // port_promise, reads the request head and sends back response. after_send,
  19961. // if given, runs on the connection before it is closed.
  19962. static std::thread
  19963. serve_single_response(std::promise<int> &port_promise,
  19964. const std::string &response,
  19965. std::function<void(socket_t)> after_send = nullptr) {
  19966. return std::thread([&port_promise, response, after_send] {
  19967. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19968. default_socket_options(srv);
  19969. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19971. sockaddr_in addr{};
  19972. addr.sin_family = AF_INET;
  19973. addr.sin_port = htons(0); // Let OS assign a free port
  19974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19975. int opt = 1;
  19976. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19977. #ifdef _WIN32
  19978. reinterpret_cast<const char *>(&opt),
  19979. #else
  19980. &opt,
  19981. #endif
  19982. sizeof(opt));
  19983. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19984. ::listen(srv, 1) != 0) {
  19985. port_promise.set_value(-1);
  19986. detail::close_socket(srv);
  19987. return;
  19988. }
  19989. socklen_t addr_len = sizeof(addr);
  19990. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19991. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19992. sockaddr_in cli_addr{};
  19993. socklen_t cli_len = sizeof(cli_addr);
  19994. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19995. if (cli != INVALID_SOCKET) {
  19996. // Read the complete HTTP request (until the blank line that terminates
  19997. // headers) before sending the response. If the server closes the socket
  19998. // while the client's request data is still unread in the kernel receive
  19999. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20000. // connection on both sides: it discards the client's receive buffer
  20001. // (which already holds our response) and causes any in-progress write on
  20002. // the client to fail with ECONNRESET. Reading all request data first
  20003. // ensures close() emits a graceful FIN.
  20004. {
  20005. char rbuf[256];
  20006. std::string req;
  20007. while (req.find("\r\n\r\n") == std::string::npos) {
  20008. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20009. if (n <= 0) { break; }
  20010. req.append(rbuf, static_cast<size_t>(n));
  20011. }
  20012. }
  20013. ::send(cli,
  20014. #ifdef _WIN32
  20015. static_cast<const char *>(response.c_str()),
  20016. static_cast<int>(response.size()),
  20017. #else
  20018. response.c_str(), response.size(),
  20019. #endif
  20020. 0);
  20021. if (after_send) { after_send(cli); }
  20022. detail::close_socket(cli);
  20023. }
  20024. detail::close_socket(srv);
  20025. });
  20026. }
  20027. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20028. #ifndef _WIN32
  20029. signal(SIGPIPE, SIG_IGN);
  20030. #endif
  20031. std::promise<int> port_promise;
  20032. auto port_future = port_promise.get_future();
  20033. auto server_thread =
  20034. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20035. "Content-Type: text/plain\r\n"
  20036. "Content-Length: not-a-number\r\n"
  20037. "Connection: close\r\n"
  20038. "\r\n"
  20039. "hello");
  20040. auto port = port_future.get();
  20041. ASSERT_GT(port, 0);
  20042. Client cli("127.0.0.1", port);
  20043. auto handle = cli.open_stream("GET", "/");
  20044. EXPECT_FALSE(handle.is_valid());
  20045. server_thread.join();
  20046. }
  20047. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20048. #ifndef _WIN32
  20049. signal(SIGPIPE, SIG_IGN);
  20050. #endif
  20051. std::promise<int> port_promise;
  20052. auto port_future = port_promise.get_future();
  20053. auto server_thread = serve_single_response(
  20054. port_promise, "HTTP/1.1 200 OK\r\n"
  20055. "Content-Type: text/plain\r\n"
  20056. "Content-Length: 99999999999999999999999999\r\n"
  20057. "Connection: close\r\n"
  20058. "\r\n"
  20059. "hello");
  20060. auto port = port_future.get();
  20061. ASSERT_GT(port, 0);
  20062. // Historically std::stoull would throw std::out_of_range here and crash
  20063. // the process, then parsing silently clamped to a bogus framing length and
  20064. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20065. // so the stream fails to open, matching the not-a-number case above. The
  20066. // process still must NOT terminate.
  20067. Client cli("127.0.0.1", port);
  20068. auto handle = cli.open_stream("GET", "/");
  20069. EXPECT_FALSE(handle.is_valid());
  20070. server_thread.join();
  20071. }
  20072. // Serves `response` to the single request `fn` makes with a fresh client.
  20073. template <typename Fn>
  20074. static void with_single_response(const std::string &response, Fn fn) {
  20075. #ifndef _WIN32
  20076. signal(SIGPIPE, SIG_IGN);
  20077. #endif
  20078. std::promise<int> port_promise;
  20079. auto port_future = port_promise.get_future();
  20080. auto server_thread = serve_single_response(port_promise, response);
  20081. auto se = detail::scope_exit([&] { server_thread.join(); });
  20082. auto port = port_future.get();
  20083. ASSERT_GT(port, 0);
  20084. Client cli("127.0.0.1", port);
  20085. fn(cli);
  20086. }
  20087. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20088. // too, also in a build without the decoder for the advertised coding.
  20089. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20090. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20091. const auto response = "HTTP/1.1 200 OK\r\n"
  20092. "Content-Encoding: gzip\r\n"
  20093. "Content-Length: " +
  20094. std::to_string(gzipped.size()) +
  20095. "\r\n"
  20096. "Connection: close\r\n\r\n" +
  20097. gzipped;
  20098. with_single_response(response, [&](Client &cli) {
  20099. cli.set_decompress(false);
  20100. auto handle = cli.open_stream("GET", "/");
  20101. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20102. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20103. EXPECT_EQ(gzipped, read_all(handle));
  20104. EXPECT_FALSE(handle.has_read_error());
  20105. });
  20106. with_single_response(response, [&](Client &cli) {
  20107. cli.set_decompress(false);
  20108. auto res = stream::Get(cli, "/", 7);
  20109. ASSERT_TRUE(res) << to_string(res.error());
  20110. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20111. EXPECT_EQ(gzipped, res.read_all());
  20112. EXPECT_FALSE(res.has_read_error());
  20113. });
  20114. }
  20115. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20116. // Neither Content-Length nor chunked: the body ends at the close
  20117. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20118. "Connection: close\r\n"
  20119. "\r\n"
  20120. "hello";
  20121. with_single_response(close_delimited, [](Client &cli) {
  20122. auto handle = cli.open_stream("GET", "/");
  20123. ASSERT_TRUE(handle.is_valid());
  20124. EXPECT_EQ("hello", read_all(handle));
  20125. EXPECT_FALSE(handle.has_read_error());
  20126. });
  20127. // A close before the end of the Content-Length is still an error
  20128. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20129. "Content-Length: 10\r\n"
  20130. "\r\n"
  20131. "hello";
  20132. with_single_response(short_content_length, [](Client &cli) {
  20133. auto handle = cli.open_stream("GET", "/");
  20134. ASSERT_TRUE(handle.is_valid());
  20135. read_all(handle);
  20136. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20137. });
  20138. // So is a close before the last chunk
  20139. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20140. "Transfer-Encoding: chunked\r\n"
  20141. "\r\n"
  20142. "5\r\nhello\r\n";
  20143. with_single_response(short_chunked, [](Client &cli) {
  20144. auto handle = cli.open_stream("GET", "/");
  20145. ASSERT_TRUE(handle.is_valid());
  20146. read_all(handle);
  20147. EXPECT_TRUE(handle.has_read_error());
  20148. });
  20149. }
  20150. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20151. const char *responses[] = {
  20152. "HTTP/1.1 103 Early Hints\r\n"
  20153. "Link: </style.css>; rel=preload\r\n"
  20154. "\r\n"
  20155. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20156. "HTTP/1.1 100 Continue\r\n"
  20157. "X-Note: interim\r\n"
  20158. "\r\n"
  20159. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20160. };
  20161. for (auto response : responses) {
  20162. with_single_response(response, [](Client &cli) {
  20163. auto res = cli.Get("/");
  20164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20165. EXPECT_EQ(StatusCode::OK_200, res->status);
  20166. EXPECT_EQ("ok", res->body);
  20167. });
  20168. }
  20169. }
  20170. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20171. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20172. const std::string final_response =
  20173. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20174. std::string interims;
  20175. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20176. interims += interim;
  20177. }
  20178. with_single_response(interims + final_response, [](Client &cli) {
  20179. auto res = cli.Get("/");
  20180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20181. EXPECT_EQ("ok", res->body);
  20182. });
  20183. with_single_response(interims + interim + final_response, [](Client &cli) {
  20184. auto res = cli.Get("/");
  20185. ASSERT_FALSE(res);
  20186. EXPECT_EQ(Error::Read, res.error());
  20187. });
  20188. }
  20189. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20190. #ifndef _WIN32
  20191. signal(SIGPIPE, SIG_IGN);
  20192. #endif
  20193. // The server answers the head without asking for the body. Bytes it then
  20194. // reads on the connection would be taken for the body the request declared.
  20195. auto closed_by_client = false;
  20196. std::promise<int> port_promise;
  20197. auto server_thread = serve_single_response(
  20198. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20199. [&](socket_t sock) {
  20200. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20201. char buf[256];
  20202. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20203. });
  20204. Client cli("127.0.0.1", port_promise.get_future().get());
  20205. cli.set_keep_alive(true);
  20206. cli.set_read_timeout(1, 0);
  20207. // Long enough for the client to send Expect: 100-continue.
  20208. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20210. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20211. cli.Get("/second");
  20212. server_thread.join();
  20213. EXPECT_TRUE(closed_by_client);
  20214. }
  20215. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20216. // Long enough for the client to send Expect: 100-continue
  20217. with_single_response(
  20218. "HTTP/1.1 103 Early Hints\r\n"
  20219. "Link: </style.css>; rel=preload\r\n"
  20220. "\r\n"
  20221. "HTTP/1.1 401 Unauthorized\r\n"
  20222. "Content-Length: 0\r\n\r\n",
  20223. [](Client &cli) {
  20224. cli.set_read_timeout(2, 0);
  20225. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20227. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20228. });
  20229. }
  20230. #ifdef CPPHTTPLIB_SSL_ENABLED
  20231. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20232. #ifndef _WIN32
  20233. signal(SIGPIPE, SIG_IGN);
  20234. #endif
  20235. auto reused = false;
  20236. std::promise<int> port_promise;
  20237. auto server_thread = serve_single_response(
  20238. port_promise,
  20239. "HTTP/1.1 401 Unauthorized\r\n"
  20240. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20241. "Content-Length: 0\r\n\r\n",
  20242. [&](socket_t sock) {
  20243. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20244. char buf[256];
  20245. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20246. });
  20247. Client cli("127.0.0.1", port_promise.get_future().get());
  20248. cli.set_keep_alive(true);
  20249. cli.set_digest_auth("user", "pass");
  20250. cli.set_read_timeout(1, 0);
  20251. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20252. server_thread.join();
  20253. EXPECT_FALSE(reused);
  20254. }
  20255. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20256. // Any other answer to CONNECT would read as the origin's response.
  20257. struct {
  20258. const char *response;
  20259. bool passed_on;
  20260. } cases[] = {
  20261. {"HTTP/1.1 201 Created\r\n"
  20262. "Set-Cookie: session=from-proxy\r\n"
  20263. "Content-Length: 0\r\n\r\n",
  20264. false},
  20265. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20266. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20267. "Content-Length: 0\r\n\r\n",
  20268. true},
  20269. };
  20270. for (const auto &c : cases) {
  20271. std::promise<int> port_promise;
  20272. auto server_thread = serve_single_response(port_promise, c.response);
  20273. SSLClient cli("example.com", 443);
  20274. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20275. auto res = cli.Get("/");
  20276. server_thread.join();
  20277. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20278. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20279. if (res) {
  20280. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20281. }
  20282. }
  20283. }
  20284. #endif
  20285. // Records the client's error logger calls as "error METHOD path", or
  20286. // "error null" for a call without a request
  20287. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20288. return [&log](const Error &err, const Request *req) {
  20289. log.push_back(to_string(err) + " " +
  20290. (req ? req->method + " " + req->path : "null"));
  20291. };
  20292. }
  20293. // A failed request is reported once, with the request the caller made
  20294. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20295. Server svr;
  20296. svr.Get("/big", [](const Request &, Response &res) {
  20297. res.set_content(std::string(100000, 'b'), "text/plain");
  20298. });
  20299. auto port = svr.bind_to_any_port(HOST);
  20300. std::thread t([&]() { svr.listen_after_bind(); });
  20301. auto se = detail::scope_exit([&] {
  20302. svr.stop();
  20303. t.join();
  20304. });
  20305. svr.wait_until_ready();
  20306. Client cli(HOST, port);
  20307. std::vector<std::string> log;
  20308. cli.set_error_logger(record_errors(log));
  20309. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20310. cli.Get("/big", [](const char *, size_t) { return false; });
  20311. EXPECT_EQ(expected, log);
  20312. log.clear();
  20313. cli.Get("/big", [](size_t, size_t) { return false; });
  20314. EXPECT_EQ(expected, log);
  20315. }
  20316. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20317. // Fails while the body is read
  20318. auto broken = [](const Request &, Response &res) {
  20319. res.set_content_provider(10, "text/plain",
  20320. [](size_t, size_t, DataSink &) { return false; });
  20321. };
  20322. Server other;
  20323. other.Get("/broken", broken);
  20324. auto other_port = other.bind_to_any_port(HOST);
  20325. std::thread other_t([&]() { other.listen_after_bind(); });
  20326. auto other_se = detail::scope_exit([&] {
  20327. other.stop();
  20328. other_t.join();
  20329. });
  20330. other.wait_until_ready();
  20331. Server svr;
  20332. svr.Get("/broken", broken);
  20333. svr.Get("/same-origin",
  20334. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20335. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20336. res.set_redirect("http://" + std::string(HOST) + ":" +
  20337. std::to_string(other_port) + "/broken");
  20338. });
  20339. auto port = svr.bind_to_any_port(HOST);
  20340. std::thread t([&]() { svr.listen_after_bind(); });
  20341. auto se = detail::scope_exit([&] {
  20342. svr.stop();
  20343. t.join();
  20344. });
  20345. svr.wait_until_ready();
  20346. Client cli(HOST, port);
  20347. cli.set_follow_location(true);
  20348. std::vector<std::string> log;
  20349. cli.set_error_logger(record_errors(log));
  20350. for (auto path : {"/same-origin", "/cross-origin"}) {
  20351. log.clear();
  20352. auto res = cli.Get(path);
  20353. ASSERT_FALSE(res);
  20354. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20355. log);
  20356. }
  20357. }
  20358. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20359. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20360. std::vector<std::string> log;
  20361. cli.set_error_logger(record_errors(log));
  20362. auto handle = cli.open_stream("GET", "/x");
  20363. EXPECT_FALSE(handle.is_valid());
  20364. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20365. log);
  20366. });
  20367. }
  20368. #ifdef CPPHTTPLIB_SSL_ENABLED
  20369. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20370. // Not a TLS server, so the handshake fails. It waits for a request line in
  20371. // the handshake bytes, so a short read timeout lets it close quickly.
  20372. Server svr;
  20373. svr.set_read_timeout(0, 100000);
  20374. svr.Get("/x", [](const Request &, Response &res) {
  20375. res.set_content("x", "text/plain");
  20376. });
  20377. auto port = svr.bind_to_any_port(HOST);
  20378. std::thread t([&]() { svr.listen_after_bind(); });
  20379. auto se = detail::scope_exit([&] {
  20380. svr.stop();
  20381. t.join();
  20382. });
  20383. svr.wait_until_ready();
  20384. std::vector<std::string> log;
  20385. SSLClient cli(HOST, port);
  20386. cli.enable_server_certificate_verification(false);
  20387. cli.set_error_logger(record_errors(log));
  20388. auto res = cli.Get("/x");
  20389. ASSERT_FALSE(res);
  20390. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20391. log.clear();
  20392. auto handle = cli.open_stream("GET", "/x");
  20393. EXPECT_FALSE(handle.is_valid());
  20394. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20395. log.clear();
  20396. SSLClient no_ca(HOST, port);
  20397. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20398. no_ca.set_error_logger(record_errors(log));
  20399. res = no_ca.Get("/x");
  20400. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20401. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20402. }
  20403. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20404. #ifndef _WIN32
  20405. signal(SIGPIPE, SIG_IGN);
  20406. #endif
  20407. // Refused, answered with a challenge, or closed without an answer
  20408. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20409. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20410. "Content-Length: 0\r\n\r\n",
  20411. ""}) {
  20412. std::promise<int> port_promise;
  20413. auto server_thread = serve_single_response(port_promise, response);
  20414. SSLClient cli("example.com", 443);
  20415. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20416. std::vector<std::string> log;
  20417. cli.set_error_logger(record_errors(log));
  20418. auto res = cli.Get("/");
  20419. server_thread.join();
  20420. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20421. << response;
  20422. }
  20423. }
  20424. #endif
  20425. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20426. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20427. // the chunked coding and drop Content-Length, so a front-end that trusts
  20428. // Content-Length would disagree about where the body ends (response
  20429. // smuggling). The client must reject such a response.
  20430. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20431. for (const char *te : {"chunked", "gzip, chunked"}) {
  20432. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20433. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20434. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20435. "5\r\nhello\r\n0\r\n\r\n";
  20436. with_single_response(response, [&](Client &cli) {
  20437. auto res = cli.Get("/");
  20438. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20439. EXPECT_EQ(Error::Read, res.error()) << te;
  20440. });
  20441. with_single_response(response, [&](Client &cli) {
  20442. auto handle = cli.open_stream("GET", "/");
  20443. EXPECT_FALSE(handle.is_valid()) << te;
  20444. EXPECT_EQ(Error::Read, handle.error) << te;
  20445. });
  20446. }
  20447. }
  20448. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20449. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20450. // closing the connection (unlike a request, which must be rejected).
  20451. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20452. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20453. "Transfer-Encoding: chunked\r\n"
  20454. "Connection: close\r\n"
  20455. "\r\n"
  20456. "5\r\nhello\r\n0\r\n\r\n",
  20457. "HTTP/1.1 200 OK\r\n"
  20458. "Transfer-Encoding: gzip\r\n"
  20459. "Connection: close\r\n"
  20460. "\r\n"
  20461. "hello"}) {
  20462. with_single_response(response, [&](Client &cli) {
  20463. auto res = cli.Get("/");
  20464. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20465. EXPECT_EQ("hello", res->body);
  20466. });
  20467. with_single_response(response, [&](Client &cli) {
  20468. auto handle = cli.open_stream("GET", "/");
  20469. ASSERT_TRUE(handle.is_valid()) << response;
  20470. EXPECT_EQ("hello", read_all(handle));
  20471. });
  20472. }
  20473. }
  20474. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20475. // framing headers describe nothing to read and must not be rejected.
  20476. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20477. const std::string framing = "Content-Length: 5\r\n"
  20478. "Transfer-Encoding: chunked\r\n"
  20479. "Connection: close\r\n"
  20480. "\r\n";
  20481. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20482. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20483. });
  20484. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20485. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20486. });
  20487. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20488. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20489. with_single_response(response, [&](Client &cli) {
  20490. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20491. });
  20492. with_single_response(response, [&](Client &cli) {
  20493. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20494. });
  20495. }
  20496. }
  20497. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20498. // header section, so a stream opened on one has nothing to read, whatever
  20499. // framing or coding headers it carries.
  20500. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20501. struct Case {
  20502. const char *method;
  20503. const char *status;
  20504. };
  20505. // A reader of the declared body reports an early close when nothing
  20506. // follows, and hands back what does.
  20507. struct Framing {
  20508. const char *headers;
  20509. const char *after;
  20510. };
  20511. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20512. Case{"GET", "304 Not Modified"}}) {
  20513. for (const auto &f :
  20514. {Framing{"Content-Length: 5\r\n", ""},
  20515. Framing{"Content-Length: 5\r\n", "hello"},
  20516. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20517. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20518. // Not decoded, so a build without Brotli opens it too
  20519. Framing{"Content-Encoding: br\r\n", ""}}) {
  20520. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20521. "Connection: close\r\n"
  20522. "\r\n" +
  20523. f.after;
  20524. with_single_response(response, [&](Client &cli) {
  20525. auto handle = cli.open_stream(c.method, "/");
  20526. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20527. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20528. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20529. });
  20530. }
  20531. }
  20532. }
  20533. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20534. // response, is faulty framing, so the connection is not reused after it.
  20535. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20536. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20537. "Content-Length: 0\r\n"
  20538. "Transfer-Encoding: chunked\r\n"
  20539. "\r\n"
  20540. "5\r\nhello\r\n0\r\n\r\n",
  20541. "HTTP/1.0 200 Connection established\r\n"
  20542. "Connection: keep-alive\r\n"
  20543. "Transfer-Encoding: chunked\r\n"
  20544. "\r\n"
  20545. "5\r\nhello\r\n0\r\n\r\n"}) {
  20546. with_single_response(response, [&](Client &cli) {
  20547. cli.set_keep_alive(true);
  20548. auto res = cli.Get("/");
  20549. ASSERT_TRUE(res) << response;
  20550. EXPECT_EQ("hello", res->body);
  20551. EXPECT_FALSE(cli.is_socket_open()) << response;
  20552. });
  20553. }
  20554. }
  20555. // A payload max length of 0 means no limit, however the body is framed.
  20556. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20557. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20558. "Transfer-Encoding: chunked\r\n"
  20559. "\r\n"
  20560. "5\r\nhello\r\n0\r\n\r\n",
  20561. "HTTP/1.1 200 OK\r\n"
  20562. "Connection: close\r\n"
  20563. "\r\n"
  20564. "hello"}) {
  20565. with_single_response(response, [&](Client &cli) {
  20566. cli.set_payload_max_length(0);
  20567. auto res = cli.Get("/");
  20568. ASSERT_TRUE(res) << response;
  20569. EXPECT_EQ("hello", res->body) << response;
  20570. });
  20571. }
  20572. }
  20573. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20574. Server svr;
  20575. svr.set_payload_max_length(0);
  20576. svr.Post("/echo", [](const Request &req, Response &res) {
  20577. res.set_content(req.body, "text/plain");
  20578. });
  20579. auto port = svr.bind_to_any_port(HOST);
  20580. thread t = thread([&] { svr.listen_after_bind(); });
  20581. auto se = detail::scope_exit([&] {
  20582. svr.stop();
  20583. t.join();
  20584. ASSERT_FALSE(svr.is_running());
  20585. });
  20586. svr.wait_until_ready();
  20587. Client cli(HOST, port);
  20588. auto res = cli.Post(
  20589. "/echo",
  20590. [](size_t /*offset*/, DataSink &sink) {
  20591. sink.write("hello", 5);
  20592. sink.done();
  20593. return true;
  20594. },
  20595. "text/plain");
  20596. ASSERT_TRUE(res);
  20597. EXPECT_EQ(StatusCode::OK_200, res->status);
  20598. EXPECT_EQ("hello", res->body);
  20599. }
  20600. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20601. TEST_F(OpenStreamTest, Gzip) {
  20602. Client cli("127.0.0.1", port_);
  20603. auto handle = cli.open_stream("GET", "/compressible", {},
  20604. {{"Accept-Encoding", "gzip"}});
  20605. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20606. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20607. }
  20608. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20609. Client cli("127.0.0.1", port_);
  20610. auto handle =
  20611. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20612. {{"Accept-Encoding", "gzip"}});
  20613. ASSERT_TRUE(handle.is_valid());
  20614. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20615. EXPECT_EQ("123456789", read_all(handle));
  20616. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20617. }
  20618. #endif
  20619. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20620. TEST_F(OpenStreamTest, Brotli) {
  20621. Client cli("127.0.0.1", port_);
  20622. auto handle =
  20623. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20624. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20625. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20626. }
  20627. #endif
  20628. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20629. TEST_F(OpenStreamTest, Zstd) {
  20630. Client cli("127.0.0.1", port_);
  20631. auto handle = cli.open_stream("GET", "/compressible", {},
  20632. {{"Accept-Encoding", "zstd"}});
  20633. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20634. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20635. }
  20636. #endif
  20637. #ifdef CPPHTTPLIB_SSL_ENABLED
  20638. class SSLOpenStreamTest : public ::testing::Test {
  20639. protected:
  20640. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20641. void SetUp() override {
  20642. svr_.Get("/hello", [](const Request &, Response &res) {
  20643. res.set_content("Hello SSL World!", "text/plain");
  20644. });
  20645. svr_.Get("/chunked", [](const Request &, Response &res) {
  20646. res.set_chunked_content_provider("text/plain",
  20647. [](size_t offset, DataSink &sink) {
  20648. if (offset < 15) {
  20649. sink.write("chunk", 5);
  20650. return true;
  20651. }
  20652. sink.done();
  20653. return true;
  20654. });
  20655. });
  20656. svr_.Post("/echo", [](const Request &req, Response &res) {
  20657. res.set_content(req.body, req.get_header_value("Content-Type"));
  20658. });
  20659. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20660. std::string body = req.body;
  20661. res.set_chunked_content_provider(
  20662. "text/plain", [body](size_t offset, DataSink &sink) {
  20663. if (offset < body.size()) {
  20664. sink.write(body.data() + offset, body.size() - offset);
  20665. }
  20666. sink.done();
  20667. return true;
  20668. });
  20669. });
  20670. port_ = svr_.bind_to_any_port("127.0.0.1");
  20671. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20672. svr_.wait_until_ready();
  20673. }
  20674. void TearDown() override {
  20675. svr_.stop();
  20676. if (thread_.joinable()) thread_.join();
  20677. }
  20678. SSLServer svr_;
  20679. std::thread thread_;
  20680. int port_ = 0;
  20681. };
  20682. TEST_F(SSLOpenStreamTest, Basic) {
  20683. SSLClient cli("127.0.0.1", port_);
  20684. cli.enable_server_certificate_verification(false);
  20685. auto handle = cli.open_stream("GET", "/hello");
  20686. ASSERT_TRUE(handle.is_valid());
  20687. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20688. }
  20689. TEST_F(SSLOpenStreamTest, Chunked) {
  20690. SSLClient cli("127.0.0.1", port_);
  20691. cli.enable_server_certificate_verification(false);
  20692. auto handle = cli.open_stream("GET", "/chunked");
  20693. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20694. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20695. "Transfer-Encoding") == "chunked");
  20696. auto body = read_all(handle);
  20697. EXPECT_EQ("chunkchunkchunk", body);
  20698. }
  20699. TEST_F(SSLOpenStreamTest, Post) {
  20700. SSLClient cli("127.0.0.1", port_);
  20701. cli.enable_server_certificate_verification(false);
  20702. auto handle =
  20703. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20704. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20705. EXPECT_EQ(200, handle.response->status);
  20706. auto body = read_all(handle);
  20707. EXPECT_EQ("Hello SSL POST", body);
  20708. }
  20709. TEST_F(SSLOpenStreamTest, PostChunked) {
  20710. SSLClient cli("127.0.0.1", port_);
  20711. cli.enable_server_certificate_verification(false);
  20712. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20713. "Chunked SSL Data", "text/plain");
  20714. ASSERT_TRUE(handle.is_valid());
  20715. EXPECT_EQ(200, handle.response->status);
  20716. auto body = read_all(handle);
  20717. EXPECT_EQ("Chunked SSL Data", body);
  20718. }
  20719. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20720. // Content-Length is terminated by the server closing the connection. When the
  20721. // SSL peer sends a close_notify after the body, the client must treat it as a
  20722. // clean EOF and return a successful response rather than an error.
  20723. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20725. ASSERT_TRUE(svr.is_valid());
  20726. svr.set_keep_alive_max_count(1);
  20727. const std::string expected_body = "Hello from connection-close response!";
  20728. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20729. res.set_content_provider("text/plain",
  20730. [&](size_t offset, DataSink &sink) -> bool {
  20731. if (offset < expected_body.size()) {
  20732. sink.write(expected_body.data() + offset,
  20733. expected_body.size() - offset);
  20734. }
  20735. sink.done();
  20736. return true;
  20737. });
  20738. });
  20739. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20740. auto se = detail::scope_exit([&] {
  20741. svr.stop();
  20742. listen_thread.join();
  20743. ASSERT_FALSE(svr.is_running());
  20744. });
  20745. svr.wait_until_ready();
  20746. SSLClient cli(HOST, PORT);
  20747. cli.enable_server_certificate_verification(false);
  20748. auto res = cli.Get("/no-content-length");
  20749. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20750. EXPECT_EQ(StatusCode::OK_200, res->status);
  20751. EXPECT_EQ(expected_body, res->body);
  20752. }
  20753. #endif // CPPHTTPLIB_SSL_ENABLED
  20754. //==============================================================================
  20755. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20756. // results for various scenarios.
  20757. //==============================================================================
  20758. TEST(ParityTest, GetVsOpenStream) {
  20759. Server svr;
  20760. const std::string path = "/parity";
  20761. const std::string content = "Parity test content: hello world";
  20762. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20763. res.set_content(content, "text/plain");
  20764. });
  20765. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20766. auto se = detail::scope_exit([&] {
  20767. svr.stop();
  20768. t.join();
  20769. ASSERT_FALSE(svr.is_running());
  20770. });
  20771. svr.wait_until_ready();
  20772. Client cli(HOST, PORT);
  20773. // Non-stream path
  20774. auto r1 = cli.Get(path);
  20775. ASSERT_TRUE(r1);
  20776. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20777. // Stream path
  20778. auto h = cli.open_stream("GET", path);
  20779. ASSERT_TRUE(h.is_valid());
  20780. EXPECT_EQ(r1->body, read_all(h));
  20781. }
  20782. // Helper to compress data with provided compressor type T
  20783. template <typename Compressor>
  20784. static std::string compress_payload_for_parity(const std::string &in) {
  20785. std::string out;
  20786. Compressor compressor;
  20787. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20788. [&](const char *data, size_t n) {
  20789. out.append(data, n);
  20790. return true;
  20791. });
  20792. EXPECT_TRUE(ok);
  20793. return out;
  20794. }
  20795. // Helper function for compression parity tests
  20796. template <typename Compressor>
  20797. static void test_compression_parity(const std::string &original,
  20798. const std::string &path,
  20799. const std::string &encoding) {
  20800. const std::string compressed =
  20801. compress_payload_for_parity<Compressor>(original);
  20802. Server svr;
  20803. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20804. res.set_content(compressed, "application/octet-stream");
  20805. res.set_header("Content-Encoding", encoding);
  20806. });
  20807. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20808. auto se = detail::scope_exit([&] {
  20809. svr.stop();
  20810. t.join();
  20811. ASSERT_FALSE(svr.is_running());
  20812. });
  20813. svr.wait_until_ready();
  20814. Client cli(HOST, PORT);
  20815. // Non-streaming
  20816. {
  20817. auto res = cli.Get(path);
  20818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20819. EXPECT_EQ(StatusCode::OK_200, res->status);
  20820. EXPECT_EQ(original, res->body);
  20821. }
  20822. // Streaming
  20823. {
  20824. auto h = cli.open_stream("GET", path);
  20825. ASSERT_TRUE(h.is_valid());
  20826. EXPECT_EQ(original, read_all(h));
  20827. }
  20828. }
  20829. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20830. TEST(ParityTest, Gzip) {
  20831. test_compression_parity<detail::gzip_compressor>(
  20832. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20833. }
  20834. #endif
  20835. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20836. TEST(ParityTest, Brotli) {
  20837. test_compression_parity<detail::brotli_compressor>(
  20838. "Hello, brotli parity test payload", "/parity-br", "br");
  20839. }
  20840. #endif
  20841. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20842. TEST(ParityTest, Zstd) {
  20843. test_compression_parity<detail::zstd_compressor>(
  20844. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20845. }
  20846. #endif
  20847. //==============================================================================
  20848. // New Stream API Tests
  20849. //==============================================================================
  20850. inline std::string read_body(httplib::stream::Result &result) {
  20851. std::string body;
  20852. while (result.next()) {
  20853. body.append(result.data(), result.size());
  20854. }
  20855. return body;
  20856. }
  20857. TEST(ClientConnectionTest, Basic) {
  20858. httplib::ClientConnection conn;
  20859. EXPECT_FALSE(conn.is_open());
  20860. conn.sock = 1;
  20861. EXPECT_TRUE(conn.is_open());
  20862. httplib::ClientConnection conn2(std::move(conn));
  20863. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20864. conn2.sock = INVALID_SOCKET;
  20865. }
  20866. // Unified test server for all stream::* tests
  20867. class StreamApiTest : public ::testing::Test {
  20868. protected:
  20869. void SetUp() override {
  20870. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20871. res.set_content("Hello World!", "text/plain");
  20872. });
  20873. svr_.Get("/echo-params",
  20874. [](const httplib::Request &req, httplib::Response &res) {
  20875. std::string r;
  20876. for (const auto &p : req.params) {
  20877. if (!r.empty()) r += "&";
  20878. r += p.first + "=" + p.second;
  20879. }
  20880. res.set_content(r, "text/plain");
  20881. });
  20882. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20883. res.set_content(req.body, req.get_header_value("Content-Type"));
  20884. });
  20885. svr_.Post("/echo-headers",
  20886. [](const httplib::Request &req, httplib::Response &res) {
  20887. std::string r;
  20888. for (const auto &h : req.headers)
  20889. r += h.first + ": " + h.second + "\n";
  20890. res.set_content(r, "text/plain");
  20891. });
  20892. svr_.Post("/echo-params",
  20893. [](const httplib::Request &req, httplib::Response &res) {
  20894. std::string r = "params:";
  20895. for (const auto &p : req.params)
  20896. r += p.first + "=" + p.second + ";";
  20897. res.set_content(r + " body:" + req.body, "text/plain");
  20898. });
  20899. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20900. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20901. });
  20902. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20903. res.set_content("PUT:" + req.body, "text/plain");
  20904. });
  20905. svr_.Patch("/echo",
  20906. [](const httplib::Request &req, httplib::Response &res) {
  20907. res.set_content("PATCH:" + req.body, "text/plain");
  20908. });
  20909. svr_.Delete(
  20910. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20911. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20912. "text/plain");
  20913. });
  20914. svr_.Get("/head-test",
  20915. [](const httplib::Request &, httplib::Response &res) {
  20916. res.set_content("body for HEAD", "text/plain");
  20917. });
  20918. svr_.Options("/options",
  20919. [](const httplib::Request &, httplib::Response &res) {
  20920. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20921. });
  20922. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20923. svr_.wait_until_ready();
  20924. }
  20925. void TearDown() override {
  20926. svr_.stop();
  20927. if (thread_.joinable()) thread_.join();
  20928. }
  20929. httplib::Server svr_;
  20930. std::thread thread_;
  20931. };
  20932. // stream::Get tests
  20933. TEST_F(StreamApiTest, GetBasic) {
  20934. httplib::Client cli(HOST, PORT);
  20935. auto result = httplib::stream::Get(cli, "/hello");
  20936. ASSERT_TRUE(result.is_valid());
  20937. EXPECT_EQ(200, result.status());
  20938. EXPECT_EQ("Hello World!", read_body(result));
  20939. }
  20940. TEST_F(StreamApiTest, GetWithParams) {
  20941. httplib::Client cli(HOST, PORT);
  20942. httplib::Params params{{"foo", "bar"}};
  20943. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20944. ASSERT_TRUE(result.is_valid());
  20945. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20946. }
  20947. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20948. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20949. httplib::Client cli(HOST, PORT);
  20950. cli.set_payload_max_length(0);
  20951. auto result = httplib::stream::Get(cli, "/hello");
  20952. ASSERT_TRUE(result.is_valid());
  20953. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20954. EXPECT_EQ("Hello World!", read_body(result));
  20955. }
  20956. #endif
  20957. TEST_F(StreamApiTest, GetConnectionError) {
  20958. httplib::Client cli(HOST, 9999);
  20959. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20960. }
  20961. TEST_F(StreamApiTest, Get404) {
  20962. httplib::Client cli(HOST, PORT);
  20963. auto result = httplib::stream::Get(cli, "/nonexistent");
  20964. EXPECT_TRUE(result.is_valid());
  20965. EXPECT_EQ(404, result.status());
  20966. }
  20967. // stream::Post tests
  20968. TEST_F(StreamApiTest, PostBasic) {
  20969. httplib::Client cli(HOST, PORT);
  20970. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20971. "application/json");
  20972. ASSERT_TRUE(result.is_valid());
  20973. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20974. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20975. }
  20976. TEST_F(StreamApiTest, PostWithHeaders) {
  20977. httplib::Client cli(HOST, PORT);
  20978. httplib::Headers headers{{"X-Custom", "value"}};
  20979. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20980. "text/plain");
  20981. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20982. }
  20983. TEST_F(StreamApiTest, PostWithParams) {
  20984. httplib::Client cli(HOST, PORT);
  20985. httplib::Params params{{"k", "v"}};
  20986. auto result =
  20987. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20988. auto body = read_body(result);
  20989. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20990. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20991. }
  20992. TEST_F(StreamApiTest, PostLarge) {
  20993. httplib::Client cli(HOST, PORT);
  20994. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20995. size_t total = 0;
  20996. while (result.next()) {
  20997. total += result.size();
  20998. }
  20999. EXPECT_EQ(100u * 1024u, total);
  21000. }
  21001. // stream::Put/Patch tests
  21002. TEST_F(StreamApiTest, PutAndPatch) {
  21003. httplib::Client cli(HOST, PORT);
  21004. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21005. EXPECT_EQ("PUT:test", read_body(put));
  21006. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21007. EXPECT_EQ("PATCH:test", read_body(patch));
  21008. }
  21009. // stream::Delete tests
  21010. TEST_F(StreamApiTest, Delete) {
  21011. httplib::Client cli(HOST, PORT);
  21012. auto del1 = httplib::stream::Delete(cli, "/resource");
  21013. EXPECT_EQ("Deleted", read_body(del1));
  21014. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21015. EXPECT_EQ("Deleted:data", read_body(del2));
  21016. }
  21017. // stream::Head/Options tests
  21018. TEST_F(StreamApiTest, HeadAndOptions) {
  21019. httplib::Client cli(HOST, PORT);
  21020. auto head = httplib::stream::Head(cli, "/head-test");
  21021. EXPECT_TRUE(head.is_valid());
  21022. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21023. auto opts = httplib::stream::Options(cli, "/options");
  21024. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21025. }
  21026. // SSL stream::* tests
  21027. #ifdef CPPHTTPLIB_SSL_ENABLED
  21028. class SSLStreamApiTest : public ::testing::Test {
  21029. protected:
  21030. void SetUp() override {
  21031. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21032. res.set_content("Hello SSL!", "text/plain");
  21033. });
  21034. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21035. res.set_content(req.body, "text/plain");
  21036. });
  21037. port_ = svr_.bind_to_any_port("127.0.0.1");
  21038. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21039. svr_.wait_until_ready();
  21040. }
  21041. void TearDown() override {
  21042. svr_.stop();
  21043. if (thread_.joinable()) thread_.join();
  21044. }
  21045. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21046. std::thread thread_;
  21047. int port_ = 0;
  21048. };
  21049. TEST_F(SSLStreamApiTest, GetAndPost) {
  21050. httplib::SSLClient cli("127.0.0.1", port_);
  21051. cli.enable_server_certificate_verification(false);
  21052. auto get = httplib::stream::Get(cli, "/hello");
  21053. EXPECT_EQ("Hello SSL!", read_body(get));
  21054. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21055. EXPECT_EQ("test", read_body(post));
  21056. }
  21057. #endif
  21058. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21059. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21060. // BodyReader
  21061. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21062. // Test that read timeout during streaming is detected
  21063. // Use a large content-length response where server delays mid-stream
  21064. Server svr;
  21065. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21066. // Send a large response with delay in the middle
  21067. res.set_content_provider(
  21068. 1000, // content_length
  21069. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21070. if (offset < 100) {
  21071. // Send first 100 bytes immediately
  21072. std::string data(100, 'A');
  21073. sink.write(data.c_str(), data.size());
  21074. return true;
  21075. }
  21076. // Then delay longer than client timeout
  21077. std::this_thread::sleep_for(std::chrono::seconds(3));
  21078. std::string data(900, 'B');
  21079. sink.write(data.c_str(), data.size());
  21080. return true;
  21081. });
  21082. });
  21083. auto port = 8091;
  21084. std::thread t([&]() { svr.listen("localhost", port); });
  21085. svr.wait_until_ready();
  21086. Client cli("localhost", port);
  21087. cli.set_read_timeout(1, 0); // 1 second timeout
  21088. auto handle = cli.open_stream("GET", "/slow-stream");
  21089. ASSERT_TRUE(handle.is_valid());
  21090. char buf[256];
  21091. ssize_t total = 0;
  21092. ssize_t n;
  21093. bool got_error = false;
  21094. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21095. total += n;
  21096. }
  21097. if (n < 0) {
  21098. got_error = true;
  21099. // Should be timeout or read error
  21100. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21101. handle.get_read_error() == Error::Read)
  21102. << "Actual error: " << to_string(handle.get_read_error());
  21103. }
  21104. // Either we got an error, or we got less data than expected
  21105. EXPECT_TRUE(got_error || total < 1000)
  21106. << "Expected timeout but got all " << total << " bytes";
  21107. svr.stop();
  21108. t.join();
  21109. }
  21110. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21111. // Test connection closed detection via BodyReader
  21112. Server svr;
  21113. std::atomic<bool> close_now{false};
  21114. svr.Get("/will-close", [&](const Request &, Response &res) {
  21115. res.set_content_provider(
  21116. 10000, // Large content_length that we won't fully send
  21117. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21118. if (offset < 100) {
  21119. std::string data(100, 'X');
  21120. sink.write(data.c_str(), data.size());
  21121. return true;
  21122. }
  21123. // Wait for signal then abort
  21124. while (!close_now) {
  21125. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21126. }
  21127. return false; // Abort - server will close connection
  21128. });
  21129. });
  21130. auto port = 8092;
  21131. std::thread t([&]() { svr.listen("localhost", port); });
  21132. svr.wait_until_ready();
  21133. Client cli("localhost", port);
  21134. auto handle = cli.open_stream("GET", "/will-close");
  21135. ASSERT_TRUE(handle.is_valid());
  21136. char buf[256];
  21137. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21138. EXPECT_GT(n, 0) << "First read should succeed";
  21139. // Signal server to close
  21140. close_now = true;
  21141. // Keep reading until error or EOF
  21142. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21143. // Keep reading
  21144. }
  21145. // Should get an error since content_length wasn't satisfied
  21146. if (n < 0) {
  21147. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21148. handle.get_read_error() == Error::Read)
  21149. << "Actual error: " << to_string(handle.get_read_error());
  21150. }
  21151. svr.stop();
  21152. t.join();
  21153. }
  21154. #ifdef CPPHTTPLIB_SSL_ENABLED
  21155. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21156. // Test that read timeout during SSL streaming is detected
  21157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21158. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21159. res.set_content_provider(
  21160. 1000, "text/plain",
  21161. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21162. if (offset < 100) {
  21163. std::string data(100, 'A');
  21164. sink.write(data.c_str(), data.size());
  21165. return true;
  21166. }
  21167. std::this_thread::sleep_for(std::chrono::seconds(3));
  21168. std::string data(900, 'B');
  21169. sink.write(data.c_str(), data.size());
  21170. return true;
  21171. });
  21172. });
  21173. auto port = 8093;
  21174. std::thread t([&]() { svr.listen("localhost", port); });
  21175. svr.wait_until_ready();
  21176. SSLClient cli("localhost", port);
  21177. cli.enable_server_certificate_verification(false);
  21178. cli.set_read_timeout(1, 0); // 1 second timeout
  21179. auto handle = cli.open_stream("GET", "/slow-stream");
  21180. ASSERT_TRUE(handle.is_valid());
  21181. char buf[256];
  21182. ssize_t total = 0;
  21183. ssize_t n;
  21184. bool got_error = false;
  21185. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21186. total += n;
  21187. }
  21188. if (n < 0) {
  21189. got_error = true;
  21190. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21191. handle.get_read_error() == Error::Read)
  21192. << "Actual error: " << to_string(handle.get_read_error());
  21193. }
  21194. EXPECT_TRUE(got_error || total < 1000)
  21195. << "Expected timeout but got all " << total << " bytes";
  21196. svr.stop();
  21197. t.join();
  21198. }
  21199. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21200. // Test SSL connection closed detection
  21201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21202. std::atomic<bool> close_now{false};
  21203. svr.Get("/will-close", [&](const Request &, Response &res) {
  21204. res.set_content_provider(
  21205. 10000, "text/plain",
  21206. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21207. if (offset < 100) {
  21208. std::string data(100, 'X');
  21209. sink.write(data.c_str(), data.size());
  21210. return true;
  21211. }
  21212. while (!close_now) {
  21213. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21214. }
  21215. return false;
  21216. });
  21217. });
  21218. auto port = 8094;
  21219. std::thread t([&]() { svr.listen("localhost", port); });
  21220. svr.wait_until_ready();
  21221. SSLClient cli("localhost", port);
  21222. cli.enable_server_certificate_verification(false);
  21223. auto handle = cli.open_stream("GET", "/will-close");
  21224. ASSERT_TRUE(handle.is_valid());
  21225. char buf[256];
  21226. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21227. EXPECT_GT(n, 0);
  21228. // Signal server to close
  21229. close_now = true;
  21230. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21231. // Keep reading
  21232. }
  21233. if (n < 0) {
  21234. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21235. handle.get_read_error() == Error::Read)
  21236. << "Actual error: " << to_string(handle.get_read_error());
  21237. }
  21238. svr.stop();
  21239. t.join();
  21240. }
  21241. #endif
  21242. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21243. using namespace httplib;
  21244. // Create a test file
  21245. const char *fname = "etag_testfile.txt";
  21246. const char *content = "etag-content";
  21247. {
  21248. std::ofstream ofs(fname);
  21249. ofs << content;
  21250. ASSERT_TRUE(ofs.good());
  21251. }
  21252. Server svr;
  21253. svr.set_mount_point("/static", ".");
  21254. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21255. svr.wait_until_ready();
  21256. Client cli(HOST, PORT);
  21257. // First request: should get 200 with ETag header
  21258. auto res1 = cli.Get("/static/etag_testfile.txt");
  21259. ASSERT_TRUE(res1);
  21260. ASSERT_EQ(200, res1->status);
  21261. ASSERT_TRUE(res1->has_header("ETag"));
  21262. std::string etag = res1->get_header_value("ETag");
  21263. EXPECT_FALSE(etag.empty());
  21264. // Verify ETag format: W/"hex-hex"
  21265. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21266. EXPECT_EQ('W', etag[0]);
  21267. EXPECT_EQ('/', etag[1]);
  21268. EXPECT_EQ('"', etag[2]);
  21269. EXPECT_EQ('"', etag.back());
  21270. // Exact match: expect 304 Not Modified
  21271. Headers h2 = {{"If-None-Match", etag}};
  21272. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21273. ASSERT_TRUE(res2);
  21274. EXPECT_EQ(304, res2->status);
  21275. // Wildcard match: expect 304 Not Modified
  21276. Headers h3 = {{"If-None-Match", "*"}};
  21277. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21278. ASSERT_TRUE(res3);
  21279. EXPECT_EQ(304, res3->status);
  21280. // Non-matching ETag: expect 200
  21281. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21282. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21283. ASSERT_TRUE(res4);
  21284. EXPECT_EQ(200, res4->status);
  21285. // Multiple ETags with one matching: expect 304
  21286. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21287. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21288. ASSERT_TRUE(res5);
  21289. EXPECT_EQ(304, res5->status);
  21290. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21291. // that equivalent to the single comma-separated list above, so the match on
  21292. // the second line must still be found.
  21293. Headers h6;
  21294. h6.emplace("If-None-Match", "W/\"other\"");
  21295. h6.emplace("If-None-Match", etag);
  21296. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21297. ASSERT_TRUE(res6);
  21298. EXPECT_EQ(304, res6->status);
  21299. svr.stop();
  21300. t.join();
  21301. std::remove(fname);
  21302. }
  21303. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21304. using namespace httplib;
  21305. Server svr;
  21306. svr.set_mount_point("/static", ".");
  21307. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21308. svr.wait_until_ready();
  21309. Client cli(HOST, PORT);
  21310. // Send If-None-Match: * to a non-existent file
  21311. Headers h = {{"If-None-Match", "*"}};
  21312. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21314. EXPECT_EQ(404, res->status);
  21315. svr.stop();
  21316. t.join();
  21317. }
  21318. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21319. using namespace httplib;
  21320. // Create a test file
  21321. const char *fname = "etag_boundary_testfile.txt";
  21322. const char *content = "boundary-test";
  21323. {
  21324. std::ofstream ofs(fname);
  21325. ofs << content;
  21326. ASSERT_TRUE(ofs.good());
  21327. }
  21328. Server svr;
  21329. svr.set_mount_point("/static", ".");
  21330. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21331. svr.wait_until_ready();
  21332. Client cli(HOST, PORT);
  21333. // Get the actual ETag
  21334. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21335. ASSERT_TRUE(res1);
  21336. ASSERT_EQ(200, res1->status);
  21337. ASSERT_TRUE(res1->has_header("ETag"));
  21338. std::string etag = res1->get_header_value("ETag");
  21339. // Test 1: Very long ETag value (longer than actual ETag)
  21340. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21341. Headers h1 = {{"If-None-Match", "W/"
  21342. "\"very-long-etag-value-that-is-much-longer-"
  21343. "than-the-actual-etag-value\""}};
  21344. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21345. ASSERT_TRUE(res2);
  21346. EXPECT_EQ(200, res2->status); // Should not match
  21347. // Test 2: Long string followed by wildcard
  21348. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21349. // string)
  21350. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21351. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21352. ASSERT_TRUE(res3);
  21353. EXPECT_EQ(304, res3->status); // Should match on "*"
  21354. // Test 3: Wildcard followed by long string
  21355. // Should match on "*" immediately and return 304
  21356. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21357. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21358. ASSERT_TRUE(res4);
  21359. EXPECT_EQ(304, res4->status); // Should match on "*"
  21360. // Test 4: Multiple long non-matching values
  21361. // Should NOT match and return 200 (test that all comparisons are safe)
  21362. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21363. "W/\"second-long-non-matching-value\", "
  21364. "W/\"third-long-non-matching-value\""}};
  21365. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21366. ASSERT_TRUE(res5);
  21367. EXPECT_EQ(200, res5->status); // Should not match
  21368. // Test 5: Single character that is not "*" (edge case)
  21369. Headers h5 = {{"If-None-Match", "X"}};
  21370. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21371. ASSERT_TRUE(res6);
  21372. EXPECT_EQ(200, res6->status); // Should not match
  21373. svr.stop();
  21374. t.join();
  21375. std::remove(fname);
  21376. }
  21377. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21378. using namespace httplib;
  21379. // Create a test file
  21380. const char *fname = "ims_testfile.txt";
  21381. const char *content = "if-modified-since-test";
  21382. {
  21383. std::ofstream ofs(fname);
  21384. ofs << content;
  21385. ASSERT_TRUE(ofs.good());
  21386. }
  21387. Server svr;
  21388. svr.set_mount_point("/static", ".");
  21389. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21390. svr.wait_until_ready();
  21391. Client cli(HOST, PORT);
  21392. // First request: should get 200 with Last-Modified header
  21393. auto res1 = cli.Get("/static/ims_testfile.txt");
  21394. ASSERT_TRUE(res1);
  21395. ASSERT_EQ(200, res1->status);
  21396. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21397. std::string last_modified = res1->get_header_value("Last-Modified");
  21398. EXPECT_FALSE(last_modified.empty());
  21399. // If-Modified-Since with same time: expect 304
  21400. Headers h2 = {{"If-Modified-Since", last_modified}};
  21401. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21402. ASSERT_TRUE(res2);
  21403. EXPECT_EQ(304, res2->status);
  21404. // If-Modified-Since with future time: expect 304
  21405. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21406. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21407. ASSERT_TRUE(res3);
  21408. EXPECT_EQ(304, res3->status);
  21409. // If-Modified-Since with past time: expect 200
  21410. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21411. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21412. ASSERT_TRUE(res4);
  21413. EXPECT_EQ(200, res4->status);
  21414. // If-None-Match takes precedence over If-Modified-Since
  21415. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21416. ASSERT_TRUE(res1->has_header("ETag"));
  21417. std::string etag = res1->get_header_value("ETag");
  21418. Headers h5 = {{"If-None-Match", etag},
  21419. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21420. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21421. ASSERT_TRUE(res5);
  21422. EXPECT_EQ(304, res5->status);
  21423. svr.stop();
  21424. t.join();
  21425. std::remove(fname);
  21426. }
  21427. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21428. using namespace httplib;
  21429. Server svr;
  21430. // Endpoint that returns compressible content
  21431. svr.Get("/compressible", [](const Request &, Response &res) {
  21432. // Return a large enough body to trigger compression
  21433. std::string body(1000, 'a');
  21434. res.set_content(body, "text/plain");
  21435. });
  21436. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21437. svr.wait_until_ready();
  21438. Client cli(HOST, PORT);
  21439. // Request with gzip support: should get Vary header when compressed
  21440. cli.set_compress(true);
  21441. auto res1 = cli.Get("/compressible");
  21442. ASSERT_TRUE(res1);
  21443. EXPECT_EQ(200, res1->status);
  21444. // If Content-Encoding is set, Vary should also be set
  21445. if (res1->has_header("Content-Encoding")) {
  21446. EXPECT_TRUE(res1->has_header("Vary"));
  21447. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21448. }
  21449. // Request without Accept-Encoding header: should not have compression
  21450. Headers h_no_compress;
  21451. auto res2 = cli.Get("/compressible", h_no_compress);
  21452. ASSERT_TRUE(res2);
  21453. EXPECT_EQ(200, res2->status);
  21454. // Verify Vary header is present when compression is applied
  21455. // (the exact behavior depends on server configuration)
  21456. svr.stop();
  21457. t.join();
  21458. }
  21459. TEST(ETagTest, IfRangeWithETag) {
  21460. using namespace httplib;
  21461. // Create a test file with known content
  21462. const char *fname = "if_range_testfile.txt";
  21463. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21464. {
  21465. std::ofstream ofs(fname);
  21466. ofs << content;
  21467. ASSERT_TRUE(ofs.good());
  21468. }
  21469. Server svr;
  21470. svr.set_mount_point("/static", ".");
  21471. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21472. svr.wait_until_ready();
  21473. Client cli(HOST, PORT);
  21474. // First request: get ETag
  21475. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21476. ASSERT_TRUE(res1);
  21477. ASSERT_EQ(200, res1->status);
  21478. ASSERT_TRUE(res1->has_header("ETag"));
  21479. std::string etag = res1->get_header_value("ETag");
  21480. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21481. // Since our server generates weak ETags (W/"..."), If-Range with our
  21482. // ETag should NOT result in partial content - it should return full content.
  21483. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21484. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21485. ASSERT_TRUE(res2);
  21486. // Weak ETag in If-Range -> full content (200), not partial (206)
  21487. EXPECT_EQ(200, res2->status);
  21488. EXPECT_EQ(content, res2->body);
  21489. EXPECT_FALSE(res2->has_header("Content-Range"));
  21490. // Range request with non-matching If-Range (ETag): should get 200 (full
  21491. // content)
  21492. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21493. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21494. ASSERT_TRUE(res3);
  21495. EXPECT_EQ(200, res3->status);
  21496. EXPECT_EQ(content, res3->body);
  21497. EXPECT_FALSE(res3->has_header("Content-Range"));
  21498. // Range request with strong ETag (hypothetical - our server doesn't generate
  21499. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21500. // should return full content)
  21501. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21502. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21503. ASSERT_TRUE(res4);
  21504. EXPECT_EQ(200, res4->status);
  21505. EXPECT_EQ(content, res4->body);
  21506. EXPECT_FALSE(res4->has_header("Content-Range"));
  21507. svr.stop();
  21508. t.join();
  21509. std::remove(fname);
  21510. }
  21511. TEST(ETagTest, IfRangeWithDate) {
  21512. using namespace httplib;
  21513. // Create a test file
  21514. const char *fname = "if_range_date_testfile.txt";
  21515. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21516. {
  21517. std::ofstream ofs(fname);
  21518. ofs << content;
  21519. ASSERT_TRUE(ofs.good());
  21520. }
  21521. Server svr;
  21522. svr.set_mount_point("/static", ".");
  21523. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21524. svr.wait_until_ready();
  21525. Client cli(HOST, PORT);
  21526. // First request: get Last-Modified
  21527. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21528. ASSERT_TRUE(res1);
  21529. ASSERT_EQ(200, res1->status);
  21530. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21531. std::string last_modified = res1->get_header_value("Last-Modified");
  21532. // Range request with matching If-Range (date): should get 206
  21533. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21534. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21535. ASSERT_TRUE(res2);
  21536. EXPECT_EQ(206, res2->status);
  21537. EXPECT_EQ("FGHIJ", res2->body);
  21538. // Range request with old If-Range date: should get 200 (full content)
  21539. Headers h3 = {{"Range", "bytes=5-9"},
  21540. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21541. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21542. ASSERT_TRUE(res3);
  21543. EXPECT_EQ(200, res3->status);
  21544. EXPECT_EQ(content, res3->body);
  21545. // Range request with future If-Range date: should get 206
  21546. Headers h4 = {{"Range", "bytes=0-4"},
  21547. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21548. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21549. ASSERT_TRUE(res4);
  21550. EXPECT_EQ(206, res4->status);
  21551. EXPECT_EQ("ABCDE", res4->body);
  21552. svr.stop();
  21553. t.join();
  21554. std::remove(fname);
  21555. }
  21556. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21557. using namespace httplib;
  21558. const char *fname = "etag_malformed.txt";
  21559. const char *content = "malformed-etag";
  21560. {
  21561. std::ofstream ofs(fname);
  21562. ofs << content;
  21563. ASSERT_TRUE(ofs.good());
  21564. }
  21565. Server svr;
  21566. svr.set_mount_point("/static", ".");
  21567. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21568. svr.wait_until_ready();
  21569. Client cli(HOST, PORT);
  21570. // baseline: should get 200 and an ETag
  21571. auto res1 = cli.Get("/static/etag_malformed.txt");
  21572. ASSERT_TRUE(res1);
  21573. ASSERT_EQ(200, res1->status);
  21574. ASSERT_TRUE(res1->has_header("ETag"));
  21575. // Malformed ETag value (missing quotes) should be treated as non-matching
  21576. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21577. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21578. ASSERT_TRUE(res_bad);
  21579. EXPECT_EQ(200, res_bad->status);
  21580. // Whitespace-only header value should be considered invalid / non-matching
  21581. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21582. "Host: localhost\r\n"
  21583. "If-None-Match: \r\n"
  21584. "Connection: close\r\n"
  21585. "\r\n";
  21586. std::string out;
  21587. ASSERT_TRUE(send_request(5, raw_req, &out));
  21588. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21589. svr.stop();
  21590. t.join();
  21591. std::remove(fname);
  21592. }
  21593. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21594. using namespace httplib;
  21595. const char *fname = "ims_invalid_format.txt";
  21596. const char *content = "ims-bad-format";
  21597. {
  21598. std::ofstream ofs(fname);
  21599. ofs << content;
  21600. ASSERT_TRUE(ofs.good());
  21601. }
  21602. Server svr;
  21603. svr.set_mount_point("/static", ".");
  21604. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21605. svr.wait_until_ready();
  21606. Client cli(HOST, PORT);
  21607. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21608. ASSERT_TRUE(res1);
  21609. ASSERT_EQ(200, res1->status);
  21610. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21611. // If-Modified-Since with invalid format should not result in 304
  21612. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21613. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21614. ASSERT_TRUE(res_bad);
  21615. EXPECT_EQ(200, res_bad->status);
  21616. // If-Range with invalid date format should be treated as mismatch -> full
  21617. // content (200)
  21618. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21619. {"If-Range", "invalid-date"}};
  21620. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21621. ASSERT_TRUE(res_ifrange);
  21622. EXPECT_EQ(200, res_ifrange->status);
  21623. svr.stop();
  21624. t.join();
  21625. std::remove(fname);
  21626. }
  21627. TEST(ETagTest, IfRangeWithMalformedETag) {
  21628. using namespace httplib;
  21629. const char *fname = "ifrange_malformed.txt";
  21630. const std::string content = "0123456789";
  21631. {
  21632. std::ofstream ofs(fname);
  21633. ofs << content;
  21634. ASSERT_TRUE(ofs.good());
  21635. }
  21636. Server svr;
  21637. svr.set_mount_point("/static", ".");
  21638. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21639. svr.wait_until_ready();
  21640. Client cli(HOST, PORT);
  21641. // First request: get ETag
  21642. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21643. ASSERT_TRUE(res1);
  21644. ASSERT_EQ(200, res1->status);
  21645. ASSERT_TRUE(res1->has_header("ETag"));
  21646. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21647. // full content (200)
  21648. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21649. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21650. ASSERT_TRUE(res2);
  21651. EXPECT_EQ(200, res2->status);
  21652. EXPECT_EQ(content, res2->body);
  21653. svr.stop();
  21654. t.join();
  21655. std::remove(fname);
  21656. }
  21657. TEST(ETagTest, ExtremeLargeDateValues) {
  21658. using namespace httplib;
  21659. const char *fname = "ims_extreme_date.txt";
  21660. const char *content = "ims-extreme-date";
  21661. {
  21662. std::ofstream ofs(fname);
  21663. ofs << content;
  21664. ASSERT_TRUE(ofs.good());
  21665. }
  21666. Server svr;
  21667. svr.set_mount_point("/static", ".");
  21668. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21669. svr.wait_until_ready();
  21670. Client cli(HOST, PORT);
  21671. auto res1 = cli.Get(std::string("/static/") + fname);
  21672. ASSERT_TRUE(res1);
  21673. ASSERT_EQ(200, res1->status);
  21674. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21675. // Extremely large year that may overflow date parsing routines.
  21676. Headers h_large_date = {
  21677. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21678. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21679. ASSERT_TRUE(res_bad);
  21680. // Expect server to treat this as invalid/mismatch and return full content
  21681. EXPECT_EQ(200, res_bad->status);
  21682. // If-Range with extremely large date should be treated as mismatch -> full
  21683. // content (200)
  21684. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21685. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21686. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21687. ASSERT_TRUE(res_ifrange);
  21688. EXPECT_EQ(200, res_ifrange->status);
  21689. svr.stop();
  21690. t.join();
  21691. std::remove(fname);
  21692. }
  21693. TEST(ETagTest, NegativeFileModificationTime) {
  21694. using namespace httplib;
  21695. const char *fname = "ims_negative_mtime.txt";
  21696. const std::string content = "negative-mtime";
  21697. {
  21698. std::ofstream ofs(fname);
  21699. ofs << content;
  21700. ASSERT_TRUE(ofs.good());
  21701. }
  21702. // Try to set file mtime to a negative value. This may fail on some
  21703. // platforms/filesystems; if it fails, the test will still verify server
  21704. // behaves safely by performing a regular conditional request.
  21705. #if defined(__APPLE__) || defined(__linux__)
  21706. bool set_negative = false;
  21707. do {
  21708. struct timeval times[2];
  21709. // access time: now
  21710. times[0].tv_sec = time(nullptr);
  21711. times[0].tv_usec = 0;
  21712. // modification time: negative (e.g., -1)
  21713. times[1].tv_sec = -1;
  21714. times[1].tv_usec = 0;
  21715. if (utimes(fname, times) == 0) { set_negative = true; }
  21716. } while (0);
  21717. #else
  21718. bool set_negative = false;
  21719. #endif
  21720. Server svr;
  21721. svr.set_mount_point("/static", ".");
  21722. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21723. svr.wait_until_ready();
  21724. Client cli(HOST, PORT);
  21725. auto res1 = cli.Get(std::string("/static/") + fname);
  21726. ASSERT_TRUE(res1);
  21727. ASSERT_EQ(200, res1->status);
  21728. bool has_last_modified = res1->has_header("Last-Modified");
  21729. std::string last_modified;
  21730. if (has_last_modified) {
  21731. last_modified = res1->get_header_value("Last-Modified");
  21732. }
  21733. if (set_negative) {
  21734. // If we successfully set a negative mtime, ensure server returns a
  21735. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21736. // with an old date and ensure server handles it without crash.
  21737. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21738. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21739. ASSERT_TRUE(res2);
  21740. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21741. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21742. } else {
  21743. // Could not set negative mtime on this platform; fall back to verifying
  21744. // that normal invalid/malformed dates are treated safely (non-304).
  21745. Headers h_bad_date = {
  21746. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21747. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21748. ASSERT_TRUE(res_bad);
  21749. EXPECT_EQ(200, res_bad->status);
  21750. }
  21751. svr.stop();
  21752. t.join();
  21753. std::remove(fname);
  21754. }
  21755. //==============================================================================
  21756. // Integration Tests with Server
  21757. //==============================================================================
  21758. class SSEIntegrationTest : public ::testing::Test {
  21759. protected:
  21760. void SetUp() override {
  21761. stop_server_.store(false);
  21762. events_.clear();
  21763. server_ = httplib::detail::make_unique<Server>();
  21764. setup_server();
  21765. start_server();
  21766. }
  21767. void TearDown() override {
  21768. stop_server_.store(true);
  21769. event_cv_.notify_all();
  21770. server_->stop();
  21771. if (server_thread_.joinable()) { server_thread_.join(); }
  21772. }
  21773. void setup_server() {
  21774. // Simple SSE endpoint
  21775. server_->Get("/events", [this](const Request &req, Response &res) {
  21776. auto last_id = req.get_header_value("Last-Event-ID");
  21777. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21778. res.set_chunked_content_provider(
  21779. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21780. std::unique_lock<std::mutex> lock(event_mutex_);
  21781. if (event_cv_.wait_for(
  21782. lock, std::chrono::milliseconds(200), [this] {
  21783. return !events_.empty() || stop_server_.load();
  21784. })) {
  21785. if (stop_server_.load()) { return false; }
  21786. if (!events_.empty()) {
  21787. std::string event = events_.front();
  21788. events_.erase(events_.begin());
  21789. sink.write(event.data(), event.size());
  21790. return true;
  21791. }
  21792. }
  21793. return !stop_server_.load();
  21794. });
  21795. });
  21796. // Endpoint that returns error
  21797. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21798. res.status = 500;
  21799. res.set_content("Internal Server Error", "text/plain");
  21800. });
  21801. // Endpoint for custom event types
  21802. server_->Get("/custom-events", [](const Request &, Response &res) {
  21803. res.set_chunked_content_provider(
  21804. "text/event-stream", [](size_t offset, DataSink &sink) {
  21805. if (offset == 0) {
  21806. std::string event = "event: update\ndata: updated\n\n"
  21807. "event: delete\ndata: deleted\n\n";
  21808. sink.write(event.data(), event.size());
  21809. }
  21810. return false; // End stream after sending
  21811. });
  21812. });
  21813. }
  21814. void start_server() {
  21815. port_ = server_->bind_to_any_port(HOST);
  21816. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21817. // Wait for server to start
  21818. while (!server_->is_running()) {
  21819. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21820. }
  21821. }
  21822. int get_port() const { return port_; }
  21823. void send_event(const std::string &event) {
  21824. std::lock_guard<std::mutex> lock(event_mutex_);
  21825. events_.push_back(event);
  21826. event_cv_.notify_all();
  21827. }
  21828. std::unique_ptr<Server> server_;
  21829. std::thread server_thread_;
  21830. std::mutex event_mutex_;
  21831. std::condition_variable event_cv_;
  21832. std::vector<std::string> events_;
  21833. std::atomic<bool> stop_server_{false};
  21834. std::string last_received_event_id_;
  21835. int port_ = 0;
  21836. };
  21837. //==============================================================================
  21838. // SSE Parsing Tests
  21839. //==============================================================================
  21840. class SSEParsingTest : public SSEIntegrationTest {
  21841. protected:
  21842. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21843. // A trailing sentinel event tells when the whole stream has been parsed.
  21844. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21845. auto body = stream + "event: end\ndata: end\n\n";
  21846. server_->Get("/parse", [body](const Request &, Response &res) {
  21847. res.set_content(body, "text/event-stream");
  21848. });
  21849. return collect("/parse");
  21850. }
  21851. // Runs SSEClient against path until an "end" event arrives and returns the
  21852. // messages dispatched before it
  21853. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21854. Client client(HOST, get_port());
  21855. sse::SSEClient sse(client, path);
  21856. std::mutex mutex;
  21857. std::condition_variable cv;
  21858. std::vector<sse::SSEMessage> messages;
  21859. auto done = false;
  21860. sse.on_message([&](const sse::SSEMessage &msg) {
  21861. std::lock_guard<std::mutex> lock(mutex);
  21862. // Ignore a replay from a reconnect that races with stop()
  21863. if (!done) { messages.push_back(msg); }
  21864. });
  21865. sse.on_event("end", [&](const sse::SSEMessage &) {
  21866. std::lock_guard<std::mutex> lock(mutex);
  21867. done = true;
  21868. cv.notify_all();
  21869. });
  21870. sse.set_reconnect_interval(100);
  21871. sse.start_async();
  21872. {
  21873. std::unique_lock<std::mutex> lock(mutex);
  21874. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21875. }
  21876. sse.stop();
  21877. EXPECT_TRUE(done);
  21878. return messages;
  21879. }
  21880. };
  21881. TEST_F(SSEParsingTest, SingleLineData) {
  21882. auto msgs = parse("data: hello\n\n");
  21883. ASSERT_EQ(msgs.size(), 1u);
  21884. EXPECT_EQ(msgs[0].data, "hello");
  21885. EXPECT_EQ(msgs[0].event, "message");
  21886. }
  21887. TEST_F(SSEParsingTest, MultiLineData) {
  21888. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21889. ASSERT_EQ(msgs.size(), 1u);
  21890. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21891. }
  21892. TEST_F(SSEParsingTest, CustomEventType) {
  21893. auto msgs = parse("event: update\ndata: payload\n\n");
  21894. ASSERT_EQ(msgs.size(), 1u);
  21895. EXPECT_EQ(msgs[0].event, "update");
  21896. EXPECT_EQ(msgs[0].data, "payload");
  21897. }
  21898. TEST_F(SSEParsingTest, EventIdHandling) {
  21899. auto msgs = parse("id: 12345\ndata: test\n\n");
  21900. ASSERT_EQ(msgs.size(), 1u);
  21901. EXPECT_EQ(msgs[0].id, "12345");
  21902. }
  21903. TEST_F(SSEParsingTest, EmptyEventId) {
  21904. auto msgs = parse("id:\ndata: test\n\n");
  21905. ASSERT_EQ(msgs.size(), 1u);
  21906. EXPECT_EQ(msgs[0].id, "");
  21907. }
  21908. TEST_F(SSEParsingTest, CommentsIgnored) {
  21909. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21910. ASSERT_EQ(msgs.size(), 1u);
  21911. EXPECT_EQ(msgs[0].data, "hello");
  21912. EXPECT_EQ(msgs[0].event, "message");
  21913. }
  21914. TEST_F(SSEParsingTest, ColonInValue) {
  21915. auto msgs = parse("data: hello:world:test\n\n");
  21916. ASSERT_EQ(msgs.size(), 1u);
  21917. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21918. }
  21919. TEST_F(SSEParsingTest, FieldNameOnly) {
  21920. // A line without a colon is a field name with an empty value
  21921. auto msgs = parse("data\n\n");
  21922. ASSERT_EQ(msgs.size(), 1u);
  21923. EXPECT_EQ(msgs[0].data, "");
  21924. }
  21925. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21926. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21927. ASSERT_EQ(msgs.size(), 1u);
  21928. EXPECT_EQ(msgs[0].event, "update");
  21929. EXPECT_EQ(msgs[0].data, "hello");
  21930. }
  21931. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21932. auto msgs = parse("data\r\n\r\n");
  21933. ASSERT_EQ(msgs.size(), 1u);
  21934. EXPECT_EQ(msgs[0].data, "");
  21935. }
  21936. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21937. auto msgs = parse("event: update\rdata: hello\r\r");
  21938. ASSERT_EQ(msgs.size(), 1u);
  21939. EXPECT_EQ(msgs[0].event, "update");
  21940. EXPECT_EQ(msgs[0].data, "hello");
  21941. }
  21942. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21943. // Chunk boundaries fall inside every \r\n and right before the first one
  21944. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21945. "\n\r", "\nevent: end\ndata: end\n\n"};
  21946. server_->Get("/split", [chunks](const Request &, Response &res) {
  21947. auto i = std::make_shared<size_t>(0);
  21948. res.set_chunked_content_provider(
  21949. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21950. if (*i == chunks.size()) {
  21951. sink.done();
  21952. } else {
  21953. sink.write(chunks[*i].data(), chunks[*i].size());
  21954. (*i)++;
  21955. }
  21956. return true;
  21957. });
  21958. });
  21959. auto msgs = collect("/split");
  21960. ASSERT_EQ(msgs.size(), 1u);
  21961. EXPECT_EQ(msgs[0].event, "update");
  21962. EXPECT_EQ(msgs[0].data, "hello");
  21963. }
  21964. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21965. // Only a BOM at the start of the stream is ignored
  21966. auto msgs = parse("\xEF\xBB\xBF"
  21967. "data: first\n\n"
  21968. "\xEF\xBB\xBF"
  21969. "data: second\n\n");
  21970. ASSERT_EQ(msgs.size(), 1u);
  21971. EXPECT_EQ(msgs[0].data, "first");
  21972. }
  21973. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21974. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21975. ASSERT_EQ(msgs.size(), 1u);
  21976. EXPECT_EQ(msgs[0].data, "hello");
  21977. EXPECT_EQ(msgs[0].event, "message");
  21978. }
  21979. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21980. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21981. ASSERT_EQ(msgs.size(), 2u);
  21982. EXPECT_EQ(msgs[0].data, "hello");
  21983. EXPECT_EQ(msgs[1].data, "hello");
  21984. }
  21985. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21986. // An event without data is not dispatched, and its type must not leak
  21987. // into the next event
  21988. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21989. ASSERT_EQ(msgs.size(), 1u);
  21990. EXPECT_EQ(msgs[0].event, "message");
  21991. EXPECT_EQ(msgs[0].data, "hello");
  21992. }
  21993. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21994. // Also when the empty field replaces an earlier type
  21995. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21996. ASSERT_EQ(msgs.size(), 2u);
  21997. EXPECT_EQ(msgs[0].event, "message");
  21998. EXPECT_EQ(msgs[1].event, "message");
  21999. }
  22000. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22001. // The first connection sends only an id; the second echoes back the
  22002. // Last-Event-ID it was reconnected with
  22003. std::atomic<int> connection_count{0};
  22004. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22005. if (connection_count++ == 0) {
  22006. res.set_content("id: 42\n\n", "text/event-stream");
  22007. } else {
  22008. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22009. "\n\nevent: end\ndata: end\n\n",
  22010. "text/event-stream");
  22011. }
  22012. });
  22013. auto msgs = collect("/id-only");
  22014. ASSERT_EQ(msgs.size(), 1u);
  22015. EXPECT_EQ(msgs[0].data, "42");
  22016. }
  22017. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22018. // The first connection sets an id and then clears it with an empty one; the
  22019. // second reports whether it was reconnected with a Last-Event-ID
  22020. std::atomic<int> connection_count{0};
  22021. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22022. if (connection_count++ == 0) {
  22023. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22024. "text/event-stream");
  22025. } else {
  22026. res.set_content(
  22027. std::string("data: ") +
  22028. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22029. "\n\nevent: end\ndata: end\n\n",
  22030. "text/event-stream");
  22031. }
  22032. });
  22033. auto msgs = collect("/id-clear");
  22034. ASSERT_EQ(msgs.size(), 3u);
  22035. EXPECT_EQ(msgs[0].id, "1");
  22036. EXPECT_EQ(msgs[1].id, "");
  22037. EXPECT_EQ(msgs[2].data, "not sent");
  22038. }
  22039. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22040. // The first connection sets an id and then sends ids that cannot be carried
  22041. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22042. // with
  22043. std::atomic<int> connection_count{0};
  22044. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22045. if (connection_count++ == 0) {
  22046. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22047. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22048. "text/event-stream");
  22049. } else {
  22050. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22051. "\n\nevent: end\ndata: end\n\n",
  22052. "text/event-stream");
  22053. }
  22054. });
  22055. auto msgs = collect("/id-unsendable");
  22056. ASSERT_EQ(msgs.size(), 1u);
  22057. EXPECT_EQ(msgs[0].data, "42");
  22058. }
  22059. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22060. auto msgs = parse("event: notification\nid: evt-42\n"
  22061. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22062. ASSERT_EQ(msgs.size(), 1u);
  22063. EXPECT_EQ(msgs[0].event, "notification");
  22064. EXPECT_EQ(msgs[0].id, "evt-42");
  22065. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22066. }
  22067. TEST(SSEMessageTest, Clear) {
  22068. sse::SSEMessage msg;
  22069. msg.event = "custom";
  22070. msg.data = "some data";
  22071. msg.id = "123";
  22072. msg.clear();
  22073. EXPECT_EQ(msg.event, "message");
  22074. EXPECT_EQ(msg.data, "");
  22075. EXPECT_EQ(msg.id, "");
  22076. }
  22077. //==============================================================================
  22078. // SSE Integration Tests
  22079. //==============================================================================
  22080. // Test: Successful connection and on_open callback
  22081. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22082. // Add a simple endpoint that sends one event and closes
  22083. server_->Get("/simple-event", [](const Request &, Response &res) {
  22084. res.set_chunked_content_provider(
  22085. "text/event-stream", [](size_t offset, DataSink &sink) {
  22086. if (offset == 0) {
  22087. std::string event = "data: hello\n\n";
  22088. sink.write(event.data(), event.size());
  22089. }
  22090. return false; // Close stream after sending
  22091. });
  22092. });
  22093. Client client("localhost", get_port());
  22094. sse::SSEClient sse(client, "/simple-event");
  22095. std::atomic<bool> open_called{false};
  22096. std::atomic<bool> message_received{false};
  22097. sse.on_open([&open_called]() { open_called.store(true); });
  22098. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22099. if (msg.data == "hello") { message_received.store(true); }
  22100. });
  22101. sse.set_reconnect_interval(100);
  22102. sse.set_max_reconnect_attempts(1);
  22103. // Start async
  22104. sse.start_async();
  22105. // Wait for message to be processed
  22106. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22107. sse.stop();
  22108. EXPECT_TRUE(open_called.load());
  22109. EXPECT_TRUE(message_received.load());
  22110. }
  22111. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22112. // A data line that never ends.
  22113. server_->Get("/endless-line", [](const Request &, Response &res) {
  22114. res.set_chunked_content_provider(
  22115. "text/event-stream", [](size_t offset, DataSink &sink) {
  22116. if (offset == 0) { sink.write("data: ", 6); }
  22117. std::string chunk(64 * 1024, 'A');
  22118. return sink.write(chunk.data(), chunk.size());
  22119. });
  22120. });
  22121. Client client("localhost", get_port());
  22122. sse::SSEClient sse(client, "/endless-line");
  22123. std::atomic<bool> too_long{false};
  22124. sse.on_error([&](Error err) {
  22125. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22126. });
  22127. sse.set_max_reconnect_attempts(1);
  22128. sse.start_async();
  22129. for (int i = 0; i < 500 && !too_long; i++) {
  22130. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22131. }
  22132. sse.stop();
  22133. EXPECT_TRUE(too_long);
  22134. }
  22135. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22136. // Far more in all than the client's payload limit below.
  22137. server_->Get("/many-events", [](const Request &, Response &res) {
  22138. res.set_chunked_content_provider(
  22139. "text/event-stream", [](size_t offset, DataSink &sink) {
  22140. if (offset == 0) {
  22141. std::string events;
  22142. for (int i = 0; i < 1000; i++) {
  22143. events += "data: message\n\n";
  22144. }
  22145. sink.write(events.data(), events.size());
  22146. }
  22147. return false;
  22148. });
  22149. });
  22150. Client client("localhost", get_port());
  22151. client.set_payload_max_length(1024);
  22152. sse::SSEClient sse(client, "/many-events");
  22153. std::atomic<int> messages{0};
  22154. std::atomic<bool> too_large{false};
  22155. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22156. sse.on_error([&](Error err) {
  22157. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22158. });
  22159. sse.set_max_reconnect_attempts(1);
  22160. sse.start_async();
  22161. for (int i = 0; i < 500 && messages < 1000; i++) {
  22162. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22163. }
  22164. sse.stop();
  22165. EXPECT_GE(messages.load(), 1000);
  22166. EXPECT_FALSE(too_large);
  22167. }
  22168. // Test: on_message callback
  22169. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22170. // Endpoint that sends multiple events then closes
  22171. server_->Get("/multi-event", [](const Request &, Response &res) {
  22172. res.set_chunked_content_provider(
  22173. "text/event-stream", [](size_t offset, DataSink &sink) {
  22174. if (offset == 0) {
  22175. std::string events = "data: message1\n\ndata: message2\n\n";
  22176. sink.write(events.data(), events.size());
  22177. }
  22178. return false;
  22179. });
  22180. });
  22181. Client client("localhost", get_port());
  22182. sse::SSEClient sse(client, "/multi-event");
  22183. std::vector<std::string> received_messages;
  22184. std::mutex messages_mutex;
  22185. sse.on_message([&](const sse::SSEMessage &msg) {
  22186. std::lock_guard<std::mutex> lock(messages_mutex);
  22187. received_messages.push_back(msg.data);
  22188. });
  22189. sse.set_reconnect_interval(100);
  22190. sse.set_max_reconnect_attempts(1);
  22191. sse.start_async();
  22192. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22193. sse.stop();
  22194. std::lock_guard<std::mutex> lock(messages_mutex);
  22195. EXPECT_GE(received_messages.size(), 2u);
  22196. if (received_messages.size() >= 2) {
  22197. EXPECT_EQ(received_messages[0], "message1");
  22198. EXPECT_EQ(received_messages[1], "message2");
  22199. }
  22200. }
  22201. // Test: on_event for specific types
  22202. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22203. Client client("localhost", get_port());
  22204. sse::SSEClient sse(client, "/custom-events");
  22205. std::atomic<bool> update_received{false};
  22206. std::atomic<bool> delete_received{false};
  22207. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22208. if (msg.data == "updated") { update_received.store(true); }
  22209. });
  22210. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22211. if (msg.data == "deleted") { delete_received.store(true); }
  22212. });
  22213. sse.set_max_reconnect_attempts(1);
  22214. sse.start_async();
  22215. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22216. sse.stop();
  22217. EXPECT_TRUE(update_received.load());
  22218. EXPECT_TRUE(delete_received.load());
  22219. }
  22220. // Test: on_error callback on connection failure
  22221. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22222. // Connect to a non-existent port
  22223. Client client("localhost", 59999);
  22224. sse::SSEClient sse(client, "/events");
  22225. std::atomic<bool> error_called{false};
  22226. Error received_error = Error::Success;
  22227. sse.on_error([&](Error err) {
  22228. error_called.store(true);
  22229. received_error = err;
  22230. });
  22231. sse.set_reconnect_interval(50);
  22232. sse.set_max_reconnect_attempts(1);
  22233. sse.start_async();
  22234. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22235. sse.stop();
  22236. EXPECT_TRUE(error_called.load());
  22237. EXPECT_NE(received_error, Error::Success);
  22238. }
  22239. // Test: Last-Event-ID header sent on reconnect
  22240. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22241. // Endpoint that sends event with ID
  22242. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22243. res.set_chunked_content_provider(
  22244. "text/event-stream", [](size_t offset, DataSink &sink) {
  22245. if (offset == 0) {
  22246. std::string event = "id: evt-123\ndata: test\n\n";
  22247. sink.write(event.data(), event.size());
  22248. }
  22249. return false;
  22250. });
  22251. });
  22252. Client client("localhost", get_port());
  22253. sse::SSEClient sse(client, "/event-with-id");
  22254. std::atomic<bool> id_received{false};
  22255. sse.on_message([&](const sse::SSEMessage &msg) {
  22256. if (!msg.id.empty()) { id_received.store(true); }
  22257. });
  22258. sse.set_reconnect_interval(100);
  22259. sse.set_max_reconnect_attempts(1);
  22260. sse.start_async();
  22261. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22262. sse.stop();
  22263. EXPECT_TRUE(id_received.load());
  22264. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22265. }
  22266. // Test: Manual stop
  22267. TEST_F(SSEIntegrationTest, ManualStop) {
  22268. // Endpoint that sends one event and stays open briefly. The server outlives
  22269. // this test body, so the provider uses the fixture's flag, not a local.
  22270. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22271. res.set_chunked_content_provider(
  22272. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22273. if (offset == 0) {
  22274. std::string event = "data: connected\n\n";
  22275. sink.write(event.data(), event.size());
  22276. }
  22277. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22278. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22279. }
  22280. return false;
  22281. });
  22282. });
  22283. Client client("localhost", get_port());
  22284. sse::SSEClient sse(client, "/stay-open");
  22285. std::atomic<bool> connected{false};
  22286. sse.on_open([&connected]() { connected.store(true); });
  22287. sse.set_reconnect_interval(100);
  22288. sse.set_max_reconnect_attempts(1);
  22289. sse.start_async();
  22290. // Wait for connection to establish
  22291. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22292. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22293. }
  22294. EXPECT_TRUE(connected.load());
  22295. EXPECT_TRUE(sse.is_connected());
  22296. // Signal handler to stop
  22297. stop_server_.store(true);
  22298. // Stop SSE client
  22299. sse.stop();
  22300. EXPECT_FALSE(sse.is_connected());
  22301. }
  22302. // Sends one event, then nothing until stop is set
  22303. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22304. return [&stop](const Request &, Response &res) {
  22305. res.set_chunked_content_provider(
  22306. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22307. if (offset == 0) {
  22308. std::string event = "data: hello\n\n";
  22309. sink.write(event.data(), event.size());
  22310. }
  22311. while (!stop.load()) {
  22312. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22313. }
  22314. return false;
  22315. });
  22316. };
  22317. }
  22318. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22319. static void check_stop_interrupts_blocked_read(Client &client) {
  22320. client.set_read_timeout(30, 0);
  22321. for (auto by_destructor : {false, true}) {
  22322. std::atomic<bool> received{false};
  22323. std::chrono::steady_clock::time_point start;
  22324. {
  22325. sse::SSEClient sse(client, "/idle-stream");
  22326. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22327. sse.start_async();
  22328. for (int i = 0; i < 500 && !received.load(); ++i) {
  22329. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22330. }
  22331. ASSERT_TRUE(received.load());
  22332. // Let the client block in the next read
  22333. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22334. start = std::chrono::steady_clock::now();
  22335. if (!by_destructor) { sse.stop(); }
  22336. }
  22337. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22338. std::chrono::seconds(2));
  22339. }
  22340. }
  22341. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22342. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22343. Client client("localhost", get_port());
  22344. check_stop_interrupts_blocked_read(client);
  22345. }
  22346. #ifdef CPPHTTPLIB_SSL_ENABLED
  22347. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22349. std::atomic<bool> done{false};
  22350. svr.Get("/idle-stream", idle_event_stream(done));
  22351. auto port = svr.bind_to_any_port(HOST);
  22352. std::thread t([&] { svr.listen_after_bind(); });
  22353. auto se = detail::scope_exit([&] {
  22354. done.store(true);
  22355. svr.stop();
  22356. t.join();
  22357. });
  22358. svr.wait_until_ready();
  22359. Client client("https://localhost:" + std::to_string(port));
  22360. client.enable_server_certificate_verification(false);
  22361. check_stop_interrupts_blocked_read(client);
  22362. }
  22363. #endif
  22364. // Test: SSEClient with custom headers
  22365. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22366. // Setup a server endpoint that checks for custom header
  22367. std::atomic<bool> header_received{false};
  22368. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22369. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22370. header_received.store(true);
  22371. }
  22372. res.set_chunked_content_provider("text/event-stream",
  22373. [](size_t, DataSink &) { return false; });
  22374. });
  22375. Client client("localhost", get_port());
  22376. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22377. sse::SSEClient sse(client, "/header-check", headers);
  22378. sse.set_max_reconnect_attempts(1);
  22379. sse.start_async();
  22380. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22381. sse.stop();
  22382. EXPECT_TRUE(header_received.load());
  22383. }
  22384. // Test: Reconnect interval configuration
  22385. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22386. Client client("localhost", get_port());
  22387. sse::SSEClient sse(client, "/events");
  22388. auto &result = sse.set_reconnect_interval(500);
  22389. // Builder pattern should return reference to self
  22390. EXPECT_EQ(&result, &sse);
  22391. }
  22392. // Test: Max reconnect attempts
  22393. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22394. // Connect to non-existent port to force reconnects
  22395. Client client("localhost", 59998);
  22396. sse::SSEClient sse(client, "/events");
  22397. std::atomic<int> error_count{0};
  22398. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22399. sse.set_reconnect_interval(50);
  22400. sse.set_max_reconnect_attempts(2);
  22401. auto start = std::chrono::steady_clock::now();
  22402. sse.start(); // Blocking call
  22403. auto end = std::chrono::steady_clock::now();
  22404. // Should have stopped after 2 failed attempts
  22405. EXPECT_GE(error_count.load(), 2);
  22406. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22407. auto duration =
  22408. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22409. #ifdef _WIN32
  22410. // Windows is much slower for socket connection failures
  22411. EXPECT_LT(duration.count(), 7000);
  22412. #else
  22413. EXPECT_LT(duration.count(), 1000);
  22414. #endif
  22415. }
  22416. // Test: Multi-line data in integration
  22417. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22418. // Endpoint with multi-line data
  22419. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22420. res.set_chunked_content_provider(
  22421. "text/event-stream", [](size_t offset, DataSink &sink) {
  22422. if (offset == 0) {
  22423. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22424. sink.write(event.data(), event.size());
  22425. }
  22426. return false;
  22427. });
  22428. });
  22429. Client client("localhost", get_port());
  22430. sse::SSEClient sse(client, "/multiline-data");
  22431. std::string received_data;
  22432. std::mutex data_mutex;
  22433. sse.on_message([&](const sse::SSEMessage &msg) {
  22434. std::lock_guard<std::mutex> lock(data_mutex);
  22435. received_data = msg.data;
  22436. });
  22437. sse.set_reconnect_interval(100);
  22438. sse.set_max_reconnect_attempts(1);
  22439. sse.start_async();
  22440. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22441. sse.stop();
  22442. std::lock_guard<std::mutex> lock(data_mutex);
  22443. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22444. }
  22445. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22446. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22447. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22448. DataSink &sink) {
  22449. if (offset == 0) {
  22450. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22451. sink.write(events.data(), events.size());
  22452. }
  22453. return false;
  22454. });
  22455. });
  22456. Client client("localhost", get_port());
  22457. sse::SSEClient sse(client, "/empty-data-lines");
  22458. std::mutex mutex;
  22459. std::condition_variable cv;
  22460. std::vector<std::string> received;
  22461. sse.on_message([&](const sse::SSEMessage &msg) {
  22462. std::lock_guard<std::mutex> lock(mutex);
  22463. received.push_back(msg.data);
  22464. cv.notify_all();
  22465. });
  22466. sse.set_max_reconnect_attempts(1);
  22467. sse.start_async();
  22468. {
  22469. std::unique_lock<std::mutex> lock(mutex);
  22470. cv.wait_for(lock, std::chrono::seconds(2),
  22471. [&] { return received.size() >= 3; });
  22472. }
  22473. sse.stop();
  22474. ASSERT_GE(received.size(), 3u);
  22475. EXPECT_EQ(received[0], "");
  22476. EXPECT_EQ(received[1], "\nhello");
  22477. EXPECT_EQ(received[2], "");
  22478. }
  22479. // Test: Auto-reconnect after server disconnection
  22480. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22481. std::atomic<int> connection_count{0};
  22482. std::atomic<int> message_count{0};
  22483. // Endpoint that sends one event and closes, forcing reconnect
  22484. server_->Get("/reconnect-test",
  22485. [&connection_count](const Request &, Response &res) {
  22486. connection_count.fetch_add(1);
  22487. res.set_chunked_content_provider(
  22488. "text/event-stream", [](size_t offset, DataSink &sink) {
  22489. if (offset == 0) {
  22490. std::string event = "data: hello\n\n";
  22491. sink.write(event.data(), event.size());
  22492. }
  22493. return false; // Close connection after sending
  22494. });
  22495. });
  22496. Client client("localhost", get_port());
  22497. sse::SSEClient sse(client, "/reconnect-test");
  22498. sse.on_message([&message_count](const sse::SSEMessage &) {
  22499. message_count.fetch_add(1);
  22500. });
  22501. sse.set_reconnect_interval(100);
  22502. sse.set_max_reconnect_attempts(3);
  22503. sse.start_async();
  22504. // Wait long enough for multiple reconnects
  22505. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22506. sse.stop();
  22507. // Should have connected multiple times (initial + reconnects)
  22508. EXPECT_GE(connection_count.load(), 2);
  22509. // Should have received messages from multiple connections
  22510. EXPECT_GE(message_count.load(), 2);
  22511. }
  22512. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22513. std::atomic<int> connection_count{0};
  22514. // Neither Content-Length nor chunked: the close ends the stream
  22515. server_->Get("/close-delimited",
  22516. [&connection_count](const Request &, Response &res) {
  22517. connection_count.fetch_add(1);
  22518. res.set_content_provider(
  22519. "text/event-stream", [](size_t offset, DataSink &sink) {
  22520. if (offset == 0) {
  22521. std::string event = "data: hello\n\n";
  22522. sink.write(event.data(), event.size());
  22523. } else {
  22524. sink.done();
  22525. }
  22526. return true;
  22527. });
  22528. });
  22529. Client client("localhost", get_port());
  22530. sse::SSEClient sse(client, "/close-delimited");
  22531. std::atomic<int> error_count{0};
  22532. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22533. sse.set_reconnect_interval(100);
  22534. sse.start_async();
  22535. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22536. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22537. }
  22538. sse.stop();
  22539. // Reconnects as after any end of the stream, but reports no error
  22540. EXPECT_GE(connection_count.load(), 2);
  22541. EXPECT_EQ(0, error_count.load());
  22542. }
  22543. // Test: A retry field that is not all ASCII digits is ignored
  22544. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22545. std::atomic<int> connection_count{0};
  22546. server_->Get("/bad-retry",
  22547. [&connection_count](const Request &, Response &res) {
  22548. connection_count.fetch_add(1);
  22549. res.set_chunked_content_provider(
  22550. "text/event-stream", [](size_t offset, DataSink &sink) {
  22551. if (offset == 0) {
  22552. std::string event = "retry: -1\ndata: hello\n\n";
  22553. sink.write(event.data(), event.size());
  22554. }
  22555. return false;
  22556. });
  22557. });
  22558. Client client("localhost", get_port());
  22559. sse::SSEClient sse(client, "/bad-retry");
  22560. sse.set_reconnect_interval(10000);
  22561. sse.start_async();
  22562. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22563. sse.stop();
  22564. EXPECT_EQ(connection_count.load(), 1);
  22565. }
  22566. // Test: A retry field of all ASCII digits sets the reconnection time
  22567. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22568. std::mutex mutex;
  22569. std::condition_variable cv;
  22570. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22571. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22572. {
  22573. std::lock_guard<std::mutex> lock(mutex);
  22574. connected_at.push_back(std::chrono::steady_clock::now());
  22575. cv.notify_all();
  22576. }
  22577. res.set_chunked_content_provider(
  22578. "text/event-stream", [](size_t offset, DataSink &sink) {
  22579. if (offset == 0) {
  22580. std::string event = "retry: 0\ndata: hello\n\n";
  22581. sink.write(event.data(), event.size());
  22582. }
  22583. return false;
  22584. });
  22585. });
  22586. Client client("localhost", get_port());
  22587. sse::SSEClient sse(client, "/zero-retry");
  22588. sse.set_reconnect_interval(10000);
  22589. sse.start_async();
  22590. {
  22591. std::unique_lock<std::mutex> lock(mutex);
  22592. cv.wait_for(lock, std::chrono::seconds(5),
  22593. [&] { return connected_at.size() >= 2; });
  22594. }
  22595. sse.stop();
  22596. // The server-supplied interval is applied, but never below 100ms, so
  22597. // "retry: 0" does not cause a busy reconnect loop
  22598. std::lock_guard<std::mutex> lock(mutex);
  22599. ASSERT_GE(connected_at.size(), 2u);
  22600. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22601. connected_at[1] - connected_at[0])
  22602. .count();
  22603. EXPECT_GE(interval_ms, 100);
  22604. }
  22605. // Test: Last-Event-ID sent on reconnect
  22606. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22607. std::atomic<int> connection_count{0};
  22608. std::vector<std::string> received_last_event_ids;
  22609. std::mutex id_mutex;
  22610. // Endpoint that checks Last-Event-ID header and sends event with ID
  22611. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22612. int conn = connection_count.fetch_add(1);
  22613. // Capture the Last-Event-ID header from each connection
  22614. {
  22615. std::lock_guard<std::mutex> lock(id_mutex);
  22616. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22617. }
  22618. res.set_chunked_content_provider(
  22619. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22620. if (offset == 0) {
  22621. std::string event =
  22622. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22623. sink.write(event.data(), event.size());
  22624. }
  22625. return false;
  22626. });
  22627. });
  22628. Client client("localhost", get_port());
  22629. sse::SSEClient sse(client, "/reconnect-with-id");
  22630. sse.set_reconnect_interval(100);
  22631. sse.set_max_reconnect_attempts(3);
  22632. sse.start_async();
  22633. // Wait for at least 2 connections
  22634. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22635. sse.stop();
  22636. // Verify behavior
  22637. std::lock_guard<std::mutex> lock(id_mutex);
  22638. EXPECT_GE(received_last_event_ids.size(), 2u);
  22639. // First connection should have no Last-Event-ID
  22640. if (!received_last_event_ids.empty()) {
  22641. EXPECT_EQ(received_last_event_ids[0], "");
  22642. }
  22643. // Second connection should have Last-Event-ID from first connection
  22644. if (received_last_event_ids.size() >= 2) {
  22645. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22646. }
  22647. }
  22648. // Test: set_headers updates headers used on reconnect
  22649. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22650. std::vector<std::string> received_tokens;
  22651. std::mutex token_mutex;
  22652. // Endpoint that captures Authorization header
  22653. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22654. {
  22655. std::lock_guard<std::mutex> lock(token_mutex);
  22656. received_tokens.push_back(req.get_header_value("Authorization"));
  22657. }
  22658. res.set_chunked_content_provider(
  22659. "text/event-stream", [](size_t offset, DataSink &sink) {
  22660. if (offset == 0) {
  22661. std::string event = "data: hello\n\n";
  22662. sink.write(event.data(), event.size());
  22663. }
  22664. return false; // Close connection to trigger reconnect
  22665. });
  22666. });
  22667. Client client("localhost", get_port());
  22668. Headers headers = {{"Authorization", "Bearer old-token"}};
  22669. sse::SSEClient sse(client, "/auth-check", headers);
  22670. // Update headers on each successful connection
  22671. sse.on_open(
  22672. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22673. sse.set_reconnect_interval(100);
  22674. sse.set_max_reconnect_attempts(3);
  22675. sse.start_async();
  22676. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22677. sse.stop();
  22678. std::lock_guard<std::mutex> lock(token_mutex);
  22679. ASSERT_GE(received_tokens.size(), 2u);
  22680. // First connection uses original header
  22681. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22682. // Second connection uses updated header from set_headers
  22683. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22684. }
  22685. // Test: 401 allows reconnection (so on_error can refresh headers)
  22686. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22687. std::atomic<int> connection_count{0};
  22688. // Endpoint: returns 401 on first attempt, 200 on second
  22689. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22690. int conn = connection_count.fetch_add(1);
  22691. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22692. res.status = StatusCode::Unauthorized_401;
  22693. res.set_content("Unauthorized", "text/plain");
  22694. return;
  22695. }
  22696. res.set_chunked_content_provider(
  22697. "text/event-stream", [](size_t offset, DataSink &sink) {
  22698. if (offset == 0) {
  22699. std::string event = "data: authenticated\n\n";
  22700. sink.write(event.data(), event.size());
  22701. }
  22702. return false;
  22703. });
  22704. });
  22705. Client client("localhost", get_port());
  22706. Headers headers = {{"Authorization", "Bearer expired"}};
  22707. sse::SSEClient sse(client, "/auth-retry", headers);
  22708. std::atomic<bool> message_received{false};
  22709. // Refresh token on error
  22710. sse.on_error(
  22711. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22712. sse.on_message([&](const sse::SSEMessage &msg) {
  22713. if (msg.data == "authenticated") { message_received.store(true); }
  22714. });
  22715. sse.set_reconnect_interval(100);
  22716. sse.set_max_reconnect_attempts(3);
  22717. sse.start_async();
  22718. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22719. sse.stop();
  22720. // Should have reconnected after 401 and succeeded with new token
  22721. EXPECT_GE(connection_count.load(), 2);
  22722. EXPECT_TRUE(message_received.load());
  22723. }
  22724. TEST(Issue2318Test, EmptyHostString) {
  22725. {
  22726. httplib::Client cli_empty("", PORT);
  22727. auto res = cli_empty.Get("/");
  22728. ASSERT_FALSE(res);
  22729. EXPECT_EQ(httplib::Error::Connection, res.error());
  22730. }
  22731. {
  22732. httplib::Client cli(" ", PORT);
  22733. auto res = cli.Get("/");
  22734. ASSERT_FALSE(res);
  22735. EXPECT_EQ(httplib::Error::Connection, res.error());
  22736. }
  22737. }
  22738. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22739. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22740. Server svr;
  22741. // Set a small payload limit (1KB)
  22742. svr.set_payload_max_length(1024);
  22743. svr.Post("/test", [&](const Request &req, Response &res) {
  22744. res.set_content("Body size: " + std::to_string(req.body.size()),
  22745. "text/plain");
  22746. });
  22747. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22748. auto se = detail::scope_exit([&] {
  22749. svr.stop();
  22750. listen_thread.join();
  22751. });
  22752. svr.wait_until_ready();
  22753. // Create data that compresses well but exceeds limit when decompressed
  22754. // 8KB of repeated null bytes compresses to a very small size
  22755. std::string original_data(8 * 1024, '\0');
  22756. // Compress the data using gzip
  22757. std::string compressed_data;
  22758. detail::gzip_compressor compressor;
  22759. compressor.compress(original_data.data(), original_data.size(), true,
  22760. [&](const char *data, size_t size) {
  22761. compressed_data.append(data, size);
  22762. return true;
  22763. });
  22764. // Verify compression worked (compressed should be much smaller)
  22765. ASSERT_LT(compressed_data.size(), original_data.size());
  22766. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22767. // Send compressed data with Content-Encoding: gzip
  22768. Client cli(HOST, PORT);
  22769. Headers headers = {{"Content-Encoding", "gzip"}};
  22770. auto res =
  22771. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22772. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22774. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22775. }
  22776. #endif
  22777. // ============================================================================
  22778. // OpenSSL-Specific Tests
  22779. // ============================================================================
  22780. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22781. X509 *readCertificate(const std::string &strFileName) {
  22782. std::ifstream inStream(strFileName);
  22783. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22784. std::istreambuf_iterator<char>());
  22785. if (strCertPEM.empty()) return (nullptr);
  22786. BIO *pbCert = BIO_new(BIO_s_mem());
  22787. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22788. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22789. BIO_free(pbCert);
  22790. return (pCert);
  22791. }
  22792. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22793. std::ifstream inStream(strFileName);
  22794. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22795. std::istreambuf_iterator<char>());
  22796. if (strPrivateKeyPEM.empty()) return (nullptr);
  22797. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22798. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22799. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22800. BIO_free(pbPrivKey);
  22801. return (pPrivateKey);
  22802. }
  22803. TEST(BindServerTest, UpdateCerts) {
  22804. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22805. int port = svr.bind_to_any_port("0.0.0.0");
  22806. ASSERT_TRUE(svr.is_valid());
  22807. ASSERT_TRUE(port > 0);
  22808. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22809. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22810. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22811. ASSERT_TRUE(cert != nullptr);
  22812. ASSERT_TRUE(ca_cert != nullptr);
  22813. ASSERT_TRUE(key != nullptr);
  22814. X509_STORE *cert_store = X509_STORE_new();
  22815. X509_STORE_add_cert(cert_store, ca_cert);
  22816. // svr.update_certs(cert, key, cert_store); // deprecated
  22817. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22818. CLIENT_CA_CERT_FILE);
  22819. ASSERT_TRUE(svr.is_valid());
  22820. svr.stop();
  22821. X509_STORE_free(cert_store);
  22822. X509_free(cert);
  22823. X509_free(ca_cert);
  22824. EVP_PKEY_free(key);
  22825. }
  22826. // Test that update_certs() updates client CA list correctly
  22827. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22828. // Start with file-based constructor
  22829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22830. ASSERT_TRUE(svr.is_valid());
  22831. // Initially no client CA list should be set
  22832. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22833. ASSERT_TRUE(ssl_ctx != nullptr);
  22834. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22835. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22836. // Now update with client CA (PEM string)
  22837. std::string cert_pem, key_pem, ca_pem;
  22838. read_file(SERVER_CERT_FILE, cert_pem);
  22839. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22840. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22841. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22842. ASSERT_TRUE(svr.is_valid());
  22843. // Now client CA list should be set
  22844. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22845. ASSERT_TRUE(ca_list_after != nullptr);
  22846. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22847. }
  22848. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22849. // Test that the file-path SSLServer constructor properly sets the client CA
  22850. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22852. ASSERT_TRUE(svr.is_valid());
  22853. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22854. ASSERT_TRUE(ssl_ctx != nullptr);
  22855. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22856. ASSERT_TRUE(ca_list != nullptr);
  22857. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22858. }
  22859. #endif
  22860. // ============================================================================
  22861. // MbedTLS-Specific Tests
  22862. // ============================================================================
  22863. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22864. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22865. using namespace httplib::tls;
  22866. // Track if callback was invoked
  22867. bool callback_invoked = false;
  22868. // The callback receives void* ctx which is actually MbedTlsContext*
  22869. // We can access the mbedtls_ssl_config via the context
  22870. auto setup_callback = [&callback_invoked](void *ctx) {
  22871. callback_invoked = true;
  22872. // Cast to MbedTlsContext* to access the ssl config
  22873. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22874. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22875. // Use static variables to hold certificate data (simplified for test)
  22876. static mbedtls_x509_crt own_cert;
  22877. static mbedtls_pk_context own_key;
  22878. static mbedtls_x509_crt ca_chain;
  22879. static bool initialized = false;
  22880. if (!initialized) {
  22881. mbedtls_x509_crt_init(&own_cert);
  22882. mbedtls_pk_init(&own_key);
  22883. mbedtls_x509_crt_init(&ca_chain);
  22884. // Load server certificate
  22885. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22886. return false;
  22887. }
  22888. // Load server private key.
  22889. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22890. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22891. #if MBEDTLS_VERSION_MAJOR == 3
  22892. ,
  22893. mbedtls_ctr_drbg_random, nullptr
  22894. #endif
  22895. ) != 0) {
  22896. return false;
  22897. }
  22898. // Load CA chain for client verification
  22899. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22900. return false;
  22901. }
  22902. initialized = true;
  22903. }
  22904. // Configure the SSL config
  22905. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22906. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22907. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22908. // Set minimum TLS version using mbedTLS native API
  22909. #if MBEDTLS_VERSION_MAJOR >= 3
  22910. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22911. #else
  22912. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22913. MBEDTLS_SSL_MINOR_VERSION_3);
  22914. #endif
  22915. return true;
  22916. };
  22917. SSLServer svr(setup_callback);
  22918. ASSERT_TRUE(svr.is_valid());
  22919. ASSERT_TRUE(callback_invoked);
  22920. svr.Get("/test", [&](const Request &req, Response &res) {
  22921. res.set_content("test", "text/plain");
  22922. auto cert = req.peer_cert();
  22923. ASSERT_TRUE(static_cast<bool>(cert));
  22924. auto common_name = cert.subject_cn();
  22925. EXPECT_EQ("Common Name", common_name);
  22926. });
  22927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22928. auto se = detail::scope_exit([&] {
  22929. svr.stop();
  22930. t.join();
  22931. ASSERT_FALSE(svr.is_running());
  22932. });
  22933. svr.wait_until_ready();
  22934. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22935. cli.enable_server_certificate_verification(false);
  22936. cli.set_connection_timeout(30);
  22937. auto res = cli.Get("/test");
  22938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22939. ASSERT_EQ(StatusCode::OK_200, res->status);
  22940. }
  22941. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22942. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22943. // keep-alive SSL session, which reads through that config in
  22944. // mbedtls_ssl_close_notify.
  22945. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22947. ASSERT_TRUE(svr.is_valid());
  22948. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22949. res.set_content("test", "text/plain");
  22950. });
  22951. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22952. auto se = detail::scope_exit([&] {
  22953. svr.stop();
  22954. t.join();
  22955. ASSERT_FALSE(svr.is_running());
  22956. });
  22957. svr.wait_until_ready();
  22958. {
  22959. SSLClient cli(HOST, PORT);
  22960. cli.enable_server_certificate_verification(false);
  22961. cli.set_keep_alive(true);
  22962. auto res = cli.Get("/test");
  22963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22964. ASSERT_EQ(StatusCode::OK_200, res->status);
  22965. // cli is destructed here with the keep-alive SSL session still open.
  22966. }
  22967. }
  22968. #endif
  22969. // WebSocket Tests
  22970. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22971. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22972. // defining the meaning of these bits has been negotiated.
  22973. auto make_frame = [](uint8_t first_byte) {
  22974. std::string frame;
  22975. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22976. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22977. frame += "Hello";
  22978. return frame;
  22979. };
  22980. // RSV1 set (0x40)
  22981. {
  22982. detail::BufferStream strm;
  22983. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22984. ws::Opcode opcode;
  22985. std::string payload;
  22986. bool fin;
  22987. EXPECT_EQ(
  22988. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22989. ws::impl::FrameRead::Fail);
  22990. }
  22991. // RSV2 set (0x20)
  22992. {
  22993. detail::BufferStream strm;
  22994. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22995. ws::Opcode opcode;
  22996. std::string payload;
  22997. bool fin;
  22998. EXPECT_EQ(
  22999. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23000. ws::impl::FrameRead::Fail);
  23001. }
  23002. // RSV3 set (0x10)
  23003. {
  23004. detail::BufferStream strm;
  23005. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23006. ws::Opcode opcode;
  23007. std::string payload;
  23008. bool fin;
  23009. EXPECT_EQ(
  23010. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23011. ws::impl::FrameRead::Fail);
  23012. }
  23013. // No RSV bits set - should succeed
  23014. {
  23015. detail::BufferStream strm;
  23016. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23017. ws::Opcode opcode;
  23018. std::string payload;
  23019. bool fin;
  23020. EXPECT_EQ(
  23021. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23022. ws::impl::FrameRead::Ok);
  23023. EXPECT_EQ(ws::Opcode::Text, opcode);
  23024. EXPECT_EQ("Hello", payload);
  23025. EXPECT_TRUE(fin);
  23026. }
  23027. }
  23028. TEST(WebSocketTest, ControlFrameValidation) {
  23029. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23030. // payload length <= 125.
  23031. // Ping with FIN=0 - must be rejected
  23032. {
  23033. detail::BufferStream strm;
  23034. std::string frame;
  23035. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23036. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23037. strm.write(frame.data(), frame.size());
  23038. ws::Opcode opcode;
  23039. std::string payload;
  23040. bool fin;
  23041. EXPECT_EQ(
  23042. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23043. ws::impl::FrameRead::Fail);
  23044. }
  23045. // Close with FIN=0 - must be rejected
  23046. {
  23047. detail::BufferStream strm;
  23048. std::string frame;
  23049. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23050. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23051. strm.write(frame.data(), frame.size());
  23052. ws::Opcode opcode;
  23053. std::string payload;
  23054. bool fin;
  23055. EXPECT_EQ(
  23056. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23057. ws::impl::FrameRead::Fail);
  23058. }
  23059. // Ping with payload_len=126 (extended length) - must be rejected
  23060. {
  23061. detail::BufferStream strm;
  23062. std::string frame;
  23063. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23064. frame += static_cast<char>(126); // payload_len=126 (>125)
  23065. frame += static_cast<char>(0x00); // extended length high byte
  23066. frame += static_cast<char>(126); // extended length low byte
  23067. frame += std::string(126, 'x');
  23068. strm.write(frame.data(), frame.size());
  23069. ws::Opcode opcode;
  23070. std::string payload;
  23071. bool fin;
  23072. EXPECT_EQ(
  23073. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23074. ws::impl::FrameRead::Fail);
  23075. }
  23076. // Ping with FIN=1 and payload_len=125 - should succeed
  23077. {
  23078. detail::BufferStream strm;
  23079. std::string frame;
  23080. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23081. frame += static_cast<char>(125); // payload_len=125
  23082. frame += std::string(125, 'x');
  23083. strm.write(frame.data(), frame.size());
  23084. ws::Opcode opcode;
  23085. std::string payload;
  23086. bool fin;
  23087. EXPECT_EQ(
  23088. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23089. ws::impl::FrameRead::Ok);
  23090. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23091. EXPECT_EQ(125u, payload.size());
  23092. EXPECT_TRUE(fin);
  23093. }
  23094. }
  23095. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23096. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23097. // length MUST be 0.
  23098. // MSB set - must be rejected
  23099. {
  23100. detail::BufferStream strm;
  23101. std::string frame;
  23102. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23103. frame += static_cast<char>(127); // 64-bit extended length
  23104. frame += static_cast<char>(0x80); // MSB set (invalid)
  23105. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23106. strm.write(frame.data(), frame.size());
  23107. ws::Opcode opcode;
  23108. std::string payload;
  23109. bool fin;
  23110. EXPECT_EQ(
  23111. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23112. ws::impl::FrameRead::Fail);
  23113. }
  23114. // MSB clear - should pass length parsing (will be rejected by max_len,
  23115. // but that's a different check; use a small length to verify)
  23116. {
  23117. detail::BufferStream strm;
  23118. std::string frame;
  23119. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23120. frame += static_cast<char>(127); // 64-bit extended length
  23121. frame += std::string(7, '\0'); // high bytes = 0
  23122. frame += static_cast<char>(0x03); // length = 3
  23123. frame += "abc";
  23124. strm.write(frame.data(), frame.size());
  23125. ws::Opcode opcode;
  23126. std::string payload;
  23127. bool fin;
  23128. EXPECT_EQ(
  23129. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23130. ws::impl::FrameRead::Ok);
  23131. EXPECT_EQ(ws::Opcode::Text, opcode);
  23132. EXPECT_EQ("abc", payload);
  23133. }
  23134. }
  23135. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23136. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23137. // Valid UTF-8
  23138. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23139. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23140. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23141. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23142. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23143. // Invalid UTF-8
  23144. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23145. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23146. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23147. EXPECT_FALSE(
  23148. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23149. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23150. }
  23151. TEST(WebSocketTest, ConnectAndDisconnect) {
  23152. Server svr;
  23153. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23154. std::string msg;
  23155. while (ws.read(msg)) {}
  23156. });
  23157. auto port = svr.bind_to_any_port(HOST);
  23158. std::thread t([&]() { svr.listen_after_bind(); });
  23159. svr.wait_until_ready();
  23160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23161. auto res = client.connect();
  23162. ASSERT_TRUE(res);
  23163. EXPECT_EQ(Error::Success, res.error());
  23164. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23165. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23166. EXPECT_TRUE(client.is_open());
  23167. client.close();
  23168. EXPECT_FALSE(client.is_open());
  23169. svr.stop();
  23170. t.join();
  23171. }
  23172. TEST(WebSocketTest, ValidURL) {
  23173. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23174. EXPECT_TRUE(ws1.is_valid());
  23175. ws::WebSocketClient ws2("ws://example.com/path");
  23176. EXPECT_TRUE(ws2.is_valid());
  23177. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23178. EXPECT_TRUE(ws3.is_valid());
  23179. #ifdef CPPHTTPLIB_SSL_ENABLED
  23180. ws::WebSocketClient wss1("wss://example.com/path");
  23181. EXPECT_TRUE(wss1.is_valid());
  23182. ws::WebSocketClient wss2("wss://example.com:443/path");
  23183. EXPECT_TRUE(wss2.is_valid());
  23184. #endif
  23185. }
  23186. TEST(WebSocketTest, InvalidURL) {
  23187. // No scheme
  23188. ws::WebSocketClient ws1("localhost:8080/path");
  23189. EXPECT_FALSE(ws1.is_valid());
  23190. // No path
  23191. ws::WebSocketClient ws2("ws://localhost:8080");
  23192. EXPECT_FALSE(ws2.is_valid());
  23193. // Empty string
  23194. ws::WebSocketClient ws3("");
  23195. EXPECT_FALSE(ws3.is_valid());
  23196. // Missing host
  23197. ws::WebSocketClient ws4("ws://:8080/path");
  23198. EXPECT_FALSE(ws4.is_valid());
  23199. // Port number overflow — should not crash
  23200. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23201. EXPECT_FALSE(ws5.is_valid());
  23202. // Port out of range
  23203. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23204. EXPECT_FALSE(ws6.is_valid());
  23205. }
  23206. TEST(WebSocketTest, UnsupportedScheme) {
  23207. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23208. ws::WebSocketClient ws1("http://localhost:8080/path");
  23209. EXPECT_FALSE(ws1.is_valid());
  23210. ws::WebSocketClient ws2("https://localhost:8080/path");
  23211. EXPECT_FALSE(ws2.is_valid());
  23212. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23213. EXPECT_FALSE(ws3.is_valid());
  23214. #else
  23215. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23216. std::invalid_argument);
  23217. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23218. std::invalid_argument);
  23219. #endif
  23220. }
  23221. TEST(WebSocketTest, ConnectWhenInvalid) {
  23222. ws::WebSocketClient ws("not a valid url");
  23223. EXPECT_FALSE(ws.is_valid());
  23224. auto res = ws.connect();
  23225. EXPECT_FALSE(res);
  23226. EXPECT_EQ(Error::Connection, res.error());
  23227. EXPECT_EQ(-1, res.status());
  23228. }
  23229. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23230. // Grab a port that is free, then close it again so nothing listens there
  23231. Server svr;
  23232. auto port = svr.bind_to_any_port(HOST);
  23233. svr.stop();
  23234. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23235. auto res = client.connect();
  23236. ASSERT_FALSE(res);
  23237. EXPECT_EQ(Error::Connection, res.error());
  23238. EXPECT_EQ(-1, res.status());
  23239. }
  23240. TEST(WebSocketTest, DefaultPort) {
  23241. ws::WebSocketClient ws1("ws://example.com/path");
  23242. EXPECT_TRUE(ws1.is_valid());
  23243. // ws:// defaults to port 80 (verified by successful parse)
  23244. #ifdef CPPHTTPLIB_SSL_ENABLED
  23245. ws::WebSocketClient ws2("wss://example.com/path");
  23246. EXPECT_TRUE(ws2.is_valid());
  23247. // wss:// defaults to port 443 (verified by successful parse)
  23248. #endif
  23249. }
  23250. TEST(WebSocketTest, IPv6LiteralAddress) {
  23251. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23252. EXPECT_TRUE(ws1.is_valid());
  23253. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23254. EXPECT_TRUE(ws2.is_valid());
  23255. }
  23256. TEST(WebSocketTest, ComplexPath) {
  23257. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23258. EXPECT_TRUE(ws1.is_valid());
  23259. ws::WebSocketClient ws2("ws://localhost:8080/");
  23260. EXPECT_TRUE(ws2.is_valid());
  23261. }
  23262. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23263. Server svr;
  23264. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23265. std::string msg;
  23266. while (ws.read(msg)) {}
  23267. });
  23268. auto port = svr.bind_to_any_port(HOST);
  23269. std::thread t([&]() { svr.listen_after_bind(); });
  23270. svr.wait_until_ready();
  23271. auto another_host = "example.com";
  23272. auto wrong_ip = "192.0.2.1";
  23273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23274. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23275. ASSERT_TRUE(client.connect());
  23276. EXPECT_TRUE(client.is_open());
  23277. client.close();
  23278. svr.stop();
  23279. t.join();
  23280. }
  23281. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23282. Server svr;
  23283. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23284. std::string msg;
  23285. while (ws.read(msg)) {}
  23286. });
  23287. auto port = svr.bind_to_any_port(HOST);
  23288. std::thread t([&]() { svr.listen_after_bind(); });
  23289. svr.wait_until_ready();
  23290. auto wrong_ip = "192.0.2.1";
  23291. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23292. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23293. client.set_connection_timeout(1);
  23294. client.set_read_timeout(1);
  23295. client.set_write_timeout(1);
  23296. EXPECT_FALSE(client.connect());
  23297. EXPECT_FALSE(client.is_open());
  23298. svr.stop();
  23299. t.join();
  23300. }
  23301. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23302. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23303. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23304. // (RFC 6761) is only a map key and the Host header value.
  23305. auto host = "target.invalid";
  23306. Server svr;
  23307. std::string received_host;
  23308. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23309. received_host = req.get_header_value("Host");
  23310. std::string msg;
  23311. while (ws.read(msg)) {}
  23312. });
  23313. auto port = svr.bind_to_any_port(HOST);
  23314. std::thread t([&]() { svr.listen_after_bind(); });
  23315. // ASSERT_* below returns from the test body, which would leave t joinable
  23316. // and make ~thread call std::terminate.
  23317. auto se = detail::scope_exit([&] {
  23318. svr.stop();
  23319. if (t.joinable()) { t.join(); }
  23320. });
  23321. svr.wait_until_ready();
  23322. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23323. std::to_string(port) + "/ws");
  23324. client.set_hostname_addr_map({{host, HOST}});
  23325. ASSERT_TRUE(client.connect());
  23326. EXPECT_TRUE(client.is_open());
  23327. client.close();
  23328. svr.stop();
  23329. t.join();
  23330. // The mapping only redirects the connection; the identity stays host_.
  23331. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23332. }
  23333. class WebSocketIntegrationTest : public ::testing::Test {
  23334. protected:
  23335. void SetUp() override {
  23336. server_ = httplib::detail::make_unique<Server>();
  23337. setup_server();
  23338. start_server();
  23339. }
  23340. void TearDown() override {
  23341. server_->stop();
  23342. if (server_thread_.joinable()) { server_thread_.join(); }
  23343. }
  23344. void setup_server() {
  23345. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23346. std::string msg;
  23347. ws::ReadResult ret;
  23348. while ((ret = ws.read(msg))) {
  23349. if (ret == ws::Binary) {
  23350. ws.send(msg.data(), msg.size());
  23351. } else {
  23352. ws.send(msg);
  23353. }
  23354. }
  23355. });
  23356. server_->WebSocket("/ws-echo-string",
  23357. [](const Request &, ws::WebSocket &ws) {
  23358. std::string msg;
  23359. while (ws.read(msg)) {
  23360. ws.send("echo: " + msg);
  23361. }
  23362. });
  23363. server_->WebSocket(
  23364. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23365. // Echo back request metadata
  23366. ws.send("path:" + req.path);
  23367. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23368. std::string msg;
  23369. while (ws.read(msg)) {}
  23370. });
  23371. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23372. std::string msg;
  23373. ws.read(msg); // wait for a message
  23374. ws.close();
  23375. });
  23376. server_->WebSocket("/ws-close-status",
  23377. [](const Request &, ws::WebSocket &ws) {
  23378. std::string msg;
  23379. ws.read(msg); // wait for a message
  23380. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23381. });
  23382. server_->WebSocket(
  23383. "/ws-subprotocol",
  23384. [](const Request &, ws::WebSocket &ws) {
  23385. std::string msg;
  23386. while (ws.read(msg)) {
  23387. ws.send(msg);
  23388. }
  23389. },
  23390. [](const std::vector<std::string> &protocols) -> std::string {
  23391. for (const auto &p : protocols) {
  23392. if (p == "graphql-ws") { return p; }
  23393. }
  23394. return "";
  23395. });
  23396. server_->WebSocket(
  23397. "/ws-subprotocol-unoffered",
  23398. [](const Request &, ws::WebSocket &ws) {
  23399. std::string msg;
  23400. while (ws.read(msg)) {
  23401. ws.send(msg);
  23402. }
  23403. },
  23404. [](const std::vector<std::string> &) -> std::string {
  23405. return "admin";
  23406. });
  23407. }
  23408. void start_server() {
  23409. port_ = server_->bind_to_any_port(HOST);
  23410. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23411. server_->wait_until_ready();
  23412. }
  23413. std::unique_ptr<Server> server_;
  23414. std::thread server_thread_;
  23415. int port_ = 0;
  23416. };
  23417. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23419. "/ws-echo");
  23420. ASSERT_TRUE(client.connect());
  23421. ASSERT_TRUE(client.is_open());
  23422. ASSERT_TRUE(client.send("Hello WebSocket"));
  23423. std::string msg;
  23424. EXPECT_EQ(ws::Text, client.read(msg));
  23425. EXPECT_EQ("Hello WebSocket", msg);
  23426. client.close();
  23427. }
  23428. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23429. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23430. "/ws-echo");
  23431. ASSERT_TRUE(client.connect());
  23432. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23433. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23434. std::string msg;
  23435. EXPECT_EQ(ws::Binary, client.read(msg));
  23436. EXPECT_EQ(binary_data, msg);
  23437. client.close();
  23438. }
  23439. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23440. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23441. "/ws-echo");
  23442. ASSERT_TRUE(client.connect());
  23443. for (int i = 0; i < 10; i++) {
  23444. auto text = "message " + std::to_string(i);
  23445. ASSERT_TRUE(client.send(text));
  23446. std::string msg;
  23447. ASSERT_TRUE(client.read(msg));
  23448. EXPECT_EQ(text, msg);
  23449. }
  23450. client.close();
  23451. }
  23452. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23453. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23454. "/ws-close");
  23455. ASSERT_TRUE(client.connect());
  23456. // Send a message to trigger the server to close
  23457. ASSERT_TRUE(client.send("trigger close"));
  23458. // The server will close, so read should return false
  23459. std::string msg;
  23460. EXPECT_FALSE(client.read(msg));
  23461. EXPECT_FALSE(client.is_open());
  23462. }
  23463. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23465. "/ws-echo");
  23466. ASSERT_TRUE(client.connect());
  23467. // 128KB message
  23468. std::string large_data(128 * 1024, 'X');
  23469. ASSERT_TRUE(client.send(large_data));
  23470. std::string msg;
  23471. ASSERT_TRUE(client.read(msg));
  23472. EXPECT_EQ(large_data, msg);
  23473. client.close();
  23474. }
  23475. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23476. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23477. "/ws-echo");
  23478. ASSERT_TRUE(client.connect());
  23479. const int num_threads = 4;
  23480. std::vector<std::thread> threads;
  23481. std::atomic<int> send_count{0};
  23482. for (int t = 0; t < num_threads; t++) {
  23483. threads.emplace_back([&client, &send_count, t]() {
  23484. for (int i = 0; i < 5; i++) {
  23485. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23486. if (client.send(text)) { send_count++; }
  23487. }
  23488. });
  23489. }
  23490. for (auto &th : threads) {
  23491. th.join();
  23492. }
  23493. int received = 0;
  23494. std::string msg;
  23495. while (received < send_count.load()) {
  23496. if (!client.read(msg)) { break; }
  23497. received++;
  23498. }
  23499. EXPECT_EQ(send_count.load(), received);
  23500. client.close();
  23501. }
  23502. TEST_F(WebSocketIntegrationTest, ReadString) {
  23503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23504. "/ws-echo-string");
  23505. ASSERT_TRUE(client.connect());
  23506. ASSERT_TRUE(client.send("hello"));
  23507. std::string msg;
  23508. ASSERT_TRUE(client.read(msg));
  23509. EXPECT_EQ("echo: hello", msg);
  23510. ASSERT_TRUE(client.send("world"));
  23511. ASSERT_TRUE(client.read(msg));
  23512. EXPECT_EQ("echo: world", msg);
  23513. client.close();
  23514. }
  23515. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23516. Headers headers = {{"X-Test-Header", "test-value"}};
  23517. ws::WebSocketClient client(
  23518. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23519. ASSERT_TRUE(client.connect());
  23520. std::string msg;
  23521. ASSERT_TRUE(client.read(msg));
  23522. EXPECT_EQ("path:/ws-request-info", msg);
  23523. ASSERT_TRUE(client.read(msg));
  23524. EXPECT_EQ("header:test-value", msg);
  23525. client.close();
  23526. }
  23527. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23528. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23529. "/ws-echo");
  23530. client.set_read_timeout(1, 0); // 1 second
  23531. ASSERT_TRUE(client.connect());
  23532. // Don't send anything — server echo handler waits for a message, so read()
  23533. // should time out. The connection survives it: nothing was consumed.
  23534. std::string msg;
  23535. EXPECT_EQ(client.read(msg), ws::Timeout);
  23536. EXPECT_TRUE(client.is_open());
  23537. // And it is still usable afterwards.
  23538. EXPECT_TRUE(client.send("after timeout"));
  23539. EXPECT_EQ(client.read(msg), ws::Text);
  23540. EXPECT_EQ(msg, "after timeout");
  23541. }
  23542. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23544. "/ws-echo");
  23545. client.set_read_timeout(1, 0);
  23546. ASSERT_TRUE(client.connect());
  23547. ASSERT_TRUE(client.send("first"));
  23548. std::string msg;
  23549. ASSERT_EQ(client.read(msg), ws::Text);
  23550. ASSERT_EQ(msg, "first");
  23551. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23552. // not be used with a read timeout: it would reprocess the previous message.
  23553. EXPECT_EQ(client.read(msg), ws::Timeout);
  23554. EXPECT_EQ(msg, "first");
  23555. }
  23556. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23557. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23558. "/ws-echo");
  23559. ASSERT_TRUE(client.connect());
  23560. // Setting it once the connection is open reaches the live stream, not just
  23561. // the seed for the next connect().
  23562. client.set_read_timeout(1, 0);
  23563. std::string msg;
  23564. EXPECT_EQ(client.read(msg), ws::Timeout);
  23565. EXPECT_TRUE(client.is_open());
  23566. }
  23567. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23568. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23569. "/ws-echo");
  23570. client.set_read_timeout(5, 0);
  23571. ASSERT_TRUE(client.connect());
  23572. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23573. // The server should reject it and close the connection.
  23574. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23575. client.send(oversized);
  23576. // The server's read() should have failed due to payload limit,
  23577. // so our read() should return false (connection closed).
  23578. std::string msg;
  23579. EXPECT_FALSE(client.read(msg));
  23580. }
  23581. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23582. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23583. "/ws-echo");
  23584. client.set_read_timeout(10, 0);
  23585. ASSERT_TRUE(client.connect());
  23586. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23587. // This should succeed.
  23588. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23589. ASSERT_TRUE(client.send(at_limit));
  23590. std::string msg;
  23591. ASSERT_TRUE(client.read(msg));
  23592. EXPECT_EQ(at_limit.size(), msg.size());
  23593. client.close();
  23594. }
  23595. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23596. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23597. "/nonexistent");
  23598. auto res = client.connect();
  23599. EXPECT_FALSE(res);
  23600. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23601. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23602. EXPECT_FALSE(client.is_open());
  23603. }
  23604. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23605. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23606. "/ws-echo");
  23607. ASSERT_TRUE(client.connect());
  23608. ASSERT_TRUE(client.send(""));
  23609. std::string msg;
  23610. EXPECT_EQ(ws::Text, client.read(msg));
  23611. EXPECT_EQ("", msg);
  23612. client.close();
  23613. }
  23614. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23615. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23616. "/ws-echo");
  23617. // First connection
  23618. ASSERT_TRUE(client.connect());
  23619. ASSERT_TRUE(client.send("first"));
  23620. std::string msg;
  23621. ASSERT_TRUE(client.read(msg));
  23622. EXPECT_EQ("first", msg);
  23623. client.close();
  23624. EXPECT_FALSE(client.is_open());
  23625. // Reconnect using the same client object
  23626. ASSERT_TRUE(client.connect());
  23627. ASSERT_TRUE(client.is_open());
  23628. ASSERT_TRUE(client.send("second"));
  23629. ASSERT_TRUE(client.read(msg));
  23630. EXPECT_EQ("second", msg);
  23631. client.close();
  23632. }
  23633. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23634. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23635. "/ws-close-status");
  23636. ASSERT_TRUE(client.connect());
  23637. // Trigger the server to close with GoingAway status
  23638. ASSERT_TRUE(client.send("trigger"));
  23639. // read() should return false after receiving the close frame
  23640. std::string msg;
  23641. EXPECT_FALSE(client.read(msg));
  23642. EXPECT_FALSE(client.is_open());
  23643. }
  23644. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23646. "/ws-echo");
  23647. ASSERT_TRUE(client.connect());
  23648. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23649. EXPECT_FALSE(client.is_open());
  23650. }
  23651. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23652. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23653. ws::WebSocketClient client(
  23654. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23655. ASSERT_TRUE(client.connect());
  23656. // Server should have selected graphql-ws
  23657. EXPECT_EQ("graphql-ws", client.subprotocol());
  23658. client.close();
  23659. }
  23660. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23661. Headers headers;
  23662. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23663. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23664. ws::WebSocketClient client(
  23665. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23666. ASSERT_TRUE(client.connect());
  23667. // The offer on the second field line counts too, so graphql-ws is selected
  23668. EXPECT_EQ("graphql-ws", client.subprotocol());
  23669. client.close();
  23670. }
  23671. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23672. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23673. ws::WebSocketClient client(
  23674. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23675. ASSERT_TRUE(client.connect());
  23676. // Server should not have selected any subprotocol
  23677. EXPECT_TRUE(client.subprotocol().empty());
  23678. client.close();
  23679. }
  23680. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23681. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23683. "/ws-subprotocol-unoffered",
  23684. headers);
  23685. ASSERT_TRUE(client.connect());
  23686. EXPECT_TRUE(client.subprotocol().empty());
  23687. client.close();
  23688. }
  23689. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23690. // Connect without requesting any subprotocol
  23691. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23692. "/ws-subprotocol");
  23693. ASSERT_TRUE(client.connect());
  23694. EXPECT_TRUE(client.subprotocol().empty());
  23695. client.close();
  23696. }
  23697. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23699. "/ws-echo");
  23700. client.set_tcp_nodelay(true);
  23701. client.set_connection_timeout(3, 0);
  23702. bool socket_options_called = false;
  23703. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23704. ASSERT_TRUE(client.connect());
  23705. ASSERT_TRUE(client.is_open());
  23706. EXPECT_TRUE(socket_options_called);
  23707. ASSERT_TRUE(client.send("hello"));
  23708. std::string msg;
  23709. auto result = client.read(msg);
  23710. EXPECT_EQ(result, ws::ReadResult::Text);
  23711. EXPECT_EQ(msg, "hello");
  23712. client.close();
  23713. }
  23714. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23715. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23716. "/ws-echo");
  23717. client.set_connection_timeout(std::chrono::seconds(3));
  23718. client.set_write_timeout(std::chrono::seconds(3));
  23719. // A sub-second remainder exercises the seconds/microseconds split.
  23720. client.set_read_timeout(std::chrono::milliseconds(1500));
  23721. ASSERT_TRUE(client.connect());
  23722. auto start = std::chrono::steady_clock::now();
  23723. std::string msg;
  23724. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23725. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23726. std::chrono::steady_clock::now() - start)
  23727. .count();
  23728. // Above 1s so that dropping the microseconds half of the split fails here.
  23729. // Ignoring the setter altogether would not reach this line at all: a client
  23730. // waits forever by default.
  23731. EXPECT_GE(elapsed, 1400);
  23732. EXPECT_LT(elapsed, 30000);
  23733. }
  23734. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23735. Server svr;
  23736. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23737. if (!req.has_header("Authorization")) {
  23738. res.status = StatusCode::Unauthorized_401;
  23739. res.set_content("Unauthorized", "text/plain");
  23740. return Server::HandlerResponse::Handled;
  23741. }
  23742. return Server::HandlerResponse::Unhandled;
  23743. });
  23744. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23745. std::string msg;
  23746. while (ws.read(msg)) {
  23747. ws.send(msg);
  23748. }
  23749. });
  23750. auto port = svr.bind_to_any_port("localhost");
  23751. std::thread t([&]() { svr.listen_after_bind(); });
  23752. svr.wait_until_ready();
  23753. // Without Authorization header - should be rejected before upgrade
  23754. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23755. EXPECT_FALSE(client1.connect());
  23756. // The rejection is framed like any other HTTP response
  23757. {
  23758. Client cli("localhost", port);
  23759. Headers headers = {{"Upgrade", "websocket"},
  23760. {"Connection", "Upgrade"},
  23761. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23762. {"Sec-WebSocket-Version", "13"}};
  23763. auto res = cli.Get("/ws", headers);
  23764. ASSERT_TRUE(res);
  23765. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23766. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23767. EXPECT_EQ("Unauthorized", res->body);
  23768. }
  23769. // With Authorization header - should succeed
  23770. Headers headers = {{"Authorization", "Bearer token123"}};
  23771. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23772. headers);
  23773. ASSERT_TRUE(client2.connect());
  23774. ASSERT_TRUE(client2.send("hello"));
  23775. std::string msg;
  23776. ASSERT_TRUE(client2.read(msg));
  23777. EXPECT_EQ("hello", msg);
  23778. client2.close();
  23779. svr.stop();
  23780. t.join();
  23781. }
  23782. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23783. Server svr;
  23784. std::atomic<int> pre_routing_calls{0};
  23785. std::atomic<int> pre_request_calls{0};
  23786. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23787. pre_routing_calls++;
  23788. if (req.path == "/handled") {
  23789. res.set_content("handled", "text/plain");
  23790. return Server::HandlerResponse::Handled;
  23791. }
  23792. return Server::HandlerResponse::Unhandled;
  23793. });
  23794. svr.set_pre_request_handler([&](const Request &, Response &) {
  23795. pre_request_calls++;
  23796. return Server::HandlerResponse::Unhandled;
  23797. });
  23798. svr.Get("/http", [](const Request &, Response &res) {
  23799. res.set_content("http", "text/plain");
  23800. });
  23801. svr.WebSocket("/ws",
  23802. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23803. auto port = svr.bind_to_any_port("localhost");
  23804. std::thread t([&]() { svr.listen_after_bind(); });
  23805. auto se = detail::scope_exit([&] {
  23806. svr.stop();
  23807. t.join();
  23808. });
  23809. svr.wait_until_ready();
  23810. Headers upgrade = {{"Upgrade", "websocket"},
  23811. {"Connection", "Upgrade"},
  23812. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23813. {"Sec-WebSocket-Version", "13"}};
  23814. auto get = [&](const char *path) {
  23815. pre_routing_calls = 0;
  23816. return Client("localhost", port).Get(path, upgrade);
  23817. };
  23818. // No WebSocket route, but an HTTP one
  23819. auto res = get("/http");
  23820. ASSERT_TRUE(res);
  23821. EXPECT_EQ(StatusCode::OK_200, res->status);
  23822. EXPECT_EQ("http", res->body);
  23823. EXPECT_EQ(1, pre_routing_calls);
  23824. EXPECT_EQ(1, pre_request_calls);
  23825. // No route at all
  23826. res = get("/none");
  23827. ASSERT_TRUE(res);
  23828. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23829. EXPECT_EQ(1, pre_routing_calls);
  23830. // Answered by the pre-routing handler
  23831. res = get("/handled");
  23832. ASSERT_TRUE(res);
  23833. EXPECT_EQ(StatusCode::OK_200, res->status);
  23834. EXPECT_EQ("handled", res->body);
  23835. EXPECT_EQ(1, pre_routing_calls);
  23836. // A WebSocket route
  23837. pre_routing_calls = 0;
  23838. pre_request_calls = 0;
  23839. {
  23840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23841. "/ws");
  23842. ASSERT_TRUE(client.connect());
  23843. std::string msg;
  23844. ASSERT_TRUE(client.read(msg));
  23845. EXPECT_EQ("ws", msg);
  23846. client.close();
  23847. }
  23848. EXPECT_EQ(1, pre_routing_calls);
  23849. EXPECT_EQ(1, pre_request_calls);
  23850. }
  23851. // An upgrade request answered by a hook leaves its body unread, so that body
  23852. // must not be served as the next request on the connection.
  23853. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23854. Server svr;
  23855. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23856. if (req.path == "/pre-routing") {
  23857. res.set_content("pre-routing", "text/plain");
  23858. return Server::HandlerResponse::Handled;
  23859. }
  23860. return Server::HandlerResponse::Unhandled;
  23861. });
  23862. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23863. if (req.matched_route == "/pre-request") {
  23864. res.set_content("pre-request", "text/plain");
  23865. return Server::HandlerResponse::Handled;
  23866. }
  23867. return Server::HandlerResponse::Unhandled;
  23868. });
  23869. svr.Get("/smuggled", [](const Request &, Response &res) {
  23870. res.set_content("smuggled", "text/plain");
  23871. });
  23872. svr.WebSocket("/pre-request",
  23873. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23874. auto port = svr.bind_to_any_port(HOST);
  23875. std::thread t([&]() { svr.listen_after_bind(); });
  23876. auto se = detail::scope_exit([&] {
  23877. svr.stop();
  23878. t.join();
  23879. });
  23880. svr.wait_until_ready();
  23881. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23882. for (auto path : {"/pre-routing", "/pre-request"}) {
  23883. std::string req = std::string("GET ") + path +
  23884. " HTTP/1.1\r\n"
  23885. "Host: localhost\r\n"
  23886. "Upgrade: websocket\r\n"
  23887. "Connection: Upgrade\r\n"
  23888. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23889. "Sec-WebSocket-Version: 13\r\n"
  23890. "Content-Length: " +
  23891. std::to_string(body.size()) + "\r\n\r\n" + body;
  23892. std::string res;
  23893. ASSERT_TRUE(send_request(5, req, &res, port));
  23894. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23895. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23896. // Only one response, and the body was not served as a request
  23897. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23898. }
  23899. }
  23900. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23901. Server svr;
  23902. std::atomic<int> pre_request_calls{0};
  23903. std::atomic<bool> route_matched{false};
  23904. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23905. pre_request_calls++;
  23906. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23907. if (req.get_header_value("Authorization") != "Bearer token123") {
  23908. res.status = StatusCode::Unauthorized_401;
  23909. res.set_content("Unauthorized", "text/plain");
  23910. return Server::HandlerResponse::Handled;
  23911. }
  23912. return Server::HandlerResponse::Unhandled;
  23913. });
  23914. std::atomic<bool> handler_called{false};
  23915. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23916. handler_called = true;
  23917. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23918. });
  23919. auto port = svr.bind_to_any_port("localhost");
  23920. std::thread t([&]() { svr.listen_after_bind(); });
  23921. svr.wait_until_ready();
  23922. // Without Authorization header - should be rejected before upgrade
  23923. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23924. "/ws/1");
  23925. EXPECT_FALSE(client1.connect());
  23926. EXPECT_FALSE(handler_called);
  23927. EXPECT_EQ(1, pre_request_calls);
  23928. EXPECT_TRUE(route_matched);
  23929. // The rejection is an ordinary HTTP response, not a protocol switch
  23930. {
  23931. Client cli("localhost", port);
  23932. Headers headers = {{"Upgrade", "websocket"},
  23933. {"Connection", "Upgrade"},
  23934. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23935. {"Sec-WebSocket-Version", "13"}};
  23936. auto res = cli.Get("/ws/1", headers);
  23937. ASSERT_TRUE(res);
  23938. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23939. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23940. EXPECT_EQ("Unauthorized", res->body);
  23941. }
  23942. EXPECT_FALSE(handler_called);
  23943. // With Authorization header - should succeed
  23944. Headers headers = {{"Authorization", "Bearer token123"}};
  23945. ws::WebSocketClient client2(
  23946. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23947. ASSERT_TRUE(client2.connect());
  23948. std::string msg;
  23949. ASSERT_TRUE(client2.read(msg));
  23950. EXPECT_EQ("/ws/:id 2", msg);
  23951. EXPECT_TRUE(handler_called);
  23952. client2.close();
  23953. svr.stop();
  23954. t.join();
  23955. }
  23956. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23957. static Headers websocket_upgrade_headers() {
  23958. return {{"Upgrade", "websocket"},
  23959. {"Connection", "Upgrade"},
  23960. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23961. {"Sec-WebSocket-Version", "13"},
  23962. {"Sec-WebSocket-Protocol", "chat"}};
  23963. }
  23964. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23965. Server svr;
  23966. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23967. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23968. return Server::HandlerResponse::Unhandled;
  23969. });
  23970. svr.set_pre_request_handler([](const Request &req, Response &) {
  23971. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23972. return Server::HandlerResponse::Unhandled;
  23973. });
  23974. svr.set_exception_handler(
  23975. [](const Request &, Response &res, std::exception_ptr ep) {
  23976. try {
  23977. std::rethrow_exception(ep);
  23978. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23979. });
  23980. auto handler = [](const Request &, ws::WebSocket &) {};
  23981. svr.WebSocket("/pre-routing", handler);
  23982. svr.WebSocket("/pre-request", handler);
  23983. svr.WebSocket("/sub-protocol", handler,
  23984. [](const std::vector<std::string> &) -> std::string {
  23985. throw std::runtime_error("/sub-protocol");
  23986. });
  23987. auto port = svr.bind_to_any_port(HOST);
  23988. ASSERT_GT(port, 0);
  23989. thread t = thread([&] { svr.listen_after_bind(); });
  23990. auto se = detail::scope_exit([&] {
  23991. svr.stop();
  23992. t.join();
  23993. ASSERT_FALSE(svr.is_running());
  23994. });
  23995. svr.wait_until_ready();
  23996. Client cli(HOST, port);
  23997. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23998. auto res = cli.Get(path, websocket_upgrade_headers());
  23999. if (!res) {
  24000. ADD_FAILURE() << path << ": " << to_string(res.error());
  24001. continue;
  24002. }
  24003. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24004. EXPECT_EQ(path, res->body);
  24005. }
  24006. }
  24007. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24008. Server svr;
  24009. svr.set_pre_routing_handler(
  24010. [](const Request &, Response &) -> Server::HandlerResponse {
  24011. throw std::runtime_error("pre-routing");
  24012. });
  24013. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24014. auto port = svr.bind_to_any_port(HOST);
  24015. ASSERT_GT(port, 0);
  24016. thread t = thread([&] { svr.listen_after_bind(); });
  24017. auto se = detail::scope_exit([&] {
  24018. svr.stop();
  24019. t.join();
  24020. ASSERT_FALSE(svr.is_running());
  24021. });
  24022. svr.wait_until_ready();
  24023. Client cli(HOST, port);
  24024. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24025. ASSERT_TRUE(res) << to_string(res.error());
  24026. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24027. }
  24028. #endif
  24029. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24030. Server svr;
  24031. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24032. // A read timeout is how a handler gets control back. Without it, a handler
  24033. // parked in read() can never write on the connection it is reading.
  24034. ws.set_read_timeout(std::chrono::milliseconds(100));
  24035. std::string msg;
  24036. while (ws.is_open()) {
  24037. auto r = ws.read(msg);
  24038. if (r == httplib::ws::Timeout) {
  24039. ws.send("tick");
  24040. continue;
  24041. }
  24042. if (r == httplib::ws::Fail) { break; }
  24043. ws.send(msg);
  24044. }
  24045. });
  24046. auto port = svr.bind_to_any_port("localhost");
  24047. std::thread t([&]() { svr.listen_after_bind(); });
  24048. svr.wait_until_ready();
  24049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24050. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24051. ASSERT_TRUE(client.connect());
  24052. // The client sends nothing, so anything it receives came out of the
  24053. // handler's timeout path.
  24054. std::string msg;
  24055. ASSERT_EQ(client.read(msg), ws::Text);
  24056. EXPECT_EQ("tick", msg);
  24057. client.close();
  24058. svr.stop();
  24059. t.join();
  24060. }
  24061. // Stream::read may return fewer bytes than asked for. This is that contract at
  24062. // its worst -- one byte per call -- which is what a frame header straddling a
  24063. // read buffer's boundary looks like to the frame parser.
  24064. class WsByteAtATimeStream : public Stream {
  24065. public:
  24066. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24067. bool is_readable() const override { return true; }
  24068. bool wait_readable() const override { return true; }
  24069. bool wait_writable() const override { return true; }
  24070. ssize_t read(char *ptr, size_t size) override {
  24071. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24072. *ptr = data_[pos_++];
  24073. return 1;
  24074. }
  24075. ssize_t write(const char *, size_t size) override {
  24076. return static_cast<ssize_t>(size);
  24077. }
  24078. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24079. ip = "127.0.0.1";
  24080. port = 0;
  24081. }
  24082. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24083. ip = "127.0.0.1";
  24084. port = 0;
  24085. }
  24086. socket_t socket() const override { return INVALID_SOCKET; }
  24087. time_t duration() const override { return 0; }
  24088. private:
  24089. std::string data_;
  24090. size_t pos_ = 0;
  24091. };
  24092. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24093. // The payload uses the 16-bit extended length, so the header, the length
  24094. // and the mask key are all multi-byte fields here. Each used to be read
  24095. // with a single read() call, which fails as soon as one is split. The
  24096. // payload is also a little over one read chunk, so it is read in two.
  24097. std::string body;
  24098. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24099. body += static_cast<char>(i % 251);
  24100. }
  24101. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24102. std::string frame;
  24103. frame += static_cast<char>(0x81); // FIN + Text
  24104. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24105. frame += static_cast<char>(body.size() >> 8);
  24106. frame += static_cast<char>(body.size() & 0xff);
  24107. for (size_t i = 0; i < 4; i++) {
  24108. frame += static_cast<char>(mask[i]);
  24109. }
  24110. for (size_t i = 0; i < body.size(); i++) {
  24111. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24112. }
  24113. WsByteAtATimeStream strm(frame);
  24114. ws::Opcode opcode;
  24115. std::string payload;
  24116. bool fin = false;
  24117. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24118. /*expect_masked=*/true, body.size()),
  24119. ws::impl::FrameRead::Ok);
  24120. EXPECT_TRUE(fin);
  24121. EXPECT_EQ(opcode, ws::Opcode::Text);
  24122. EXPECT_EQ(payload, body);
  24123. }
  24124. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24125. std::string body(2000, 'x');
  24126. std::string frame;
  24127. frame += static_cast<char>(0x82); // FIN + Binary
  24128. frame += static_cast<char>(126); // 16-bit length follows
  24129. frame += static_cast<char>(body.size() >> 8);
  24130. frame += static_cast<char>(body.size() & 0xff);
  24131. frame += body;
  24132. detail::BufferStream strm;
  24133. strm.write(frame.data(), frame.size());
  24134. ws::Opcode opcode;
  24135. std::string payload;
  24136. bool fin;
  24137. EXPECT_EQ(
  24138. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24139. ws::impl::FrameRead::Ok);
  24140. EXPECT_EQ(body, payload);
  24141. }
  24142. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24143. // The header announces the largest payload allowed, and only 3 bytes of it
  24144. // ever arrive.
  24145. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24146. std::string frame;
  24147. frame += static_cast<char>(0x82); // FIN + Binary
  24148. frame += static_cast<char>(127); // 64-bit length follows
  24149. for (int shift = 56; shift >= 0; shift -= 8) {
  24150. frame += static_cast<char>((len >> shift) & 0xff);
  24151. }
  24152. frame += "abc";
  24153. detail::BufferStream strm;
  24154. strm.write(frame.data(), frame.size());
  24155. ws::Opcode opcode;
  24156. std::string payload;
  24157. bool fin;
  24158. EXPECT_EQ(
  24159. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24160. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24161. ws::impl::FrameRead::Fail);
  24162. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24163. }
  24164. TEST(WebSocketTest, QueryStringInHandshake) {
  24165. Server svr;
  24166. std::mutex mtx;
  24167. std::string received_target;
  24168. std::string received_token;
  24169. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24170. {
  24171. std::lock_guard<std::mutex> lock(mtx);
  24172. received_target = req.target;
  24173. if (req.has_param("token")) {
  24174. received_token = req.get_param_value("token");
  24175. }
  24176. }
  24177. std::string msg;
  24178. while (ws.read(msg)) {
  24179. ws.send(msg);
  24180. }
  24181. });
  24182. auto port = svr.bind_to_any_port("localhost");
  24183. std::thread t([&]() { svr.listen_after_bind(); });
  24184. svr.wait_until_ready();
  24185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24186. "/ws?token=ABC&session=123");
  24187. ASSERT_TRUE(client.connect());
  24188. // Round-trip ensures the handler has run and captured the request.
  24189. ASSERT_TRUE(client.send("hello"));
  24190. std::string msg;
  24191. ASSERT_TRUE(client.read(msg));
  24192. EXPECT_EQ("hello", msg);
  24193. client.close();
  24194. {
  24195. std::lock_guard<std::mutex> lock(mtx);
  24196. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24197. EXPECT_EQ("ABC", received_token);
  24198. }
  24199. svr.stop();
  24200. t.join();
  24201. }
  24202. // Run a handshake against a throwaway server and hand the request the server
  24203. // received back to the caller, so tests can assert on the headers the client
  24204. // actually put on the wire.
  24205. static void capture_websocket_handshake_request(
  24206. const Headers &client_headers,
  24207. std::function<void(const Request &, int port)> verify) {
  24208. Server svr;
  24209. std::mutex mtx;
  24210. Request received;
  24211. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24212. {
  24213. std::lock_guard<std::mutex> lock(mtx);
  24214. received = req;
  24215. }
  24216. std::string msg;
  24217. while (ws.read(msg)) {
  24218. ws.send(msg);
  24219. }
  24220. });
  24221. auto port = svr.bind_to_any_port("localhost");
  24222. std::thread t([&]() { svr.listen_after_bind(); });
  24223. auto se = detail::scope_exit([&] {
  24224. svr.stop();
  24225. t.join();
  24226. });
  24227. svr.wait_until_ready();
  24228. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24229. client_headers);
  24230. ASSERT_TRUE(client.connect());
  24231. ASSERT_TRUE(client.send("hello"));
  24232. std::string msg;
  24233. ASSERT_TRUE(client.read(msg));
  24234. client.close();
  24235. {
  24236. std::lock_guard<std::mutex> lock(mtx);
  24237. verify(received, port);
  24238. }
  24239. }
  24240. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24241. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24242. // Non-default port must be present in the Host header. Default ports
  24243. // (80/443) are omitted; that logic is covered by
  24244. // MakeHostAndPortStringTest.
  24245. EXPECT_EQ("localhost:" + std::to_string(port),
  24246. req.get_header_value("Host"));
  24247. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24248. req.get_header_value("User-Agent"));
  24249. EXPECT_FALSE(req.has_header("Accept"));
  24250. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24251. EXPECT_FALSE(req.has_header("Content-Length"));
  24252. });
  24253. }
  24254. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24255. capture_websocket_handshake_request(
  24256. {{"Host", "example.com"},
  24257. {"User-Agent", "custom-agent"},
  24258. {"X-Custom", "value"}},
  24259. [](const Request &req, int) {
  24260. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24261. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24262. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24263. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24264. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24265. });
  24266. }
  24267. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24268. capture_websocket_handshake_request(
  24269. {{"Upgrade", "bogus"},
  24270. {"Connection", "close"},
  24271. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24272. {"Sec-WebSocket-Version", "8"}},
  24273. [](const Request &req, int) {
  24274. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24275. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24276. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24277. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24278. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24279. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24280. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24281. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24282. req.get_header_value("Sec-WebSocket-Key"));
  24283. });
  24284. }
  24285. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24286. // A header the client refuses to send must abort the handshake before any
  24287. // part of it reaches the wire; a lone request line would otherwise sit in
  24288. // the peer's buffer as a truncated request.
  24289. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24290. ASSERT_NE(INVALID_SOCKET, srv);
  24291. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24292. sockaddr_in addr{};
  24293. addr.sin_family = AF_INET;
  24294. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24295. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24296. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24297. ASSERT_EQ(0, ::listen(srv, 1));
  24298. sockaddr_in bound{};
  24299. socklen_t bound_len = sizeof(bound);
  24300. ASSERT_EQ(
  24301. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24302. auto port = ntohs(bound.sin_port);
  24303. ssize_t received = -1;
  24304. std::thread t([&] {
  24305. // Bound every blocking call so a regression fails the test with a bad
  24306. // value instead of hanging the suite.
  24307. fd_set rfds;
  24308. FD_ZERO(&rfds);
  24309. FD_SET(srv, &rfds);
  24310. timeval tv{5, 0};
  24311. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24312. 0) {
  24313. return;
  24314. }
  24315. sockaddr_in cli_addr{};
  24316. socklen_t cli_len = sizeof(cli_addr);
  24317. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24318. if (cli == INVALID_SOCKET) { return; }
  24319. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24320. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24321. char buf[4096];
  24322. received = ::recv(cli, buf, sizeof(buf), 0);
  24323. });
  24324. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24325. // connect() has already shut the socket down by the time it returns false,
  24326. // so the peer sees EOF without waiting for the client to be destroyed.
  24327. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24328. {{"X-Bad", "a\r\nInjected: 1"}});
  24329. EXPECT_FALSE(client.connect());
  24330. t.join();
  24331. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24332. EXPECT_EQ(0, received);
  24333. }
  24334. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24335. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24336. // contains "upgrade" as a substring is a different token and must not
  24337. // start a WebSocket handshake.
  24338. auto make_request = [](const std::vector<std::string> &connection_values) {
  24339. Request req;
  24340. req.method = "GET";
  24341. req.headers.emplace("Upgrade", "websocket");
  24342. for (const auto &value : connection_values) {
  24343. req.headers.emplace("Connection", value);
  24344. }
  24345. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24346. req.headers.emplace("Sec-WebSocket-Version", "13");
  24347. return req;
  24348. };
  24349. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24350. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24351. EXPECT_TRUE(
  24352. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24353. EXPECT_TRUE(
  24354. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24355. EXPECT_TRUE(
  24356. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24357. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24358. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24359. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24360. EXPECT_FALSE(
  24361. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24362. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24363. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24364. }
  24365. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24366. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24367. // asks recipients to match each protocol-name case-insensitively, and RFC
  24368. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24369. // client naming websocket alongside another protocol, or on a second field
  24370. // line, is offering websocket; a value that merely contains "websocket" as a
  24371. // substring is a different protocol name and is not.
  24372. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24373. Request req;
  24374. req.method = "GET";
  24375. for (const auto &value : upgrade_values) {
  24376. req.headers.emplace("Upgrade", value);
  24377. }
  24378. req.headers.emplace("Connection", "Upgrade");
  24379. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24380. req.headers.emplace("Sec-WebSocket-Version", "13");
  24381. return req;
  24382. };
  24383. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24384. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24385. EXPECT_TRUE(
  24386. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24387. EXPECT_TRUE(
  24388. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24389. EXPECT_TRUE(
  24390. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24391. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24392. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24393. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24394. EXPECT_FALSE(
  24395. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24396. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24397. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24398. }
  24399. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24400. Server svr;
  24401. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24402. auto port = svr.bind_to_any_port("localhost");
  24403. std::thread t([&]() { svr.listen_after_bind(); });
  24404. auto se = detail::scope_exit([&] {
  24405. svr.stop();
  24406. t.join();
  24407. });
  24408. svr.wait_until_ready();
  24409. Headers headers = {{"Upgrade", "websocket"},
  24410. {"Connection", "notupgrade"},
  24411. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24412. {"Sec-WebSocket-Version", "13"}};
  24413. Client cli("localhost", port);
  24414. auto res = cli.Get("/ws", headers);
  24415. // The route exists only as a WebSocket route, so a request that fails the
  24416. // handshake check falls through to ordinary routing.
  24417. ASSERT_TRUE(res);
  24418. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24419. }
  24420. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24421. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24422. // Connection value is the only thing left for the client to reject.
  24423. Server svr;
  24424. svr.Get("/ws", [](const Request &req, Response &res) {
  24425. res.status = StatusCode::SwitchingProtocol_101;
  24426. res.set_header("Upgrade", "websocket");
  24427. res.set_header("Connection", "notupgrade");
  24428. res.set_header("Sec-WebSocket-Accept",
  24429. detail::websocket_accept_key(
  24430. req.get_header_value("Sec-WebSocket-Key")));
  24431. });
  24432. auto port = svr.bind_to_any_port("localhost");
  24433. std::thread t([&]() { svr.listen_after_bind(); });
  24434. auto se = detail::scope_exit([&] {
  24435. svr.stop();
  24436. t.join();
  24437. });
  24438. svr.wait_until_ready();
  24439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24440. auto res = client.connect();
  24441. EXPECT_FALSE(res);
  24442. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24443. EXPECT_FALSE(client.is_open());
  24444. }
  24445. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24446. Server svr;
  24447. svr.Get("/ws", [](const Request &req, Response &res) {
  24448. res.status = StatusCode::SwitchingProtocol_101;
  24449. res.set_header("Upgrade", "websocket");
  24450. res.set_header("Connection", "Upgrade");
  24451. res.set_header("Sec-WebSocket-Accept",
  24452. detail::websocket_accept_key(
  24453. req.get_header_value("Sec-WebSocket-Key")));
  24454. res.set_header("Sec-WebSocket-Protocol", "admin");
  24455. });
  24456. auto port = svr.bind_to_any_port("localhost");
  24457. std::thread t([&]() { svr.listen_after_bind(); });
  24458. auto se = detail::scope_exit([&] {
  24459. svr.stop();
  24460. t.join();
  24461. });
  24462. svr.wait_until_ready();
  24463. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24464. // Server selects a subprotocol the client never offered
  24465. {
  24466. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24467. ws::WebSocketClient client(url, headers);
  24468. auto res = client.connect();
  24469. EXPECT_FALSE(res);
  24470. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24471. EXPECT_FALSE(client.is_open());
  24472. EXPECT_TRUE(client.subprotocol().empty());
  24473. }
  24474. // Client offered none but the server named one anyway
  24475. {
  24476. ws::WebSocketClient client(url);
  24477. auto res = client.connect();
  24478. EXPECT_FALSE(res);
  24479. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24480. EXPECT_FALSE(client.is_open());
  24481. EXPECT_TRUE(client.subprotocol().empty());
  24482. }
  24483. }
  24484. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24485. // The socket path doubles as the URL host, so it must not contain '/'.
  24486. const char *shard = getenv("GTEST_SHARD_INDEX");
  24487. const std::string sock_path =
  24488. shard ? std::string("httplib-ws-") + shard + ".sock"
  24489. : std::string("httplib-ws.sock");
  24490. std::remove(sock_path.c_str());
  24491. Server svr;
  24492. std::mutex mtx;
  24493. std::string received_host;
  24494. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24495. {
  24496. std::lock_guard<std::mutex> lock(mtx);
  24497. received_host = req.get_header_value("Host");
  24498. }
  24499. std::string msg;
  24500. while (ws.read(msg)) {
  24501. ws.send(msg);
  24502. }
  24503. });
  24504. svr.set_address_family(AF_UNIX);
  24505. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24506. auto se = detail::scope_exit([&] {
  24507. svr.stop();
  24508. t.join();
  24509. std::remove(sock_path.c_str());
  24510. });
  24511. svr.wait_until_ready();
  24512. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24513. client.set_address_family(AF_UNIX);
  24514. ASSERT_TRUE(client.connect());
  24515. ASSERT_TRUE(client.send("hello"));
  24516. std::string msg;
  24517. ASSERT_TRUE(client.read(msg));
  24518. client.close();
  24519. {
  24520. std::lock_guard<std::mutex> lock(mtx);
  24521. // There is no host:port for a Unix socket, so the same "localhost"
  24522. // placeholder the HTTP client uses is expected.
  24523. EXPECT_EQ("localhost", received_host);
  24524. }
  24525. }
  24526. // Two threads must never parse WebSocket frames from the same stream.
  24527. // close() used to read the peer's Close reply with its own frame read, so it
  24528. // raced a reader thread that was in the middle of a payload: the payload loop
  24529. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24530. // so bytes taken by close() were replaced with bytes from further along the
  24531. // stream. The message kept its length and silently changed content.
  24532. //
  24533. // The raw peer below sends a frame header plus part of the payload, waits for
  24534. // the handler to call close(), and only then sends the rest. Whichever thread
  24535. // would win the race for those bytes, the message must arrive intact, because
  24536. // close() must not touch the stream while read() owns it.
  24537. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24538. #ifndef _WIN32
  24539. signal(SIGPIPE, SIG_IGN);
  24540. #endif
  24541. const size_t payload_len = 120; // fits the 7-bit length field
  24542. const size_t prefix_len = 8;
  24543. const int attempts = 8;
  24544. std::string expected(payload_len, '\0');
  24545. for (size_t i = 0; i < payload_len; i++) {
  24546. expected[i] = static_cast<char>('a' + i % 26);
  24547. }
  24548. std::atomic<bool> peer_stalled{false};
  24549. std::atomic<bool> handler_done{false};
  24550. std::mutex received_mutex;
  24551. std::vector<std::string> received;
  24552. // Bound every wait, so a regression fails the test instead of hanging the
  24553. // suite.
  24554. auto wait_for = [](const std::atomic<bool> &flag) {
  24555. for (int i = 0; i < 500 && !flag; i++) {
  24556. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24557. }
  24558. };
  24559. Server svr;
  24560. svr.set_websocket_ping_interval(0);
  24561. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24562. std::thread reader([&]() {
  24563. std::string msg;
  24564. while (ws.read(msg)) {
  24565. std::lock_guard<std::mutex> guard(received_mutex);
  24566. received.push_back(msg);
  24567. }
  24568. });
  24569. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24570. // inside read_websocket_frame() when close() runs.
  24571. wait_for(peer_stalled);
  24572. ws.close();
  24573. reader.join();
  24574. handler_done = true;
  24575. });
  24576. auto port = svr.bind_to_any_port("127.0.0.1");
  24577. std::thread t([&]() { svr.listen_after_bind(); });
  24578. auto se = detail::scope_exit([&] {
  24579. svr.stop();
  24580. t.join();
  24581. });
  24582. svr.wait_until_ready();
  24583. auto send_bytes = [](socket_t s, const std::string &data) {
  24584. #ifdef _WIN32
  24585. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24586. #else
  24587. auto n = ::send(s, data.data(), data.size(), 0);
  24588. #endif
  24589. return n == static_cast<decltype(n)>(data.size());
  24590. };
  24591. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24592. // Every length used here fits the 7-bit length field.
  24593. auto masked_header = [](uint8_t first_byte, size_t len) {
  24594. std::string h;
  24595. h += static_cast<char>(first_byte);
  24596. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24597. h.append(4, '\0'); // mask key
  24598. return h;
  24599. };
  24600. for (int attempt = 0; attempt < attempts; attempt++) {
  24601. peer_stalled = false;
  24602. handler_done = false;
  24603. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24604. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24605. auto se_sock = detail::scope_exit([&] {
  24606. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24607. });
  24608. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24609. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24610. sockaddr_in addr{};
  24611. addr.sin_family = AF_INET;
  24612. addr.sin_port = htons(static_cast<uint16_t>(port));
  24613. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24614. ASSERT_EQ(
  24615. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24616. << "attempt " << attempt;
  24617. ASSERT_TRUE(send_bytes(sock,
  24618. "GET /ws HTTP/1.1\r\n"
  24619. "Host: 127.0.0.1\r\n"
  24620. "Upgrade: websocket\r\n"
  24621. "Connection: Upgrade\r\n"
  24622. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24623. "Sec-WebSocket-Version: 13\r\n"
  24624. "\r\n"))
  24625. << "attempt " << attempt;
  24626. std::string response;
  24627. while (response.find("\r\n\r\n") == std::string::npos) {
  24628. char buf[512];
  24629. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24630. if (n <= 0) { break; }
  24631. response.append(buf, static_cast<size_t>(n));
  24632. }
  24633. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24634. << "attempt " << attempt;
  24635. // Send the header of a Binary message but only the first prefix_len bytes
  24636. // of its payload, leaving the reader thread stalled inside the payload.
  24637. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24638. expected.substr(0, prefix_len)))
  24639. << "attempt " << attempt;
  24640. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24641. peer_stalled = true;
  24642. // Let close() send its Close frame and park in its own read before the
  24643. // rest of the payload arrives, so both threads are waiting for it.
  24644. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24645. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24646. close_frame += static_cast<char>(0x03); // status 1000
  24647. close_frame += static_cast<char>(0xE8);
  24648. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24649. << "attempt " << attempt;
  24650. // Closing the peer releases the reader thread even on the buggy path,
  24651. // where it waits for bytes another thread already consumed.
  24652. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24653. detail::close_socket(sock);
  24654. sock = INVALID_SOCKET;
  24655. wait_for(handler_done);
  24656. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24657. }
  24658. std::lock_guard<std::mutex> guard(received_mutex);
  24659. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24660. << "a message in flight when close() ran was dropped";
  24661. for (size_t i = 0; i < received.size(); i++) {
  24662. EXPECT_EQ(expected, received[i]) << "message " << i;
  24663. }
  24664. }
  24665. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24666. // returning the socket, or INVALID_SOCKET.
  24667. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24668. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24669. if (sock == INVALID_SOCKET) { return sock; }
  24670. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24671. sockaddr_in addr{};
  24672. addr.sin_family = AF_INET;
  24673. addr.sin_port = htons(static_cast<uint16_t>(port));
  24674. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24675. std::string req = "GET " + path +
  24676. " HTTP/1.1\r\n"
  24677. "Host: 127.0.0.1\r\n"
  24678. "Upgrade: websocket\r\n"
  24679. "Connection: Upgrade\r\n"
  24680. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24681. "Sec-WebSocket-Version: 13\r\n"
  24682. "\r\n";
  24683. std::string res;
  24684. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24685. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24686. static_cast<ssize_t>(req.size())) {
  24687. char c;
  24688. while (res.find("\r\n\r\n") == std::string::npos &&
  24689. ::recv(sock, &c, 1, 0) == 1) {
  24690. res += c;
  24691. }
  24692. }
  24693. if (res.find(" 101 ") == std::string::npos) {
  24694. detail::close_socket(sock);
  24695. return INVALID_SOCKET;
  24696. }
  24697. return sock;
  24698. }
  24699. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24700. // The payload must fit the 7-bit length field.
  24701. static std::string masked_frame(uint8_t first_byte,
  24702. const std::string &payload) {
  24703. std::string f;
  24704. f += static_cast<char>(first_byte);
  24705. f += static_cast<char>(0x80 | payload.size());
  24706. f.append(4, '\0');
  24707. return f + payload;
  24708. }
  24709. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24710. std::atomic<bool> done{false};
  24711. std::string received;
  24712. Server svr;
  24713. svr.set_websocket_ping_interval(0);
  24714. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24715. std::string msg;
  24716. if (ws.read(msg) == ws::Binary) { received = msg; }
  24717. done = true;
  24718. });
  24719. auto port = svr.bind_to_any_port("127.0.0.1");
  24720. std::thread t([&]() { svr.listen_after_bind(); });
  24721. auto se = detail::scope_exit([&] {
  24722. svr.stop();
  24723. t.join();
  24724. });
  24725. svr.wait_until_ready();
  24726. auto sock = connect_raw_websocket(port, "/ws");
  24727. ASSERT_NE(INVALID_SOCKET, sock);
  24728. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24729. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24730. masked_frame(0x89, "p") + // FIN + Ping
  24731. masked_frame(0x80, "lo"); // FIN + Continuation
  24732. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24733. for (int i = 0; i < 500 && !done; i++) {
  24734. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24735. }
  24736. ASSERT_TRUE(done);
  24737. EXPECT_EQ("Hello", received);
  24738. // The Ping between the fragments is answered with a Pong.
  24739. char pong[3];
  24740. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24741. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24742. }
  24743. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24744. Server svr;
  24745. svr.set_websocket_ping_interval(-1);
  24746. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24747. std::string msg;
  24748. while (ws.read(msg)) {}
  24749. });
  24750. auto port = svr.bind_to_any_port("127.0.0.1");
  24751. std::thread t([&]() { svr.listen_after_bind(); });
  24752. auto se = detail::scope_exit([&] {
  24753. svr.stop();
  24754. t.join();
  24755. });
  24756. svr.wait_until_ready();
  24757. auto sock = connect_raw_websocket(port, "/ws");
  24758. ASSERT_NE(INVALID_SOCKET, sock);
  24759. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24760. // Nothing comes while the client stays quiet.
  24761. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24762. char c;
  24763. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24764. }
  24765. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24766. // and that has to end a read() already waiting on the peer, on every platform.
  24767. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24768. // The peer sends no pings, and its handler never calls read(), which is
  24769. // where pongs are written.
  24770. std::mutex mutex;
  24771. std::condition_variable cv;
  24772. auto release = false;
  24773. svr.set_websocket_ping_interval(0);
  24774. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24775. std::unique_lock<std::mutex> lock(mutex);
  24776. cv.wait(lock, [&] { return release; });
  24777. });
  24778. auto port = svr.bind_to_any_port(HOST);
  24779. std::thread t([&]() { svr.listen_after_bind(); });
  24780. auto se = detail::scope_exit([&] {
  24781. {
  24782. std::lock_guard<std::mutex> lock(mutex);
  24783. release = true;
  24784. }
  24785. cv.notify_all();
  24786. svr.stop();
  24787. t.join();
  24788. });
  24789. svr.wait_until_ready();
  24790. ws::WebSocketClient client(std::string(scheme) +
  24791. "://localhost:" + std::to_string(port) + "/ws");
  24792. #ifdef CPPHTTPLIB_SSL_ENABLED
  24793. client.enable_server_certificate_verification(false);
  24794. #endif
  24795. // A ping a second, given up on after two go unanswered: about 3s
  24796. client.set_websocket_ping_interval(1);
  24797. client.set_websocket_max_missed_pongs(2);
  24798. // Well past that, so that a read the timeout ends instead stands out
  24799. client.set_read_timeout(10);
  24800. ASSERT_TRUE(client.connect());
  24801. auto start = std::chrono::steady_clock::now();
  24802. std::string msg;
  24803. EXPECT_EQ(ws::Fail, client.read(msg));
  24804. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24805. std::chrono::steady_clock::now() - start)
  24806. .count(),
  24807. 6000);
  24808. EXPECT_FALSE(client.is_open());
  24809. }
  24810. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24811. Server svr;
  24812. check_pong_timeout_ends_read(svr, "ws");
  24813. }
  24814. #ifdef CPPHTTPLIB_SSL_ENABLED
  24815. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24817. ASSERT_TRUE(svr.is_valid());
  24818. check_pong_timeout_ends_read(svr, "wss");
  24819. }
  24820. #endif
  24821. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24822. Server svr;
  24823. svr.set_websocket_ping_interval(0);
  24824. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24825. std::string msg;
  24826. while (ws.read(msg)) {}
  24827. });
  24828. auto port = svr.bind_to_any_port("127.0.0.1");
  24829. std::thread t([&]() { svr.listen_after_bind(); });
  24830. auto se = detail::scope_exit([&] {
  24831. svr.stop();
  24832. t.join();
  24833. });
  24834. svr.wait_until_ready();
  24835. // Each Close payload and the reply it should get: an echo when valid, 1002
  24836. // otherwise.
  24837. std::vector<std::pair<std::string, std::string>> cases = {
  24838. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24839. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24840. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24841. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24842. };
  24843. // Also between the fragments of a message.
  24844. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24845. for (const auto &c : cases) {
  24846. auto sock = connect_raw_websocket(port, "/ws");
  24847. ASSERT_NE(INVALID_SOCKET, sock);
  24848. auto frames = prefix + masked_frame(0x88, c.first);
  24849. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24850. std::string reply;
  24851. char buf[256];
  24852. while (reply.size() < 2 + c.second.size()) {
  24853. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24854. if (n <= 0) { break; }
  24855. reply.append(buf, static_cast<size_t>(n));
  24856. }
  24857. detail::close_socket(sock);
  24858. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24859. c.second,
  24860. reply);
  24861. }
  24862. }
  24863. }
  24864. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24865. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24866. protected:
  24867. void SetUp() override {
  24868. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24869. SERVER_PRIVATE_KEY_FILE);
  24870. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24871. std::string msg;
  24872. ws::ReadResult ret;
  24873. while ((ret = ws.read(msg))) {
  24874. if (ret == ws::Binary) {
  24875. ws.send(msg.data(), msg.size());
  24876. } else {
  24877. ws.send(msg);
  24878. }
  24879. }
  24880. });
  24881. port_ = server_->bind_to_any_port(HOST);
  24882. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24883. server_->wait_until_ready();
  24884. }
  24885. void TearDown() override {
  24886. server_->stop();
  24887. if (server_thread_.joinable()) { server_thread_.join(); }
  24888. }
  24889. std::unique_ptr<SSLServer> server_;
  24890. std::thread server_thread_;
  24891. int port_ = 0;
  24892. };
  24893. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24894. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24895. {
  24896. ws::WebSocketClient client(url);
  24897. client.enable_server_certificate_verification(false);
  24898. auto calls = 0;
  24899. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24900. calls++;
  24901. return false;
  24902. });
  24903. EXPECT_FALSE(client.connect());
  24904. EXPECT_GT(calls, 0);
  24905. }
  24906. {
  24907. ws::WebSocketClient client(url);
  24908. client.enable_server_certificate_verification(false);
  24909. client.set_session_verifier([](tls::session_t) {
  24910. return SSLVerifierResponse::CertificateRejected;
  24911. });
  24912. EXPECT_FALSE(client.connect());
  24913. }
  24914. {
  24915. ws::WebSocketClient client(url);
  24916. client.enable_server_certificate_verification(false);
  24917. client.set_session_verifier([](tls::session_t) {
  24918. return SSLVerifierResponse::CertificateAccepted;
  24919. });
  24920. EXPECT_TRUE(client.connect());
  24921. }
  24922. }
  24923. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24924. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24925. "/ws-echo");
  24926. client.enable_server_certificate_verification(false);
  24927. ASSERT_TRUE(client.connect());
  24928. ASSERT_TRUE(client.is_open());
  24929. ASSERT_TRUE(client.send("Hello WSS"));
  24930. std::string msg;
  24931. EXPECT_EQ(ws::Text, client.read(msg));
  24932. EXPECT_EQ("Hello WSS", msg);
  24933. client.close();
  24934. }
  24935. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24936. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24937. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24938. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24939. // client (without calling close() first) is the only path that runs
  24940. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24941. // bug exactly.
  24942. //
  24943. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24944. // when linked against an instrumented libssl; run under Valgrind to catch it
  24945. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24946. // suite (the freed session otherwise stalls on the close handshake) — this test
  24947. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24948. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24949. {
  24950. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24951. "/ws-echo");
  24952. client.enable_server_certificate_verification(false);
  24953. client.set_read_timeout(2, 0);
  24954. client.set_write_timeout(2, 0);
  24955. ASSERT_TRUE(client.connect());
  24956. ASSERT_TRUE(client.is_open());
  24957. ASSERT_TRUE(client.send("still open"));
  24958. // Intentionally do NOT call client.close(): leaving scope runs
  24959. // shutdown_and_close() with the WebSocket still open, which must send the
  24960. // close frame while the TLS session is still alive.
  24961. }
  24962. }
  24963. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24964. // shutdown_and_close() at the start of connect(), reproducing the same
  24965. // use-after-free within the test body rather than at scope exit. The second
  24966. // connect must succeed and echo, proving the close handshake ran over a live
  24967. // session. See the note above about memory-tool requirements.
  24968. TEST_F(WebSocketSSLIntegrationTest,
  24969. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24970. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24971. "/ws-echo");
  24972. client.enable_server_certificate_verification(false);
  24973. client.set_read_timeout(2, 0);
  24974. client.set_write_timeout(2, 0);
  24975. ASSERT_TRUE(client.connect());
  24976. ASSERT_TRUE(client.is_open());
  24977. ASSERT_TRUE(client.send("still open"));
  24978. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24979. // the still-open connection, which must not touch a freed TLS session.
  24980. ASSERT_TRUE(client.connect());
  24981. ASSERT_TRUE(client.is_open());
  24982. ASSERT_TRUE(client.send("after reconnect"));
  24983. std::string msg;
  24984. EXPECT_EQ(ws::Text, client.read(msg));
  24985. EXPECT_EQ("after reconnect", msg);
  24986. client.close();
  24987. }
  24988. #endif
  24989. #ifdef CPPHTTPLIB_SSL_ENABLED
  24990. class WebSocketSSLCATest : public ::testing::Test {
  24991. protected:
  24992. void SetUp() override {
  24993. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24994. SERVER_PRIVATE_KEY_FILE);
  24995. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24996. std::string msg;
  24997. while (ws.read(msg)) {
  24998. ws.send(msg);
  24999. }
  25000. });
  25001. port_ = server_->bind_to_any_port("127.0.0.1");
  25002. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25003. server_->wait_until_ready();
  25004. }
  25005. void TearDown() override {
  25006. server_->stop();
  25007. if (server_thread_.joinable()) { server_thread_.join(); }
  25008. }
  25009. std::string url() const {
  25010. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25011. }
  25012. std::unique_ptr<SSLServer> server_;
  25013. std::thread server_thread_;
  25014. int port_ = 0;
  25015. };
  25016. // A custom CA loaded as PEM verifies the server with full certificate
  25017. // verification enabled
  25018. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25019. ws::WebSocketClient client(url());
  25020. std::string cert;
  25021. read_file(SERVER_CERT2_FILE, cert);
  25022. client.load_ca_cert_store(cert.c_str(), cert.size());
  25023. ASSERT_TRUE(client.connect());
  25024. ASSERT_TRUE(client.send("hello"));
  25025. std::string msg;
  25026. EXPECT_EQ(ws::Text, client.read(msg));
  25027. EXPECT_EQ("hello", msg);
  25028. client.close();
  25029. }
  25030. // A custom CA that does not cover the server must fail verification (the
  25031. // custom CA is exclusive; system certs are not loaded alongside it)
  25032. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25033. ws::WebSocketClient client(url());
  25034. std::string cert;
  25035. read_file(CLIENT_CA_CERT_FILE, cert);
  25036. client.load_ca_cert_store(cert.c_str(), cert.size());
  25037. auto res = client.connect();
  25038. ASSERT_FALSE(res);
  25039. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25040. EXPECT_EQ(-1, res.status());
  25041. EXPECT_NE(0u, res.ssl_backend_error());
  25042. }
  25043. // The same CA as a file path rather than PEM in memory
  25044. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25045. ws::WebSocketClient client(url());
  25046. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25047. ASSERT_TRUE(client.connect());
  25048. ASSERT_TRUE(client.send("hello"));
  25049. std::string msg;
  25050. EXPECT_EQ(ws::Text, client.read(msg));
  25051. EXPECT_EQ("hello", msg);
  25052. client.close();
  25053. }
  25054. // ...and a CA file that does not cover the server still fails, so it is the
  25055. // path above that decides the outcome
  25056. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25057. ws::WebSocketClient client(url());
  25058. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25059. ASSERT_FALSE(client.connect());
  25060. }
  25061. // Regression test: reconnecting with a native custom CA store used to reuse
  25062. // a store handle the previous TLS context had already freed (use-after-free
  25063. // under the OpenSSL backend). The context now lives as long as the client.
  25064. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25065. ws::WebSocketClient client(url());
  25066. std::string cert;
  25067. read_file(SERVER_CERT2_FILE, cert);
  25068. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25069. ASSERT_TRUE(client.connect());
  25070. client.close();
  25071. ASSERT_TRUE(client.connect());
  25072. ASSERT_TRUE(client.send("again"));
  25073. std::string msg;
  25074. EXPECT_EQ(ws::Text, client.read(msg));
  25075. EXPECT_EQ("again", msg);
  25076. client.close();
  25077. }
  25078. // Regression test: a certificate with a trusted chain but no identity match
  25079. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25080. // verification entirely for IP hosts, so this connection succeeded there.
  25081. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25082. // chain verification while the identity check must still fail.
  25083. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25085. ASSERT_TRUE(svr.is_valid());
  25086. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25087. std::string msg;
  25088. while (ws.read(msg)) {
  25089. ws.send(msg);
  25090. }
  25091. });
  25092. auto port = svr.bind_to_any_port("127.0.0.1");
  25093. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25094. auto se = detail::scope_exit([&] {
  25095. svr.stop();
  25096. t.join();
  25097. });
  25098. svr.wait_until_ready();
  25099. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25100. "/echo");
  25101. std::string cert;
  25102. read_file(SERVER_CERT_FILE, cert);
  25103. client.load_ca_cert_store(cert.c_str(), cert.size());
  25104. ASSERT_FALSE(client.connect());
  25105. }
  25106. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25107. // SNI, so nothing binds the host name to the TLS session. These bind the
  25108. // server to "localhost" instead, the only shape that exercises the SNI and
  25109. // hostname-verification path with certificate verification left enabled.
  25110. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25111. protected:
  25112. void Start(const char *cert_file) {
  25113. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25114. SERVER_PRIVATE_KEY_FILE);
  25115. ASSERT_TRUE(server_->is_valid());
  25116. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25117. std::string msg;
  25118. while (ws.read(msg)) {
  25119. ws.send(msg);
  25120. }
  25121. });
  25122. port_ = server_->bind_to_any_port("localhost");
  25123. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25124. server_->wait_until_ready();
  25125. }
  25126. void TearDown() override {
  25127. if (server_) { server_->stop(); }
  25128. if (server_thread_.joinable()) { server_thread_.join(); }
  25129. }
  25130. std::string url() const {
  25131. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25132. }
  25133. std::unique_ptr<SSLServer> server_;
  25134. std::thread server_thread_;
  25135. int port_ = 0;
  25136. };
  25137. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25138. // out and the connection is usable
  25139. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25140. Start(SERVER_CERT2_FILE);
  25141. ws::WebSocketClient client(url());
  25142. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25143. ASSERT_TRUE(client.connect());
  25144. ASSERT_TRUE(client.send("hello"));
  25145. std::string msg;
  25146. EXPECT_EQ(ws::Text, client.read(msg));
  25147. EXPECT_EQ("hello", msg);
  25148. client.close();
  25149. }
  25150. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25151. // while the identity check must still reject "localhost"
  25152. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25153. Start(SERVER_CERT_FILE);
  25154. ws::WebSocketClient client(url());
  25155. client.set_ca_cert_path(SERVER_CERT_FILE);
  25156. auto res = client.connect();
  25157. ASSERT_FALSE(res);
  25158. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25159. EXPECT_EQ(-1, res.status());
  25160. }
  25161. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25162. // disabled: the chain is still checked, only the identity check is skipped
  25163. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25164. Start(SERVER_CERT_FILE);
  25165. ws::WebSocketClient client(url());
  25166. client.set_ca_cert_path(SERVER_CERT_FILE);
  25167. client.enable_server_hostname_verification(false);
  25168. ASSERT_TRUE(client.connect());
  25169. ASSERT_TRUE(client.send("hello"));
  25170. std::string msg;
  25171. EXPECT_EQ(ws::Text, client.read(msg));
  25172. EXPECT_EQ("hello", msg);
  25173. client.close();
  25174. }
  25175. // A CA that did not sign the server certificate fails the chain, even though
  25176. // the name would match
  25177. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25178. Start(SERVER_CERT2_FILE);
  25179. ws::WebSocketClient client(url());
  25180. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25181. ASSERT_FALSE(client.connect());
  25182. }
  25183. // With verification disabled, neither the chain nor the name is checked
  25184. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25185. Start(SERVER_CERT_FILE);
  25186. ws::WebSocketClient client(url());
  25187. client.enable_server_certificate_verification(false);
  25188. ASSERT_TRUE(client.connect());
  25189. ASSERT_TRUE(client.send("hello"));
  25190. std::string msg;
  25191. EXPECT_EQ(ws::Text, client.read(msg));
  25192. EXPECT_EQ("hello", msg);
  25193. client.close();
  25194. }
  25195. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25196. protected:
  25197. void SetUp() override {
  25198. server_ = httplib::detail::make_unique<SSLServer>(
  25199. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25200. ASSERT_TRUE(server_->is_valid());
  25201. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25202. std::string msg;
  25203. while (ws.read(msg)) {
  25204. ws.send(msg);
  25205. }
  25206. });
  25207. port_ = server_->bind_to_any_port("localhost");
  25208. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25209. server_->wait_until_ready();
  25210. }
  25211. void TearDown() override {
  25212. server_->stop();
  25213. if (server_thread_.joinable()) { server_thread_.join(); }
  25214. }
  25215. std::string url() const {
  25216. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25217. }
  25218. void ConnectWithClientCert(const std::string &client_cert_file,
  25219. const std::string &client_private_key_file,
  25220. const char *private_key_password) {
  25221. std::string cert_pem, key_pem;
  25222. read_file(client_cert_file, cert_pem);
  25223. read_file(client_private_key_file, key_pem);
  25224. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25225. key_pem.c_str(), key_pem.size(),
  25226. private_key_password};
  25227. ConnectWithPem(pem);
  25228. }
  25229. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25230. ws::WebSocketClient client(url(), pem);
  25231. ASSERT_TRUE(client.is_valid());
  25232. client.enable_server_certificate_verification(false);
  25233. ASSERT_TRUE(client.connect());
  25234. ASSERT_TRUE(client.send("hello"));
  25235. std::string msg;
  25236. EXPECT_EQ(ws::Text, client.read(msg));
  25237. EXPECT_EQ("hello", msg);
  25238. client.close();
  25239. }
  25240. std::unique_ptr<SSLServer> server_;
  25241. std::thread server_thread_;
  25242. int port_ = 0;
  25243. };
  25244. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25245. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25246. }
  25247. // Control for the tests above: the fixture's server really does require a
  25248. // client certificate, so it is the PEM the constructor installed that decides
  25249. // the outcome.
  25250. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25251. ws::WebSocketClient client(url());
  25252. ASSERT_TRUE(client.is_valid());
  25253. client.enable_server_certificate_verification(false);
  25254. EXPECT_FALSE(client.connect());
  25255. }
  25256. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25257. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25258. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25259. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25260. }
  25261. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25262. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25263. std::string cert_pem, key_pem;
  25264. read_file(CLIENT_CERT_FILE, cert_pem);
  25265. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25266. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25267. std::vector<char> key(key_pem.begin(), key_pem.end());
  25268. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25269. key.size(), nullptr};
  25270. ConnectWithPem(pem);
  25271. }
  25272. #endif
  25273. #if !defined(_WIN32)
  25274. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25275. auto secret_dir = std::string("./symlink_test_secret");
  25276. auto served_dir = std::string("./symlink_test_served");
  25277. auto secret_file = secret_dir + "/secret.txt";
  25278. auto symlink_path = served_dir + "/escape";
  25279. // Setup: create directories and files
  25280. mkdir(secret_dir.c_str(), 0755);
  25281. mkdir(served_dir.c_str(), 0755);
  25282. {
  25283. std::ofstream ofs(secret_file);
  25284. ofs << "SECRET_DATA";
  25285. }
  25286. // Create symlink using absolute path so it resolves correctly
  25287. #ifdef PATH_MAX
  25288. char abs_secret[PATH_MAX];
  25289. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25290. #else
  25291. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25292. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25293. ASSERT_NE(nullptr, abs_secret);
  25294. #endif
  25295. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25296. auto se = detail::scope_exit([&] {
  25297. unlink(symlink_path.c_str());
  25298. unlink(secret_file.c_str());
  25299. rmdir(served_dir.c_str());
  25300. rmdir(secret_dir.c_str());
  25301. });
  25302. Server svr;
  25303. svr.set_mount_point("/", served_dir);
  25304. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25305. auto se2 = detail::scope_exit([&] {
  25306. svr.stop();
  25307. listen_thread.join();
  25308. });
  25309. svr.wait_until_ready();
  25310. Client cli("localhost", PORT);
  25311. // Symlink pointing outside base dir should be blocked
  25312. auto res = cli.Get("/escape/secret.txt");
  25313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25314. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25315. }
  25316. #endif
  25317. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25318. // "GET /smuggled" request), reads the first response, and only then sends the
  25319. // embedded request as the body. Returns how many times /smuggled ran.
  25320. //
  25321. // The body is sent AFTER receiving the first response (as in the original
  25322. // PoC) so that the stream_line_reader cannot buffer it together with the
  25323. // headers of the first request.
  25324. static int count_smuggled_requests(const std::string &outer_head,
  25325. std::string &first_response) {
  25326. Server svr;
  25327. svr.set_mount_point("/", "./www");
  25328. std::atomic<int> smuggled_count(0);
  25329. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25330. smuggled_count++;
  25331. res.set_content("oops", "text/plain");
  25332. });
  25333. svr.Post("/post", [&](const Request &req, Response &res) {
  25334. res.set_content(req.body, "text/plain");
  25335. });
  25336. auto port = svr.bind_to_any_port("localhost");
  25337. thread t = thread([&] { svr.listen_after_bind(); });
  25338. auto se = detail::scope_exit([&] {
  25339. svr.stop();
  25340. t.join();
  25341. });
  25342. svr.wait_until_ready();
  25343. auto error = Error::Success;
  25344. auto sock = detail::create_client_socket(
  25345. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25346. /*connection_timeout_sec=*/2, 0,
  25347. /*read_timeout_sec=*/2, 0,
  25348. /*write_timeout_sec=*/2, 0, std::string(), error);
  25349. EXPECT_NE(INVALID_SOCKET, sock);
  25350. if (sock == INVALID_SOCKET) { return -1; }
  25351. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25352. // The "smuggled" request will be sent as the body of the outer request
  25353. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25354. "Host: localhost\r\n"
  25355. "Connection: close\r\n"
  25356. "\r\n";
  25357. auto head = outer_head;
  25358. auto len = std::to_string(smuggled.size());
  25359. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25360. pos = head.find("{len}", pos + len.size())) {
  25361. head.replace(pos, 5, len);
  25362. }
  25363. // Step 1: Send only the outer request headers (no body yet)
  25364. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25365. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25366. // Step 2: Read the first response
  25367. char buf[4096];
  25368. for (;;) {
  25369. auto n = recv(sock, buf, sizeof(buf), 0);
  25370. if (n <= 0) break;
  25371. first_response.append(buf, static_cast<size_t>(n));
  25372. // Stop once we have a complete response (headers + body)
  25373. auto hdr_end = first_response.find("\r\n\r\n");
  25374. if (hdr_end != std::string::npos) {
  25375. // Check for Content-Length to know when the body is complete
  25376. auto cl_pos = first_response.find("Content-Length:");
  25377. if (cl_pos != std::string::npos) {
  25378. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25379. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25380. auto cl = std::stoul(
  25381. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25382. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25383. } else {
  25384. break; // No Content-Length, assume headers-only response
  25385. }
  25386. }
  25387. }
  25388. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25389. // vulnerable server the keep-alive loop reads this as a second request. The
  25390. // server may already have closed the connection, so the result is ignored.
  25391. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25392. // Half-close so that a server which drained the body sees EOF and closes,
  25393. // instead of the read below waiting for the read timeout.
  25394. #ifdef _WIN32
  25395. ::shutdown(sock, SD_SEND);
  25396. #else
  25397. ::shutdown(sock, SHUT_WR);
  25398. #endif
  25399. // Step 4: Read until the server closes the connection
  25400. for (;;) {
  25401. auto n = recv(sock, buf, sizeof(buf), 0);
  25402. if (n <= 0) break;
  25403. }
  25404. return smuggled_count.load();
  25405. }
  25406. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25407. // A GET request with Content-Length to a static file handler must have its
  25408. // body drained before the keep-alive connection is reused. Otherwise the
  25409. // unread body bytes are interpreted as the next HTTP request.
  25410. std::string first_response;
  25411. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25412. "Host: localhost\r\n"
  25413. "Content-Length: {len}\r\n"
  25414. "\r\n",
  25415. first_response));
  25416. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25417. }
  25418. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25419. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25420. // be answered with 400 and the connection closed. Treating it as "no body"
  25421. // leaves the body to be parsed as the next request.
  25422. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25423. const char *targets[] = {
  25424. "GET /file", // handler that never reads the body
  25425. "GET /not-found", // no handler matches (404)
  25426. "POST /post", // handler that reads the body
  25427. };
  25428. for (auto target : targets) {
  25429. for (auto value : values) {
  25430. std::string first_response;
  25431. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25432. " HTTP/1.1\r\n"
  25433. "Host: localhost\r\n"
  25434. "Content-Length: " +
  25435. value + "\r\n\r\n",
  25436. first_response))
  25437. << target << " with Content-Length: " << value;
  25438. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25439. << target << " with Content-Length: " << value;
  25440. }
  25441. }
  25442. }
  25443. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25444. // A 400 for an unparseable request line leaves the rest of the message
  25445. // unread, so the connection must be closed rather than reused.
  25446. std::string first_response;
  25447. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25448. "Host: localhost\r\n"
  25449. "Content-Length: {len}\r\n"
  25450. "\r\n",
  25451. first_response));
  25452. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25453. }
  25454. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25455. // Same as above for a header block that fails to parse.
  25456. std::string first_response;
  25457. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25458. "Host: localhost\r\n"
  25459. "Bad Header\r\n"
  25460. "Content-Length: {len}\r\n"
  25461. "\r\n",
  25462. first_response));
  25463. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25464. }
  25465. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25466. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25467. // server must not read another request on that connection, even when the
  25468. // request had no body to drain.
  25469. std::string first_response;
  25470. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25471. "Host: localhost\r\n"
  25472. "\r\n",
  25473. first_response));
  25474. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25475. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25476. }
  25477. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25478. // A content reader that stops early leaves the stream inside the body.
  25479. // Draining the whole Content-Length from there, or reading the body again,
  25480. // reads into the next request, and whatever follows is parsed as a request
  25481. // of its own.
  25482. Server svr;
  25483. std::atomic<int> smuggled_count(0);
  25484. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25485. svr.Post("/upload", [](const Request &req, Response &res,
  25486. const ContentReader &content_reader) {
  25487. // Stop at the last chunk, so the whole body has been read however it
  25488. // arrives.
  25489. auto length = req.get_header_value_u64("Content-Length");
  25490. size_t total = 0;
  25491. auto consumed = content_reader([&](const char *, size_t n) {
  25492. total += n;
  25493. return total < length;
  25494. });
  25495. EXPECT_FALSE(consumed);
  25496. if (req.has_param("retry")) {
  25497. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25498. }
  25499. // Replace the 400 the aborted read set, which would close the connection.
  25500. res.set_redirect("/done");
  25501. });
  25502. auto port = svr.bind_to_any_port(HOST);
  25503. thread t = thread([&] { svr.listen_after_bind(); });
  25504. auto se = detail::scope_exit([&] {
  25505. svr.stop();
  25506. t.join();
  25507. });
  25508. svr.wait_until_ready();
  25509. // A front end sees the second request as a POST whose body is the GET. The
  25510. // first body is as long as the POST's headers, so draining it again reads
  25511. // exactly those and leaves the GET to be parsed next.
  25512. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25513. "Host: localhost\r\n"
  25514. "\r\n";
  25515. std::string second_head = "POST /post HTTP/1.1\r\n"
  25516. "Host: localhost\r\n"
  25517. "Content-Length: " +
  25518. std::to_string(inner.size()) +
  25519. "\r\n"
  25520. "\r\n";
  25521. for (auto target : {"/upload", "/upload?retry"}) {
  25522. smuggled_count = 0;
  25523. std::string request = "POST " + std::string(target) +
  25524. " HTTP/1.1\r\n"
  25525. "Host: localhost\r\n"
  25526. "Content-Length: " +
  25527. std::to_string(second_head.size()) +
  25528. "\r\n"
  25529. "\r\n" +
  25530. std::string(second_head.size(), 'A') + second_head +
  25531. inner;
  25532. std::string response;
  25533. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25534. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25535. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25536. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25537. EXPECT_EQ(0, smuggled_count.load()) << target;
  25538. }
  25539. }
  25540. // An error response closes the connection anyway, so the body is left unread
  25541. // with a redirect, such as one to a login page.
  25542. static void serve_redirects(Server &svr,
  25543. const std::function<void(int)> &client) {
  25544. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25545. res.set_redirect("/login");
  25546. return Server::HandlerResponse::Handled;
  25547. });
  25548. auto port = svr.bind_to_any_port(HOST);
  25549. ASSERT_GT(port, 0);
  25550. thread t = thread([&] { svr.listen_after_bind(); });
  25551. auto se = detail::scope_exit([&] {
  25552. svr.stop();
  25553. t.join();
  25554. ASSERT_FALSE(svr.is_running());
  25555. });
  25556. svr.wait_until_ready();
  25557. client(port);
  25558. }
  25559. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25560. Server svr;
  25561. serve_redirects(svr, [](int port) {
  25562. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25563. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25564. std::to_string(body.size()) + "\r\n\r\n" + body +
  25565. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25566. std::string resp;
  25567. ASSERT_TRUE(send_request(1, req, &resp, port));
  25568. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25569. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25570. });
  25571. }
  25572. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25573. Server svr;
  25574. svr.set_read_timeout(0, 200000);
  25575. serve_redirects(svr, [](int port) {
  25576. // A byte every 100 ms keeps each read within the read timeout, but not the
  25577. // body as a whole, so the server closes and the bytes sent after that fail.
  25578. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25579. "Content-Length: 10\r\n\r\n"};
  25580. parts.resize(11, "x");
  25581. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25582. });
  25583. }
  25584. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25585. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25586. // must be rejected with 400 Bad Request.
  25587. Server svr;
  25588. svr.Post("/test", [&](const Request &, Response &res) {
  25589. res.set_content("ok", "text/plain");
  25590. });
  25591. thread t = thread([&] { svr.listen(HOST, PORT); });
  25592. auto se = detail::scope_exit([&] {
  25593. svr.stop();
  25594. t.join();
  25595. ASSERT_FALSE(svr.is_running());
  25596. });
  25597. svr.wait_until_ready();
  25598. // Exact "chunked"
  25599. {
  25600. auto req = "POST /test HTTP/1.1\r\n"
  25601. "Host: localhost\r\n"
  25602. "Content-Length: 5\r\n"
  25603. "Transfer-Encoding: chunked\r\n"
  25604. "Connection: close\r\n"
  25605. "\r\n"
  25606. "hello";
  25607. std::string response;
  25608. ASSERT_TRUE(send_request(1, req, &response));
  25609. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25610. response.substr(0, response.find("\r\n")));
  25611. }
  25612. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25613. {
  25614. auto req = "POST /test HTTP/1.1\r\n"
  25615. "Host: localhost\r\n"
  25616. "Content-Length: 5\r\n"
  25617. "Transfer-Encoding: gzip, chunked\r\n"
  25618. "Connection: close\r\n"
  25619. "\r\n"
  25620. "hello";
  25621. std::string response;
  25622. ASSERT_TRUE(send_request(1, req, &response));
  25623. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25624. response.substr(0, response.find("\r\n")));
  25625. }
  25626. }
  25627. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25628. Server svr;
  25629. svr.Post("/test", [&](const Request &, Response &res) {
  25630. res.set_content("ok", "text/plain");
  25631. });
  25632. thread t = thread([&] { svr.listen(HOST, PORT); });
  25633. auto se = detail::scope_exit([&] {
  25634. svr.stop();
  25635. t.join();
  25636. ASSERT_FALSE(svr.is_running());
  25637. });
  25638. svr.wait_until_ready();
  25639. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25640. // length cannot be determined, so the server must answer 400 and close
  25641. // rather than treat the request as bodyless and leave the body in the
  25642. // socket for the next request to pick up.
  25643. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25644. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25645. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25646. std::string response;
  25647. ASSERT_TRUE(send_request(1, req, &response));
  25648. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25649. response.substr(0, response.find("\r\n")))
  25650. << transfer_encoding;
  25651. }
  25652. // RFC 9110 5.3: the codings may also be split across several
  25653. // Transfer-Encoding lines, which combine in the order they were received.
  25654. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25655. // just like the single-line "chunked, gzip" above.
  25656. {
  25657. auto req = "POST /test HTTP/1.1\r\n"
  25658. "Host: localhost\r\n"
  25659. "Transfer-Encoding: chunked\r\n"
  25660. "Transfer-Encoding: gzip\r\n"
  25661. "\r\n"
  25662. "0\r\n\r\n";
  25663. std::string response;
  25664. ASSERT_TRUE(send_request(1, req, &response));
  25665. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25666. response.substr(0, response.find("\r\n")));
  25667. }
  25668. }
  25669. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25670. Server svr;
  25671. svr.Post("/test", [&](const Request &, Response &res) {
  25672. res.set_content("ok", "text/plain");
  25673. });
  25674. auto port = svr.bind_to_any_port(HOST);
  25675. ASSERT_GT(port, 0);
  25676. thread t = thread([&] { svr.listen_after_bind(); });
  25677. auto se = detail::scope_exit([&] {
  25678. svr.stop();
  25679. t.join();
  25680. ASSERT_FALSE(svr.is_running());
  25681. });
  25682. svr.wait_until_ready();
  25683. for (auto transfer_encoding :
  25684. {"Transfer-Encoding: gzip, chunked\r\n",
  25685. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25686. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25687. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25688. transfer_encoding + "\r\n0\r\n\r\n";
  25689. std::string response;
  25690. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25691. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25692. response.substr(0, response.find("\r\n")))
  25693. << transfer_encoding;
  25694. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25695. << transfer_encoding;
  25696. }
  25697. }
  25698. // Regression for issue #2450: a DELETE without Content-Length on a
  25699. // keep-alive connection must not let the post-response drain consume the
  25700. // next request's bytes.
  25701. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25702. Server svr;
  25703. std::atomic<int> delete_count(0);
  25704. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25705. delete_count++;
  25706. res.status = StatusCode::NoContent_204;
  25707. });
  25708. auto port = svr.bind_to_any_port(HOST);
  25709. thread t = thread([&] { svr.listen_after_bind(); });
  25710. auto se = detail::scope_exit([&] {
  25711. svr.stop();
  25712. t.join();
  25713. });
  25714. svr.wait_until_ready();
  25715. auto error = Error::Success;
  25716. auto sock = detail::create_client_socket(
  25717. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25718. /*connection_timeout_sec=*/2, 0,
  25719. /*read_timeout_sec=*/2, 0,
  25720. /*write_timeout_sec=*/2, 0, std::string(), error);
  25721. ASSERT_NE(INVALID_SOCKET, sock);
  25722. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25723. auto send_request_and_read_response = [&](const std::string &req,
  25724. std::string &out) -> bool {
  25725. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25726. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25727. char buf[4096];
  25728. for (;;) {
  25729. auto n = recv(sock, buf, sizeof(buf), 0);
  25730. if (n <= 0) { return !out.empty(); }
  25731. out.append(buf, static_cast<size_t>(n));
  25732. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25733. }
  25734. };
  25735. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25736. "Host: localhost\r\n"
  25737. "\r\n";
  25738. std::string resp1;
  25739. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25740. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25741. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25742. "Host: localhost\r\n"
  25743. "Connection: close\r\n"
  25744. "\r\n";
  25745. std::string resp2;
  25746. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25747. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25748. EXPECT_EQ(2, delete_count.load());
  25749. }
  25750. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25751. Server svr;
  25752. svr.Post("/ingest", [&](const Request &, Response &res,
  25753. const ContentReader &content_reader) {
  25754. auto consumed = content_reader([](const char *, size_t) { return false; });
  25755. EXPECT_FALSE(consumed);
  25756. res.status = StatusCode::Conflict_409;
  25757. res.set_header("Connection", "close");
  25758. });
  25759. auto port = svr.bind_to_any_port(HOST);
  25760. thread t = thread([&] { svr.listen_after_bind(); });
  25761. auto se = detail::scope_exit([&] {
  25762. svr.stop();
  25763. t.join();
  25764. });
  25765. svr.wait_until_ready();
  25766. auto error = Error::Success;
  25767. auto sock = detail::create_client_socket(
  25768. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25769. /*connection_timeout_sec=*/2, 0,
  25770. /*read_timeout_sec=*/1, 0,
  25771. /*write_timeout_sec=*/2, 0, std::string(), error);
  25772. ASSERT_NE(INVALID_SOCKET, sock);
  25773. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25774. std::string request = "POST /ingest HTTP/1.1\r\n"
  25775. "Host: localhost\r\n"
  25776. "Transfer-Encoding: chunked\r\n"
  25777. "\r\n"
  25778. "4\r\n"
  25779. "data\r\n";
  25780. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25781. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25782. std::string response;
  25783. ssize_t received = 0;
  25784. do {
  25785. char buf[4096];
  25786. received = recv(sock, buf, sizeof(buf), 0);
  25787. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25788. } while (received > 0);
  25789. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25790. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25791. EXPECT_EQ(0, received);
  25792. }
  25793. namespace no_proxy_test {
  25794. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25795. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25796. // calling listen().
  25797. class ScopedServer {
  25798. public:
  25799. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25800. ~ScopedServer() {
  25801. svr_.stop();
  25802. if (th_.joinable()) { th_.join(); }
  25803. }
  25804. Server &svr() { return svr_; }
  25805. int port() const { return port_; }
  25806. void listen() {
  25807. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25808. svr_.wait_until_ready();
  25809. }
  25810. private:
  25811. Server svr_;
  25812. std::thread th_;
  25813. int port_ = 0;
  25814. };
  25815. class ProxyAndTargetServers {
  25816. public:
  25817. ProxyAndTargetServers() {
  25818. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25819. proxy_hits_++;
  25820. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25821. res.set_content("via-proxy", "text/plain");
  25822. });
  25823. target_.Get(".*", [this](const Request &req, Response &res) {
  25824. target_hits_++;
  25825. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25826. res.set_content("direct", "text/plain");
  25827. });
  25828. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25829. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25830. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25831. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25832. proxy_mock_.wait_until_ready();
  25833. target_.wait_until_ready();
  25834. }
  25835. ~ProxyAndTargetServers() {
  25836. proxy_mock_.stop();
  25837. target_.stop();
  25838. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25839. if (target_thread_.joinable()) { target_thread_.join(); }
  25840. }
  25841. Server &proxy_mock() { return proxy_mock_; }
  25842. Server &target() { return target_; }
  25843. int proxy_port() const { return proxy_port_; }
  25844. int target_port() const { return target_port_; }
  25845. int proxy_hits() const { return proxy_hits_.load(); }
  25846. int target_hits() const { return target_hits_.load(); }
  25847. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25848. void reset_counters() {
  25849. proxy_hits_ = 0;
  25850. target_hits_ = 0;
  25851. last_had_proxy_authz_ = false;
  25852. }
  25853. private:
  25854. Server proxy_mock_;
  25855. Server target_;
  25856. std::thread proxy_thread_;
  25857. std::thread target_thread_;
  25858. int proxy_port_ = 0;
  25859. int target_port_ = 0;
  25860. std::atomic<int> proxy_hits_{0};
  25861. std::atomic<int> target_hits_{0};
  25862. std::atomic<bool> last_had_proxy_authz_{false};
  25863. };
  25864. inline std::unique_ptr<Client> make_client(const std::string &host,
  25865. ProxyAndTargetServers &s) {
  25866. auto cli = detail::make_unique<Client>(host, s.target_port());
  25867. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25868. cli->set_proxy("127.0.0.1", s.proxy_port());
  25869. return cli;
  25870. }
  25871. } // namespace no_proxy_test
  25872. using no_proxy_test::make_client;
  25873. using no_proxy_test::ProxyAndTargetServers;
  25874. // A stream request carries the credentials a buffered request does
  25875. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25876. no_proxy_test::ScopedServer origin;
  25877. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25878. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25879. });
  25880. origin.listen();
  25881. Client cli("127.0.0.1", origin.port());
  25882. cli.set_basic_auth("user", "pass");
  25883. auto handle = cli.open_stream("GET", "/x");
  25884. ASSERT_TRUE(handle.is_valid());
  25885. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25886. Client bearer("127.0.0.1", origin.port());
  25887. bearer.set_bearer_token_auth("tok");
  25888. auto handle2 = bearer.open_stream("GET", "/x");
  25889. ASSERT_TRUE(handle2.is_valid());
  25890. EXPECT_EQ("Bearer tok", read_all(handle2));
  25891. }
  25892. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25893. // takes its own credentials, as for a buffered request
  25894. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25895. std::string target, authz, proxy_authz;
  25896. no_proxy_test::ScopedServer proxy;
  25897. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25898. target = req.target;
  25899. authz = req.get_header_value("Authorization");
  25900. proxy_authz = req.get_header_value("Proxy-Authorization");
  25901. res.set_content("ok", "text/plain");
  25902. });
  25903. proxy.listen();
  25904. Client cli("origin.example", 8080);
  25905. cli.set_proxy("127.0.0.1", proxy.port());
  25906. cli.set_proxy_basic_auth("puser", "ppass");
  25907. cli.set_basic_auth("user", "pass");
  25908. auto handle = cli.open_stream("GET", "/x");
  25909. ASSERT_TRUE(handle.is_valid());
  25910. EXPECT_EQ("ok", read_all(handle));
  25911. EXPECT_EQ("http://origin.example:8080/x", target);
  25912. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25913. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25914. }
  25915. // In absolute-form the path follows the authority, so a path that does not
  25916. // begin with '/' would make the proxy connect to another host
  25917. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  25918. std::vector<std::string> targets;
  25919. no_proxy_test::ScopedServer proxy;
  25920. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25921. targets.push_back(req.target);
  25922. res.set_content("ok", "text/plain");
  25923. });
  25924. proxy.listen();
  25925. Client cli("origin.example", 8080);
  25926. cli.set_proxy("127.0.0.1", proxy.port());
  25927. cli.set_basic_auth("user", "pass");
  25928. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  25929. auto res = cli.Get(path);
  25930. EXPECT_FALSE(res) << path;
  25931. auto handle = cli.open_stream("GET", path);
  25932. EXPECT_FALSE(handle.is_valid()) << path;
  25933. }
  25934. EXPECT_TRUE(targets.empty());
  25935. auto res = cli.Get("/x");
  25936. ASSERT_TRUE(res);
  25937. ASSERT_EQ(1u, targets.size());
  25938. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  25939. }
  25940. TEST(NoProxyTest, ExactHostnameBypasses) {
  25941. ProxyAndTargetServers s;
  25942. auto cli = make_client("example.com", s);
  25943. cli->set_no_proxy({"example.com"});
  25944. auto res = cli->Get("/");
  25945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25946. EXPECT_EQ(0, s.proxy_hits());
  25947. EXPECT_EQ(1, s.target_hits());
  25948. }
  25949. TEST(NoProxyTest, SubdomainBypasses) {
  25950. ProxyAndTargetServers s;
  25951. auto cli = make_client("foo.example.com", s);
  25952. cli->set_no_proxy({"example.com"});
  25953. auto res = cli->Get("/");
  25954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25955. EXPECT_EQ(0, s.proxy_hits());
  25956. EXPECT_EQ(1, s.target_hits());
  25957. }
  25958. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25959. // Regression guard: "evilexample.com" must not be considered a subdomain
  25960. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25961. // check would let traffic bypass the proxy and leak credentials direct
  25962. // to the attacker host.
  25963. ProxyAndTargetServers s;
  25964. auto cli = make_client("evilexample.com", s);
  25965. cli->set_no_proxy({"example.com"});
  25966. auto res = cli->Get("/");
  25967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25968. EXPECT_GE(s.proxy_hits(), 1);
  25969. EXPECT_EQ(0, s.target_hits());
  25970. }
  25971. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25972. ProxyAndTargetServers s;
  25973. auto cli = make_client("example.com.evil.com", s);
  25974. cli->set_no_proxy({"example.com"});
  25975. auto res = cli->Get("/");
  25976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25977. EXPECT_GE(s.proxy_hits(), 1);
  25978. EXPECT_EQ(0, s.target_hits());
  25979. }
  25980. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25981. ProxyAndTargetServers s;
  25982. auto cli = make_client("example.com", s);
  25983. cli->set_no_proxy({".example.com"});
  25984. auto res = cli->Get("/");
  25985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25986. EXPECT_EQ(0, s.proxy_hits());
  25987. EXPECT_EQ(1, s.target_hits());
  25988. }
  25989. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25990. ProxyAndTargetServers s;
  25991. auto cli = make_client("Example.COM", s);
  25992. cli->set_no_proxy({"EXAMPLE.com"});
  25993. auto res = cli->Get("/");
  25994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25995. EXPECT_EQ(0, s.proxy_hits());
  25996. EXPECT_EQ(1, s.target_hits());
  25997. }
  25998. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25999. ProxyAndTargetServers s;
  26000. auto cli = make_client("example.com.", s);
  26001. cli->set_no_proxy({"example.com"});
  26002. auto res = cli->Get("/");
  26003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26004. EXPECT_EQ(0, s.proxy_hits());
  26005. EXPECT_EQ(1, s.target_hits());
  26006. }
  26007. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26008. // Trailing dots must be normalized on BOTH sides — host and entry.
  26009. // An implementation that only strips the host-side trailing dot would
  26010. // fail to match host "example.com" against entry "example.com." because
  26011. // a literal substring search would compare 11 chars against 12.
  26012. ProxyAndTargetServers s;
  26013. auto cli = make_client("example.com", s);
  26014. cli->set_no_proxy({"example.com."});
  26015. auto res = cli->Get("/");
  26016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26017. EXPECT_EQ(0, s.proxy_hits());
  26018. EXPECT_EQ(1, s.target_hits());
  26019. }
  26020. TEST(NoProxyTest, WildcardBypassesEverything) {
  26021. ProxyAndTargetServers s;
  26022. auto cli = make_client("anything.invalid.test", s);
  26023. cli->set_no_proxy({"*"});
  26024. auto res = cli->Get("/");
  26025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26026. EXPECT_EQ(0, s.proxy_hits());
  26027. EXPECT_EQ(1, s.target_hits());
  26028. }
  26029. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26030. ProxyAndTargetServers s;
  26031. Client cli("127.0.0.1", s.target_port());
  26032. cli.set_proxy("127.0.0.1", s.proxy_port());
  26033. cli.set_no_proxy({"127.0.0.1"});
  26034. auto res = cli.Get("/");
  26035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26036. EXPECT_EQ(0, s.proxy_hits());
  26037. EXPECT_EQ(1, s.target_hits());
  26038. }
  26039. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26040. ProxyAndTargetServers s;
  26041. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26042. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26043. cli.set_proxy("127.0.0.1", s.proxy_port());
  26044. cli.set_no_proxy({"::1"});
  26045. auto res = cli.Get("/");
  26046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26047. EXPECT_EQ(0, s.proxy_hits());
  26048. EXPECT_EQ(1, s.target_hits());
  26049. }
  26050. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26051. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26052. // must still be recognized as IPv6 for CIDR matching. Implementations
  26053. // that detect IPv6 only when the host begins with '[' would parse the
  26054. // host as a hostname and miss the match.
  26055. ProxyAndTargetServers s;
  26056. Client cli("fe80::1", s.target_port());
  26057. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26058. cli.set_proxy("127.0.0.1", s.proxy_port());
  26059. cli.set_no_proxy({"fe80::/10"});
  26060. auto res = cli.Get("/");
  26061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26062. EXPECT_EQ(0, s.proxy_hits());
  26063. EXPECT_EQ(1, s.target_hits());
  26064. }
  26065. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26066. ProxyAndTargetServers s;
  26067. Client cli("::1", s.target_port());
  26068. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  26069. cli.set_proxy("127.0.0.1", s.proxy_port());
  26070. cli.set_no_proxy({"[::1]"});
  26071. auto res = cli.Get("/");
  26072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26073. EXPECT_EQ(0, s.proxy_hits());
  26074. EXPECT_EQ(1, s.target_hits());
  26075. }
  26076. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26077. ProxyAndTargetServers s;
  26078. Client cli("fe80::1", s.target_port());
  26079. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26080. cli.set_proxy("127.0.0.1", s.proxy_port());
  26081. cli.set_no_proxy({"[fe80::]/10"});
  26082. auto res = cli.Get("/");
  26083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26084. EXPECT_EQ(0, s.proxy_hits());
  26085. EXPECT_EQ(1, s.target_hits());
  26086. }
  26087. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26088. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26089. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26090. // tricks via address-family conversion.
  26091. ProxyAndTargetServers s;
  26092. Client cli("::ffff:127.0.0.1", s.target_port());
  26093. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26094. cli.set_proxy("127.0.0.1", s.proxy_port());
  26095. cli.set_no_proxy({"127.0.0.1"});
  26096. auto res = cli.Get("/");
  26097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26098. EXPECT_GE(s.proxy_hits(), 1);
  26099. EXPECT_EQ(0, s.target_hits());
  26100. }
  26101. TEST(NoProxyTest, IPv4CidrMatch) {
  26102. ProxyAndTargetServers s;
  26103. Client cli("127.0.0.1", s.target_port());
  26104. cli.set_proxy("127.0.0.1", s.proxy_port());
  26105. cli.set_no_proxy({"127.0.0.0/8"});
  26106. auto res = cli.Get("/");
  26107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26108. EXPECT_EQ(0, s.proxy_hits());
  26109. EXPECT_EQ(1, s.target_hits());
  26110. }
  26111. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26112. ProxyAndTargetServers s;
  26113. Client cli("127.0.0.1", s.target_port());
  26114. cli.set_proxy("127.0.0.1", s.proxy_port());
  26115. cli.set_no_proxy({"10.0.0.0/8"});
  26116. auto res = cli.Get("/");
  26117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26118. EXPECT_GE(s.proxy_hits(), 1);
  26119. EXPECT_EQ(0, s.target_hits());
  26120. }
  26121. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26122. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26123. // IPv4 target matches.
  26124. ProxyAndTargetServers s;
  26125. Client cli("127.0.0.1", s.target_port());
  26126. cli.set_proxy("127.0.0.1", s.proxy_port());
  26127. cli.set_no_proxy({"0.0.0.0/0"});
  26128. auto res = cli.Get("/");
  26129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26130. EXPECT_EQ(0, s.proxy_hits());
  26131. EXPECT_EQ(1, s.target_hits());
  26132. }
  26133. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26134. ProxyAndTargetServers s;
  26135. Client cli("127.0.0.1", s.target_port());
  26136. cli.set_proxy("127.0.0.1", s.proxy_port());
  26137. cli.set_no_proxy({"127.0.0.1"});
  26138. auto res = cli.Get("/");
  26139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26140. EXPECT_EQ(0, s.proxy_hits());
  26141. EXPECT_EQ(1, s.target_hits());
  26142. }
  26143. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26144. ProxyAndTargetServers s;
  26145. Client cli("127.0.0.1", s.target_port());
  26146. cli.set_proxy("127.0.0.1", s.proxy_port());
  26147. cli.set_no_proxy({"127.0.0.0/33"});
  26148. auto res = cli.Get("/");
  26149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26150. EXPECT_GE(s.proxy_hits(), 1);
  26151. EXPECT_EQ(0, s.target_hits());
  26152. }
  26153. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26154. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26155. ProxyAndTargetServers s;
  26156. Client cli("127.0.0.1", s.target_port());
  26157. cli.set_proxy("127.0.0.1", s.proxy_port());
  26158. cli.set_no_proxy({"127.0.0.1/"});
  26159. auto res = cli.Get("/");
  26160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26161. EXPECT_GE(s.proxy_hits(), 1);
  26162. EXPECT_EQ(0, s.target_hits());
  26163. }
  26164. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26165. ProxyAndTargetServers s;
  26166. auto cli = make_client("internal.corp", s);
  26167. cli->set_proxy_basic_auth("u", "p");
  26168. cli->set_no_proxy({"internal.corp"});
  26169. auto res = cli->Get("/");
  26170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26171. EXPECT_EQ(1, s.target_hits());
  26172. EXPECT_EQ(0, s.proxy_hits());
  26173. EXPECT_FALSE(s.last_had_proxy_authz())
  26174. << "Proxy-Authorization must not be sent direct to the target";
  26175. }
  26176. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26177. ProxyAndTargetServers s;
  26178. auto cli = make_client("public.example", s);
  26179. cli->set_proxy_basic_auth("u", "p");
  26180. cli->set_no_proxy({"internal.corp"}); // does not match
  26181. auto res = cli->Get("/");
  26182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26183. EXPECT_GE(s.proxy_hits(), 1);
  26184. EXPECT_TRUE(s.last_had_proxy_authz());
  26185. }
  26186. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26187. std::atomic<int> hits{0};
  26188. std::atomic<int> hits_with_authz{0};
  26189. no_proxy_test::ScopedServer proxy_mock;
  26190. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26191. hits++;
  26192. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26193. if (req.target.find("/redir") != std::string::npos) {
  26194. res.set_redirect("http://other.example/landed");
  26195. } else {
  26196. res.set_content("via-proxy", "text/plain");
  26197. }
  26198. });
  26199. proxy_mock.listen();
  26200. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26201. hits = 0;
  26202. hits_with_authz = 0;
  26203. Client cli("public.example", 80);
  26204. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26205. cli.set_proxy_basic_auth(c.first, c.second);
  26206. cli.set_follow_location(true);
  26207. // The redirect to another host goes through the proxy as well
  26208. auto res = cli.Get("/redir");
  26209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26210. EXPECT_EQ(2, hits.load());
  26211. EXPECT_EQ(2, hits_with_authz.load());
  26212. }
  26213. }
  26214. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26215. ProxyAndTargetServers s;
  26216. auto cli = make_client("anything.test", s);
  26217. auto res = cli->Get("/");
  26218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26219. EXPECT_GE(s.proxy_hits(), 1);
  26220. EXPECT_EQ(0, s.target_hits());
  26221. }
  26222. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26223. ProxyAndTargetServers s;
  26224. auto cli = make_client("example.com", s);
  26225. cli->set_no_proxy({"example.com:8080"});
  26226. auto res = cli->Get("/");
  26227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26228. EXPECT_GE(s.proxy_hits(), 1);
  26229. EXPECT_EQ(0, s.target_hits());
  26230. }
  26231. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26232. ProxyAndTargetServers s;
  26233. auto cli = make_client("anything.test", s);
  26234. cli->set_no_proxy({"", " ", "\t"});
  26235. auto res = cli->Get("/");
  26236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26237. EXPECT_GE(s.proxy_hits(), 1);
  26238. EXPECT_EQ(0, s.target_hits());
  26239. }
  26240. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26241. // An entry with leading/trailing whitespace must still match — env-style
  26242. // values are commonly pasted with stray spaces and an implementation
  26243. // that feeds the raw token directly to inet_pton would fail to match
  26244. // valid CIDRs because of the spaces.
  26245. ProxyAndTargetServers s;
  26246. Client cli("127.0.0.1", s.target_port());
  26247. cli.set_proxy("127.0.0.1", s.proxy_port());
  26248. cli.set_no_proxy({" 127.0.0.0/8 "});
  26249. auto res = cli.Get("/");
  26250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26251. EXPECT_EQ(0, s.proxy_hits());
  26252. EXPECT_EQ(1, s.target_hits());
  26253. }
  26254. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26255. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26256. // go direct and must NOT carry Proxy-Authorization.
  26257. std::atomic<int> proxy_hits{0};
  26258. std::atomic<int> target_hits{0};
  26259. std::atomic<bool> target_saw_authz{false};
  26260. no_proxy_test::ScopedServer proxy_mock, target;
  26261. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26262. proxy_hits++;
  26263. res.status = 302;
  26264. res.set_header("Location", "http://127.0.0.1:" +
  26265. std::to_string(target.port()) + "/landed");
  26266. });
  26267. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26268. target_hits++;
  26269. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26270. res.set_content("direct", "text/plain");
  26271. });
  26272. proxy_mock.listen();
  26273. target.listen();
  26274. Client cli("public.example", target.port());
  26275. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26276. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26277. cli.set_proxy_basic_auth("u", "p");
  26278. cli.set_no_proxy({"127.0.0.1"});
  26279. cli.set_follow_location(true);
  26280. auto res = cli.Get("/redir");
  26281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26282. EXPECT_GE(proxy_hits.load(), 1);
  26283. EXPECT_GE(target_hits.load(), 1);
  26284. EXPECT_FALSE(target_saw_authz.load());
  26285. }
  26286. #ifdef CPPHTTPLIB_SSL_ENABLED
  26287. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26288. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26289. // proxy creds would be sent to the (possibly hostile) origin.
  26290. std::atomic<int> target_hits{0};
  26291. std::atomic<bool> target_saw_proxy_authz{false};
  26292. no_proxy_test::ScopedServer target;
  26293. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26294. target_hits++;
  26295. if (req.has_header("Proxy-Authorization")) {
  26296. target_saw_proxy_authz = true;
  26297. }
  26298. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26299. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26300. "nonce=\"abc\", algorithm=MD5");
  26301. });
  26302. target.listen();
  26303. // The proxy address is set to the target's port: the bypass MUST kick in;
  26304. // if it doesn't, the test still routes "via proxy" to the same server and
  26305. // the Proxy-Authorization assertion below catches the leak.
  26306. Client cli("evil.example", target.port());
  26307. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26308. cli.set_proxy("127.0.0.1", target.port());
  26309. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26310. cli.set_no_proxy({"evil.example"});
  26311. auto res = cli.Get("/x");
  26312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26313. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26314. EXPECT_EQ(1, target_hits.load());
  26315. EXPECT_FALSE(target_saw_proxy_authz.load());
  26316. }
  26317. #endif
  26318. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26319. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26320. std::atomic<int> proxy_hits{0};
  26321. std::atomic<int> bypass_hits{0};
  26322. std::atomic<bool> proxy_saw_c_url{false};
  26323. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26324. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26325. proxy_hits++;
  26326. if (req.path.find("/start") != std::string::npos) {
  26327. res.status = 302;
  26328. res.set_header("Location", "http://127.0.0.1:" +
  26329. std::to_string(bypass_server.port()) +
  26330. "/middle");
  26331. return;
  26332. }
  26333. if (req.path.find("/end") != std::string::npos) {
  26334. proxy_saw_c_url = true;
  26335. res.set_content("c-via-proxy", "text/plain");
  26336. return;
  26337. }
  26338. res.set_content("unexpected", "text/plain");
  26339. });
  26340. // public.example's "advertised" port is arbitrary (the request never lands
  26341. // there — it goes through the proxy), but use a dynamic value to stay
  26342. // friendly with sharded parallel runs.
  26343. int public_port = bypass_server.port();
  26344. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26345. bypass_hits++;
  26346. res.status = 302;
  26347. res.set_header("Location", "http://public.example:" +
  26348. std::to_string(public_port) + "/end");
  26349. });
  26350. proxy_mock.listen();
  26351. bypass_server.listen();
  26352. Client cli("public.example", public_port);
  26353. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26354. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26355. cli.set_no_proxy({"127.0.0.1"});
  26356. cli.set_follow_location(true);
  26357. auto res = cli.Get("/start");
  26358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26359. EXPECT_EQ(StatusCode::OK_200, res->status);
  26360. EXPECT_EQ("c-via-proxy", res->body);
  26361. EXPECT_GE(proxy_hits.load(), 2);
  26362. EXPECT_GE(bypass_hits.load(), 1);
  26363. EXPECT_TRUE(proxy_saw_c_url.load());
  26364. }
  26365. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26366. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26367. // request reconnects to the correct endpoint.
  26368. std::atomic<int> proxy_hits{0};
  26369. std::atomic<int> target_hits{0};
  26370. no_proxy_test::ScopedServer proxy_mock, target;
  26371. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26372. proxy_hits++;
  26373. res.set_content("via-proxy", "text/plain");
  26374. });
  26375. target.svr().Get(".*", [&](const Request &, Response &res) {
  26376. target_hits++;
  26377. res.set_content("direct", "text/plain");
  26378. });
  26379. proxy_mock.listen();
  26380. target.listen();
  26381. Client cli("public.example", target.port());
  26382. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26383. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26384. cli.set_keep_alive(true);
  26385. auto res1 = cli.Get("/a");
  26386. ASSERT_TRUE(res1);
  26387. EXPECT_EQ("via-proxy", res1->body);
  26388. EXPECT_EQ(1, proxy_hits.load());
  26389. EXPECT_EQ(0, target_hits.load());
  26390. cli.set_no_proxy({"public.example"});
  26391. auto res2 = cli.Get("/b");
  26392. ASSERT_TRUE(res2);
  26393. EXPECT_EQ("direct", res2->body);
  26394. EXPECT_EQ(1, proxy_hits.load());
  26395. EXPECT_EQ(1, target_hits.load());
  26396. }
  26397. // Forward declarations (see the base64_encode note).
  26398. namespace httplib {
  26399. namespace detail {
  26400. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26401. int shutdown_socket(socket_t sock) noexcept;
  26402. } // namespace detail
  26403. } // namespace httplib
  26404. namespace proxy_tunnel_test {
  26405. const char *const kTunnelEstablished =
  26406. "HTTP/1.1 200 Connection established\r\n\r\n";
  26407. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26408. using ConnectReply = std::function<std::string(const std::string &head)>;
  26409. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26410. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26411. class ScopedConnectProxy {
  26412. public:
  26413. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26414. : forward_port_(forward_port), reply_(std::move(reply)) {
  26415. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26416. if (listen_sock_ == INVALID_SOCKET) { return; }
  26417. auto a = loopback(0);
  26418. auto addr = reinterpret_cast<sockaddr *>(&a);
  26419. socklen_t alen = sizeof(a);
  26420. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26421. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26422. ::listen(listen_sock_, 4) != 0) {
  26423. return;
  26424. }
  26425. port_ = ntohs(a.sin_port);
  26426. th_ = std::thread([this] { run(); });
  26427. }
  26428. ~ScopedConnectProxy() {
  26429. if (th_.joinable()) {
  26430. stop_ = true;
  26431. auto wake = connect_to(port_);
  26432. th_.join();
  26433. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26434. }
  26435. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26436. }
  26437. int port() const { return port_; }
  26438. int connect_hits() const { return connect_hits_.load(); }
  26439. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26440. std::string connect_request() const {
  26441. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26442. return connect_request_;
  26443. }
  26444. private:
  26445. static sockaddr_in loopback(int port) {
  26446. sockaddr_in a{};
  26447. a.sin_family = AF_INET;
  26448. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26449. a.sin_port = htons(static_cast<unsigned short>(port));
  26450. return a;
  26451. }
  26452. static socket_t connect_to(int port) {
  26453. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26454. if (sock == INVALID_SOCKET) { return sock; }
  26455. auto a = loopback(port);
  26456. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26457. detail::close_socket(sock);
  26458. return INVALID_SOCKET;
  26459. }
  26460. return sock;
  26461. }
  26462. static bool send_all(socket_t sock, const char *data, size_t size) {
  26463. while (size > 0) {
  26464. auto n = detail::send_socket(sock, data, size, 0);
  26465. if (n <= 0) { return false; }
  26466. data += n;
  26467. size -= static_cast<size_t>(n);
  26468. }
  26469. return true;
  26470. }
  26471. void run() {
  26472. for (;;) {
  26473. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26474. if (stop_) {
  26475. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26476. return;
  26477. }
  26478. if (client == INVALID_SOCKET) { continue; }
  26479. serve(client);
  26480. detail::close_socket(client);
  26481. }
  26482. }
  26483. void serve(socket_t client) {
  26484. std::string head;
  26485. char buf[2048];
  26486. while (head.find("\r\n\r\n") == std::string::npos) {
  26487. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26488. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26489. if (n <= 0) { return; }
  26490. head.append(buf, static_cast<size_t>(n));
  26491. }
  26492. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26493. connect_hits_++;
  26494. {
  26495. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26496. connect_request_ = head;
  26497. }
  26498. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26499. if (!send_all(client, res.data(), res.size()) ||
  26500. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26501. return;
  26502. }
  26503. auto origin = connect_to(forward_port_);
  26504. if (origin == INVALID_SOCKET) { return; }
  26505. // When either side stops, shut both down so the other pump returns too.
  26506. auto pump = [&](socket_t from, socket_t to) {
  26507. char b[8192];
  26508. for (;;) {
  26509. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26510. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26511. }
  26512. detail::shutdown_socket(client);
  26513. detail::shutdown_socket(origin);
  26514. };
  26515. std::thread up([&] { pump(client, origin); });
  26516. pump(origin, client);
  26517. up.join();
  26518. detail::close_socket(origin);
  26519. }
  26520. int forward_port_;
  26521. ConnectReply reply_;
  26522. socket_t listen_sock_ = INVALID_SOCKET;
  26523. int port_ = 0;
  26524. std::thread th_;
  26525. std::atomic<bool> stop_{false};
  26526. std::atomic<int> connect_hits_{0};
  26527. mutable std::mutex connect_request_mutex_;
  26528. std::string connect_request_;
  26529. };
  26530. } // namespace proxy_tunnel_test
  26531. #ifdef CPPHTTPLIB_SSL_ENABLED
  26532. namespace proxy_tunnel_test {
  26533. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26534. class ScopedSSLServer {
  26535. public:
  26536. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26537. port_ = svr_.bind_to_any_port("127.0.0.1");
  26538. }
  26539. ~ScopedSSLServer() {
  26540. svr_.stop();
  26541. if (th_.joinable()) { th_.join(); }
  26542. }
  26543. SSLServer &svr() { return svr_; }
  26544. int port() const { return port_; }
  26545. void listen() {
  26546. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26547. svr_.wait_until_ready();
  26548. }
  26549. private:
  26550. SSLServer svr_;
  26551. std::thread th_;
  26552. int port_ = 0;
  26553. };
  26554. // Sends one request through the CONNECT proxy to the TLS origin with a
  26555. // credential configured for each hop, and checks that each credential reaches
  26556. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26557. // origin's (every header in origin_headers) on the tunnelled request.
  26558. void CredentialsStayWithTheirHop(
  26559. const std::function<void(SSLClient &)> &set_credentials,
  26560. const std::string &scheme,
  26561. const std::vector<std::string> &origin_headers = {"Authorization"},
  26562. bool stream = false) {
  26563. std::atomic<int> origin_hits{0};
  26564. std::atomic<bool> origin_saw_proxy_authz{false};
  26565. std::atomic<bool> origin_saw_headers{false};
  26566. ScopedSSLServer origin;
  26567. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26568. origin_hits++;
  26569. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26570. origin_saw_headers =
  26571. std::all_of(origin_headers.begin(), origin_headers.end(),
  26572. [&](const std::string &h) { return req.has_header(h); });
  26573. res.set_content("ok", "text/plain");
  26574. });
  26575. origin.listen();
  26576. ScopedConnectProxy proxy(origin.port());
  26577. ASSERT_NE(0, proxy.port());
  26578. // Pinned to 127.0.0.1 for the same reason as the test below.
  26579. SSLClient cli("127.0.0.1", origin.port());
  26580. cli.enable_server_certificate_verification(false);
  26581. cli.set_proxy("127.0.0.1", proxy.port());
  26582. set_credentials(cli);
  26583. if (stream) {
  26584. auto handle = cli.open_stream("GET", "/x");
  26585. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26586. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26587. } else {
  26588. auto res = cli.Get("/x");
  26589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26590. EXPECT_EQ(StatusCode::OK_200, res->status);
  26591. }
  26592. EXPECT_EQ(1, origin_hits.load());
  26593. EXPECT_EQ(1, proxy.connect_hits());
  26594. EXPECT_TRUE(origin_saw_headers.load());
  26595. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26596. << "Proxy-Authorization must not be sent inside the tunnel";
  26597. auto connect_req = proxy.connect_request();
  26598. EXPECT_NE(std::string::npos,
  26599. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26600. for (const auto &h : origin_headers) {
  26601. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26602. << h << " must not be sent to the proxy on CONNECT";
  26603. }
  26604. }
  26605. } // namespace proxy_tunnel_test
  26606. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26607. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26608. [](SSLClient &cli) {
  26609. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26610. cli.set_basic_auth("origin-user", "origin-pass");
  26611. },
  26612. "Basic");
  26613. }
  26614. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26615. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26616. [](SSLClient &cli) {
  26617. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26618. cli.set_basic_auth("origin-user", "origin-pass");
  26619. },
  26620. "Basic", {"Authorization"}, true);
  26621. }
  26622. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26623. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26624. [](SSLClient &cli) {
  26625. cli.set_proxy_bearer_token_auth("proxy-token");
  26626. cli.set_bearer_token_auth("origin-token");
  26627. },
  26628. "Bearer");
  26629. }
  26630. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26631. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26632. [](SSLClient &cli) {
  26633. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26634. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26635. {"Cookie", "sid=origin-session"},
  26636. {"X-Api-Key", "origin-key"}});
  26637. },
  26638. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26639. }
  26640. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26641. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26642. // retry; otherwise proxy creds would be sent to the origin.
  26643. std::atomic<int> origin_hits{0};
  26644. std::atomic<bool> origin_saw_proxy_authz{false};
  26645. proxy_tunnel_test::ScopedSSLServer origin;
  26646. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26647. origin_hits++;
  26648. if (req.has_header("Proxy-Authorization")) {
  26649. origin_saw_proxy_authz = true;
  26650. }
  26651. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26652. res.set_header("Proxy-Authenticate",
  26653. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26654. "algorithm=MD5");
  26655. });
  26656. origin.listen();
  26657. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26658. ASSERT_NE(0, proxy.port());
  26659. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26660. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26661. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26662. // and answer with its own status, making this test flaky.
  26663. SSLClient cli("127.0.0.1", origin.port());
  26664. cli.enable_server_certificate_verification(false);
  26665. cli.set_proxy("127.0.0.1", proxy.port());
  26666. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26667. auto res = cli.Get("/x");
  26668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26669. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26670. EXPECT_EQ(1, origin_hits.load());
  26671. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26672. EXPECT_EQ(1, proxy.connect_hits());
  26673. }
  26674. #endif
  26675. namespace proxy_tunnel_test {
  26676. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26677. // anything else gets a 407 with `challenge`.
  26678. ConnectReply require_proxy_auth(const std::string &expected,
  26679. const std::string &challenge) {
  26680. return [=](const std::string &head) -> std::string {
  26681. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26682. std::string::npos) {
  26683. return kTunnelEstablished;
  26684. }
  26685. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26686. "Proxy-Authenticate: " +
  26687. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26688. };
  26689. }
  26690. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26691. // request, then echoes.
  26692. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26693. ws.send(
  26694. "authorization:" + req.get_header_value("Authorization") +
  26695. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26696. std::string msg;
  26697. while (ws.read(msg)) {
  26698. ws.send(msg);
  26699. }
  26700. }
  26701. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26702. class ScopedWebSocketOrigin {
  26703. public:
  26704. ScopedWebSocketOrigin() {
  26705. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26706. server_.listen();
  26707. }
  26708. int port() const { return server_.port(); }
  26709. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26710. std::string url() const {
  26711. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26712. }
  26713. private:
  26714. no_proxy_test::ScopedServer server_;
  26715. };
  26716. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26717. // passed as a constructor header, and checks that each reaches only its hop.
  26718. void WebSocketCredentialsStayWithTheirHop(
  26719. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26720. const std::string &proxy_authz, const std::string &origin_authz) {
  26721. ScopedWebSocketOrigin origin;
  26722. ScopedConnectProxy proxy(
  26723. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26724. ASSERT_NE(0, proxy.port());
  26725. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26726. client.set_proxy("127.0.0.1", proxy.port());
  26727. set_proxy_credentials(client);
  26728. auto res = client.connect();
  26729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26730. std::string msg;
  26731. ASSERT_TRUE(client.read(msg));
  26732. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26733. client.close();
  26734. EXPECT_EQ(1, proxy.connect_hits());
  26735. EXPECT_EQ(std::string::npos,
  26736. proxy.connect_request().find("\r\nAuthorization: "))
  26737. << "origin credentials must not be sent to the proxy";
  26738. }
  26739. } // namespace proxy_tunnel_test
  26740. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26741. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26742. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26743. ASSERT_NE(0, proxy.port());
  26744. ws::WebSocketClient client(origin.url());
  26745. client.set_proxy("127.0.0.1", proxy.port());
  26746. auto res = client.connect();
  26747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26748. std::string msg;
  26749. ASSERT_TRUE(client.read(msg));
  26750. ASSERT_TRUE(client.send("hello"));
  26751. ASSERT_TRUE(client.read(msg));
  26752. EXPECT_EQ("hello", msg);
  26753. client.close();
  26754. EXPECT_EQ(1, proxy.connect_hits());
  26755. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26756. auto connect_req = proxy.connect_request();
  26757. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26758. EXPECT_NE(std::string::npos,
  26759. connect_req.find("\r\nHost: " + target + "\r\n"));
  26760. }
  26761. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26762. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26763. [](ws::WebSocketClient &cli) {
  26764. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26765. },
  26766. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26767. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26768. }
  26769. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26770. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26771. [](ws::WebSocketClient &cli) {
  26772. cli.set_proxy_bearer_token_auth("proxy-token");
  26773. },
  26774. "Bearer proxy-token", "Bearer origin-token");
  26775. }
  26776. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26777. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26778. proxy_tunnel_test::ScopedConnectProxy proxy(
  26779. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26780. "Basic " + detail::base64_encode("proxy-user:"),
  26781. "Basic realm=\"proxy\""));
  26782. ASSERT_NE(0, proxy.port());
  26783. ws::WebSocketClient client(origin.url());
  26784. client.set_proxy("127.0.0.1", proxy.port());
  26785. client.set_proxy_basic_auth("proxy-user", "");
  26786. auto res = client.connect();
  26787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26788. client.close();
  26789. EXPECT_EQ(1, proxy.connect_hits());
  26790. }
  26791. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26792. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26793. proxy_tunnel_test::ScopedConnectProxy proxy(
  26794. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26795. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26796. ASSERT_NE(0, proxy.port());
  26797. ws::WebSocketClient client(origin.url());
  26798. client.set_proxy("127.0.0.1", proxy.port());
  26799. auto res = client.connect();
  26800. EXPECT_FALSE(res);
  26801. EXPECT_EQ(Error::ProxyConnection, res.error());
  26802. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26803. EXPECT_EQ("Basic realm=\"proxy\"",
  26804. res.get_header_value("Proxy-Authenticate"));
  26805. EXPECT_FALSE(client.is_open());
  26806. }
  26807. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26808. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26809. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26810. ASSERT_NE(0, proxy.port());
  26811. ws::WebSocketClient client(origin.url());
  26812. client.set_proxy("127.0.0.1", proxy.port());
  26813. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26814. client.set_no_proxy({"127.0.0.1"});
  26815. auto res = client.connect();
  26816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26817. std::string msg;
  26818. ASSERT_TRUE(client.read(msg));
  26819. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26820. << "proxy credentials must not reach a bypassed origin";
  26821. client.close();
  26822. EXPECT_EQ(0, proxy.connect_hits());
  26823. }
  26824. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26825. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26826. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26827. ASSERT_NE(0, proxy.port());
  26828. ws::WebSocketClient client(origin.url());
  26829. client.set_proxy("127.0.0.1", proxy.port());
  26830. ASSERT_TRUE(client.connect());
  26831. ASSERT_TRUE(client.connect());
  26832. client.close();
  26833. EXPECT_EQ(2, proxy.connect_hits());
  26834. }
  26835. #ifdef CPPHTTPLIB_SSL_ENABLED
  26836. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26837. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26838. proxy_tunnel_test::ScopedConnectProxy proxy(
  26839. origin.port(), [](const std::string &head) -> std::string {
  26840. if (head.find(
  26841. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26842. std::string::npos) {
  26843. return proxy_tunnel_test::kTunnelEstablished;
  26844. }
  26845. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26846. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26847. "nonce=\"abc\", algorithm=MD5\r\n"
  26848. "Content-Length: 0\r\n\r\n";
  26849. });
  26850. ASSERT_NE(0, proxy.port());
  26851. ws::WebSocketClient client(origin.url());
  26852. client.set_proxy("127.0.0.1", proxy.port());
  26853. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26854. auto res = client.connect();
  26855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26856. std::string msg;
  26857. ASSERT_TRUE(client.read(msg));
  26858. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26859. client.close();
  26860. EXPECT_EQ(2, proxy.connect_hits());
  26861. }
  26862. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26863. proxy_tunnel_test::ScopedSSLServer origin;
  26864. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26865. origin.listen();
  26866. proxy_tunnel_test::ScopedConnectProxy proxy(
  26867. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26868. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26869. ASSERT_NE(0, proxy.port());
  26870. ws::WebSocketClient client(
  26871. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26872. client.enable_server_certificate_verification(false);
  26873. client.set_proxy("127.0.0.1", proxy.port());
  26874. client.set_proxy_bearer_token_auth("proxy-token");
  26875. auto res = client.connect();
  26876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26877. std::string msg;
  26878. ASSERT_TRUE(client.read(msg));
  26879. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26880. << "Proxy-Authorization must not be sent inside the tunnel";
  26881. client.close();
  26882. EXPECT_EQ(1, proxy.connect_hits());
  26883. }
  26884. #endif