1
0

test.cc 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  253. // Another socket in the working directory, which a Location can name as
  254. // its host
  255. const auto other_path = "other-" + pathname_.substr(2);
  256. httplib::Server svr;
  257. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  258. // An absolute Location naming the Host this client sends
  259. res.set_redirect("http://localhost" + pattern_);
  260. });
  261. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  262. res.set_redirect("http://" + other_path + pattern_);
  263. });
  264. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  265. res.set_redirect("http://mapped.test" + pattern_);
  266. });
  267. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  268. res.set_header("X-Auth", req.get_header_value("Authorization"));
  269. res.set_content(content_, "text/plain");
  270. });
  271. httplib::Server other;
  272. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  273. res.set_content("other", "text/plain");
  274. });
  275. std::thread t{[&] {
  276. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  277. }};
  278. std::thread t2{[&] {
  279. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  280. }};
  281. auto se = detail::scope_exit([&] {
  282. svr.stop();
  283. other.stop();
  284. t.join();
  285. t2.join();
  286. std::remove(other_path.c_str());
  287. });
  288. svr.wait_until_ready();
  289. other.wait_until_ready();
  290. httplib::Client cli{pathname_};
  291. cli.set_address_family(AF_UNIX);
  292. cli.set_follow_location(true);
  293. cli.set_bearer_token_auth("token");
  294. // Another host: the same socket, without the credentials
  295. auto res = cli.Get("/cross");
  296. ASSERT_TRUE(res) << "error: " << res.error();
  297. EXPECT_EQ(StatusCode::OK_200, res->status);
  298. EXPECT_EQ(content_, res->body);
  299. EXPECT_EQ("", res->get_header_value("X-Auth"));
  300. // localhost is this client's own host
  301. res = cli.Get("/redirect");
  302. ASSERT_TRUE(res) << "error: " << res.error();
  303. EXPECT_EQ(StatusCode::OK_200, res->status);
  304. EXPECT_EQ(content_, res->body);
  305. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  306. // A host the caller mapped to a socket goes there
  307. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  308. res = cli.Get("/mapped");
  309. ASSERT_TRUE(res) << "error: " << res.error();
  310. EXPECT_EQ(StatusCode::OK_200, res->status);
  311. EXPECT_EQ("other", res->body);
  312. }
  313. #ifndef _WIN32
  314. TEST(SocketStream, wait_writable_UNIX) {
  315. int fds[2];
  316. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  317. const auto asSocketStream = [&](socket_t fd,
  318. std::function<bool(Stream &)> func) {
  319. return detail::process_client_socket(
  320. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  321. };
  322. asSocketStream(fds[0], [&](Stream &s0) {
  323. EXPECT_EQ(s0.socket(), fds[0]);
  324. EXPECT_TRUE(s0.wait_writable());
  325. EXPECT_TRUE(s0.is_peer_alive());
  326. EXPECT_EQ(0, close(fds[1]));
  327. EXPECT_FALSE(s0.is_peer_alive());
  328. return true;
  329. });
  330. EXPECT_EQ(0, close(fds[0]));
  331. }
  332. TEST(SocketStream, wait_writable_INET) {
  333. sockaddr_in addr;
  334. memset(&addr, 0, sizeof(addr));
  335. addr.sin_family = AF_INET;
  336. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  337. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  338. int disconnected_svr_sock = -1;
  339. std::thread svr{[&] {
  340. const int s = socket(AF_INET, SOCK_STREAM, 0);
  341. ASSERT_LE(0, s);
  342. // PORT + 1 is shared with the SSL redirect tests and with
  343. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  344. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  345. // because that happens on a worker thread the ASSERT does not stop the
  346. // test: it runs on and fails at the disconnected_svr_sock check instead.
  347. default_socket_options(s);
  348. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  349. ASSERT_EQ(0, listen(s, 1));
  350. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  351. ASSERT_EQ(0, close(s));
  352. }};
  353. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  354. std::thread cli{[&] {
  355. const int s = socket(AF_INET, SOCK_STREAM, 0);
  356. ASSERT_LE(0, s);
  357. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  358. ASSERT_EQ(0, close(s));
  359. }};
  360. cli.join();
  361. svr.join();
  362. ASSERT_NE(disconnected_svr_sock, -1);
  363. const auto asSocketStream = [&](socket_t fd,
  364. std::function<bool(Stream &)> func) {
  365. return detail::process_client_socket(
  366. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  367. };
  368. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  369. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  370. // wait_writable() returns true because select_write() only checks if the
  371. // send buffer has space. Peer disconnection is detected later by send().
  372. EXPECT_TRUE(ss.wait_writable());
  373. return true;
  374. });
  375. ASSERT_EQ(0, close(disconnected_svr_sock));
  376. }
  377. #endif // #ifndef _WIN32
  378. TEST(SetSocketOptTest, TcpNoDelay) {
  379. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  380. ASSERT_NE(sock, INVALID_SOCKET);
  381. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  382. int val = 0;
  383. socklen_t len = sizeof(val);
  384. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  385. reinterpret_cast<char *>(&val), &len));
  386. EXPECT_NE(val, 0);
  387. detail::close_socket(sock);
  388. }
  389. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  390. // accept() reports failures through WSAGetLastError() on Windows and through
  391. // errno everywhere else. Asking the wrong one is what made the accept loop
  392. // treat every recoverable failure as fatal on Windows.
  393. struct Classification {
  394. bool resource;
  395. bool transient;
  396. };
  397. auto classify = [](int err) {
  398. #ifdef _WIN32
  399. WSASetLastError(err);
  400. #else
  401. errno = err;
  402. #endif
  403. // Read both before asserting: an assertion may clobber the error slot.
  404. Classification c;
  405. c.resource = detail::is_accept_resource_error();
  406. c.transient = detail::is_accept_transient_error();
  407. return c;
  408. };
  409. #ifdef _WIN32
  410. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  411. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  412. WSAECONNRESET, WSAECONNABORTED};
  413. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  414. #else
  415. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  416. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  417. ECONNABORTED};
  418. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  419. #endif
  420. for (auto err : resource_errors) {
  421. const auto c = classify(err);
  422. EXPECT_TRUE(c.resource) << "error " << err;
  423. EXPECT_FALSE(c.transient) << "error " << err;
  424. }
  425. for (auto err : transient_errors) {
  426. const auto c = classify(err);
  427. EXPECT_TRUE(c.transient) << "error " << err;
  428. EXPECT_FALSE(c.resource) << "error " << err;
  429. }
  430. for (auto err : fatal_errors) {
  431. const auto c = classify(err);
  432. EXPECT_FALSE(c.resource) << "error " << err;
  433. EXPECT_FALSE(c.transient) << "error " << err;
  434. }
  435. #ifdef _WIN32
  436. WSASetLastError(0);
  437. #else
  438. errno = 0;
  439. #endif
  440. }
  441. TEST(ClientTest, MoveConstructible) {
  442. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  443. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  444. }
  445. TEST(ClientTest, MoveAssignable) {
  446. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  447. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  448. }
  449. #ifdef _WIN32
  450. TEST(StartupTest, WSAStartup) {
  451. WSADATA wsaData;
  452. int ret = WSAStartup(0x0002, &wsaData);
  453. ASSERT_EQ(0, ret);
  454. }
  455. #endif
  456. TEST(DecodePathTest, PercentCharacter) {
  457. EXPECT_EQ(
  458. decode_path_component(
  459. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  460. U8("descrip=Gastos áéíóúñÑ 6"));
  461. }
  462. TEST(DecodePathTest, PercentCharacterNUL) {
  463. string expected;
  464. expected.push_back('x');
  465. expected.push_back('\0');
  466. expected.push_back('x');
  467. EXPECT_EQ(decode_path_component("x%00x"), expected);
  468. }
  469. TEST(DecodePathTest, UnicodeEncoding) {
  470. // %u0041 = 'A' (1-byte UTF-8)
  471. EXPECT_EQ("A", decode_path_component("%u0041"));
  472. // %u00E9 = 'é' (2-byte UTF-8)
  473. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  474. // %u3042 = 'あ' (3-byte UTF-8)
  475. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  476. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  477. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  478. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  479. // neighbours)
  480. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  481. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  482. }
  483. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  484. // A sign or whitespace inside the two-character escape window must not be
  485. // accepted as a valid percent-encoding; the sequence is passed through
  486. // literally, matching decode_uri_component / decode_path_component.
  487. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  488. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  489. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  490. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  491. // Well-formed escapes still decode.
  492. EXPECT_EQ("-", decode_query_component("%2D", false));
  493. EXPECT_EQ("A", decode_query_component("%41", false));
  494. }
  495. TEST(SanitizeFilenameTest, VariousPatterns) {
  496. // Path traversal
  497. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  498. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  499. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  500. // Normal and edge cases
  501. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  502. EXPECT_EQ("filename.txt",
  503. httplib::sanitize_filename("/path/to/filename.txt"));
  504. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  505. EXPECT_EQ("", httplib::sanitize_filename(".."));
  506. EXPECT_EQ("", httplib::sanitize_filename(""));
  507. // Null bytes stripped
  508. EXPECT_EQ("safe.txt",
  509. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  510. // Whitespace-only rejected
  511. EXPECT_EQ("", httplib::sanitize_filename(" "));
  512. }
  513. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  514. // before it is dropped; anywhere else it is an ordinary file name character.
  515. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  516. #ifdef _WIN32
  517. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  518. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  519. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  520. #else
  521. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  522. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  523. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  524. #endif
  525. }
  526. // Forward declaration (see the base64_encode note below): split builds move the
  527. // definition into httplib.cc, so re-declaring it here lets the test link.
  528. namespace httplib {
  529. namespace detail {
  530. bool is_chunked_transfer_encoding(const Headers &headers);
  531. } // namespace detail
  532. } // namespace httplib
  533. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  534. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  535. auto make = [](std::initializer_list<const char *> lines) {
  536. Headers h;
  537. for (auto te : lines) {
  538. if (te) { h.emplace("Transfer-Encoding", te); }
  539. }
  540. return h;
  541. };
  542. // Sole coding, matched case-insensitively.
  543. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  544. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  545. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  546. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  547. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  548. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  549. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  550. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  551. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  552. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  553. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  554. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  555. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  556. // were received, into one list. Headers preserves that order, so the answer
  557. // is decided by the last coding of the last line and the order the lines
  558. // arrived in is significant.
  559. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  560. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  561. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  562. // The split can fall anywhere in the list.
  563. EXPECT_TRUE(
  564. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  565. EXPECT_FALSE(
  566. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  567. // A trailing line naming no coding leaves the list ending in nothing, so it
  568. // must not inherit the chunked from the line before it.
  569. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  570. }
  571. // Forward declarations (see the base64_encode note below).
  572. namespace httplib {
  573. namespace detail {
  574. bool parse_status_line(const char *line, std::string &version, int &status,
  575. std::string &reason);
  576. std::string file_extension(const std::string &path);
  577. std::string
  578. find_content_type(const std::string &path,
  579. const std::map<std::string, std::string> &user_data,
  580. const std::string &default_content_type);
  581. bool can_compress_content_type(const std::string &content_type);
  582. bool is_prohibited_header_name(const std::string &name);
  583. bool is_valid_path(const std::string &path);
  584. #ifdef CPPHTTPLIB_SSL_ENABLED
  585. bool match_hostname(const std::string &pattern, const std::string &hostname);
  586. #endif
  587. } // namespace detail
  588. } // namespace httplib
  589. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  590. struct {
  591. const char *line;
  592. const char *version;
  593. int status;
  594. const char *reason;
  595. } cases[] = {
  596. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  597. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  598. // The reason phrase may be empty, or left out along with its space.
  599. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  600. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  601. };
  602. for (const auto &c : cases) {
  603. std::string version;
  604. int status = 0;
  605. std::string reason = "unset";
  606. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  607. << c.line;
  608. EXPECT_EQ(c.version, version);
  609. EXPECT_EQ(c.status, status);
  610. EXPECT_EQ(c.reason, reason);
  611. }
  612. }
  613. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  614. const char *lines[] = {
  615. "HTTP/2 200 OK\r\n",
  616. "HTTP/1.2 200 OK\r\n",
  617. "HTTP/1.1 20 OK\r\n",
  618. "HTTP/1.1 2000 OK\r\n",
  619. "HTTP/1.1 2x0 OK\r\n",
  620. "HTTP/1.1 200 OK\r\n",
  621. "HTTP/1.1 200OK\r\n",
  622. "HTTP/1.1 200 O\rK\r\n",
  623. "HTTP/1.1 200 OK",
  624. "HTTP/1.1 200 OK\r\nX",
  625. "",
  626. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  627. "HTTP/1.1 200 OK\n",
  628. #endif
  629. };
  630. for (auto line : lines) {
  631. std::string version;
  632. int status = 0;
  633. std::string reason;
  634. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  635. << line;
  636. }
  637. }
  638. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  639. // Long enough to overflow the stack when matched with std::regex.
  640. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  641. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  642. std::string version;
  643. int status = 0;
  644. std::string reason;
  645. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  646. EXPECT_EQ(200, status);
  647. EXPECT_EQ(long_reason, reason);
  648. }
  649. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  650. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  651. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  652. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  653. EXPECT_EQ("", detail::file_extension("noext"));
  654. EXPECT_EQ("", detail::file_extension("a."));
  655. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  656. EXPECT_EQ("", detail::file_extension("a.b-c"));
  657. // Long enough to overflow the stack when matched with std::regex.
  658. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  659. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  660. }
  661. #ifdef CPPHTTPLIB_SSL_ENABLED
  662. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  663. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  664. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  665. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  666. // A wildcard needs two labels after it, in the leftmost label only
  667. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  668. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  669. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  670. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  671. EXPECT_FALSE(
  672. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  673. // No name may have an empty label
  674. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  675. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  676. }
  677. #endif
  678. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  679. detail::case_ignore::hash hash;
  680. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  681. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  682. // Long enough to overflow the stack if hashed one call per character.
  683. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  684. }
  685. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  686. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  687. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  688. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  689. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  690. // Same 26-bit hash as html, svg and js.
  691. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  692. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  693. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  694. }
  695. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  696. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  697. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  698. }
  699. }
  700. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  701. // name anywhere else.
  702. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  703. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  704. #ifdef _WIN32
  705. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  706. #else
  707. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  708. #endif
  709. }
  710. }
  711. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  712. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  713. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  714. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  715. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  716. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  717. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  718. // Same 26-bit hash as application/json.
  719. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  720. }
  721. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  722. Request req;
  723. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  724. EXPECT_TRUE(req.is_multipart_form_data());
  725. std::string boundary;
  726. EXPECT_TRUE(detail::parse_multipart_boundary(
  727. req.get_header_value("Content-Type"), boundary));
  728. EXPECT_EQ("x", boundary);
  729. }
  730. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  731. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  732. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  733. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  734. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  735. // Same 26-bit hash as REMOTE_ADDR.
  736. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  737. }
  738. // Forward declaration: in split builds split.py strips `inline` and moves the
  739. // definition into httplib.cc, so detail::base64_encode is not visible from the
  740. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  741. // in both header-only and split builds.
  742. namespace httplib {
  743. namespace detail {
  744. std::string base64_encode(const std::string &in);
  745. } // namespace detail
  746. } // namespace httplib
  747. TEST(Base64EncodeTest, KnownAnswers) {
  748. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  749. // where the accumulator's top bit is already set before the next shift.
  750. EXPECT_EQ("", detail::base64_encode(""));
  751. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  752. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  753. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  754. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  755. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  756. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  757. // High bytes keep the top bit set across several rounds.
  758. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  759. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  760. }
  761. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  762. string unescapedCharacters = "-_.!~*'()";
  763. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  764. }
  765. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  766. string reservedCharacters = ";,/?:@&=+$";
  767. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  768. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  769. }
  770. TEST(ClientQueryOrder, PreserveOrder) {
  771. // This test reproduces Issue #2259: client may reorder query parameters
  772. // when sending a GET request. The expected behavior is that the client
  773. // preserves the original query string order when the caller supplied it
  774. // as part of the path.
  775. Server svr;
  776. svr.Get("/", [&](const Request &req, Response &res) {
  777. // Echo back the raw target so the test can assert ordering
  778. res.set_content(req.target, "text/plain");
  779. });
  780. std::thread t{[&] { svr.listen(HOST, PORT); }};
  781. auto se = detail::scope_exit([&] {
  782. svr.stop();
  783. t.join();
  784. ASSERT_FALSE(svr.is_running());
  785. });
  786. svr.wait_until_ready();
  787. Client cli(HOST, PORT);
  788. ASSERT_TRUE(cli.is_valid());
  789. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  790. auto res = cli.Get(original);
  791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  792. // Expect the echoed target to exactly match the original path (order
  793. // preserved)
  794. EXPECT_EQ(res->body, original);
  795. }
  796. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  797. string chineseCharacters = U8("中国語");
  798. string russianCharacters = U8("дом");
  799. string brazilianCharacters = U8("óculos");
  800. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  801. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  802. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  803. "%D0%B4%D0%BE%D0%BC");
  804. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  805. }
  806. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  807. string unescapedCharacters = "-_.!~*'()";
  808. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  809. }
  810. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  811. string reservedCharacters = ";,/?:@&=+$";
  812. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  813. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  814. }
  815. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  816. string chineseCharacters = U8("中国語");
  817. string russianCharacters = U8("дом");
  818. string brazilianCharacters = U8("óculos");
  819. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  820. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  821. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  822. "%D0%B4%D0%BE%D0%BC");
  823. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  824. }
  825. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  826. // Issue #2082 use case: encoding path component with ampersand
  827. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  828. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  829. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  830. }
  831. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  832. string unescapedCharacters = "-_.!~*'()";
  833. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  834. }
  835. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  836. string reservedCharacters = ";,/?:@&=+$#";
  837. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  838. }
  839. TEST(EncodeUriTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  846. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  847. }
  848. TEST(EncodeUriTest, TestCompleteUri) {
  849. string uri =
  850. "https://example.com/path/to/resource?query=value&param=test#fragment";
  851. EXPECT_EQ(
  852. httplib::encode_uri(uri),
  853. "https://example.com/path/to/resource?query=value&param=test#fragment");
  854. }
  855. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  856. string uri =
  857. "https://example.com/path with spaces/file name.html?q=hello world";
  858. EXPECT_EQ(httplib::encode_uri(uri),
  859. "https://example.com/path%20with%20spaces/"
  860. "file%20name.html?q=hello%20world");
  861. }
  862. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  863. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  864. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  865. }
  866. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  867. string unescapedCharacters = "-_.!~*'()";
  868. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  869. }
  870. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  871. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  872. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  873. string encodedBrazilian = "%C3%B3culos";
  874. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  875. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  876. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  877. }
  878. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  879. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  880. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  881. "Piri Tommy Villiers - on & on");
  882. }
  883. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  884. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  885. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  886. }
  887. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  888. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  889. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  890. }
  891. TEST(DecodeUriTest, TestUTF8Characters) {
  892. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  893. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  894. string encodedBrazilian = "%C3%B3culos";
  895. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  896. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  897. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  898. }
  899. TEST(DecodeUriTest, TestCompleteUri) {
  900. string encodedUri = "https://example.com/path%20with%20spaces/"
  901. "file%20name.html?q=hello%20world";
  902. EXPECT_EQ(
  903. httplib::decode_uri(encodedUri),
  904. "https://example.com/path with spaces/file name.html?q=hello world");
  905. }
  906. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  907. string original =
  908. "https://example.com/path with spaces/file name.html?q=hello world";
  909. string encoded = httplib::encode_uri(original);
  910. string decoded = httplib::decode_uri(encoded);
  911. EXPECT_EQ(decoded, original);
  912. }
  913. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  914. // decode_uri is the inverse of encode_uri: an escaped reserved character
  915. // stays encoded so it is not promoted into a real delimiter, while
  916. // non-reserved escapes still decode (like JS decodeURI).
  917. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  918. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  919. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  920. "%3F%3A%40%26%3D%2B%24%2C%3B");
  921. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  922. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  923. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  924. "http://example.com/a%2Fb");
  925. // decode_uri_component still decodes the reserved character.
  926. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  927. }
  928. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  929. string original = "Piri Tommy Villiers - on & on";
  930. string encoded = httplib::encode_uri_component(original);
  931. string decoded = httplib::decode_uri_component(encoded);
  932. EXPECT_EQ(decoded, original);
  933. }
  934. TEST(TrimTests, TrimStringTests) {
  935. EXPECT_EQ("abc", detail::trim_copy("abc"));
  936. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  937. EXPECT_TRUE(detail::trim_copy("").empty());
  938. }
  939. TEST(AsciiTest, LocaleIndependentClassification) {
  940. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  941. // which consult the global C locale: std::isalnum(0xC5) can return true
  942. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  943. // helpers must classify every byte by the ASCII grammar alone.
  944. for (int i = 0; i < 256; i++) {
  945. auto c = static_cast<char>(i);
  946. auto is_digit = i >= '0' && i <= '9';
  947. auto is_upper = i >= 'A' && i <= 'Z';
  948. auto is_lower = i >= 'a' && i <= 'z';
  949. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  950. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  951. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  952. << "byte " << i;
  953. }
  954. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  955. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  956. // Non-ASCII bytes must be percent-encoded, never passed through as
  957. // alphanumeric.
  958. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  959. }
  960. TEST(FromCharsTest, Double) {
  961. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  962. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  963. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  964. auto parse = [](const std::string &s, double &v) {
  965. return detail::from_chars(s.data(), s.data() + s.size(), v);
  966. };
  967. double v = -1.0;
  968. // Representative quality values.
  969. EXPECT_EQ(parse("0", v).ec, std::errc{});
  970. EXPECT_DOUBLE_EQ(v, 0.0);
  971. EXPECT_EQ(parse("1", v).ec, std::errc{});
  972. EXPECT_DOUBLE_EQ(v, 1.0);
  973. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  974. EXPECT_DOUBLE_EQ(v, 0.8);
  975. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  976. EXPECT_DOUBLE_EQ(v, 0.001);
  977. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  978. EXPECT_DOUBLE_EQ(v, 1.0);
  979. // A missing integer or fractional part is tolerated.
  980. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  981. EXPECT_DOUBLE_EQ(v, 0.5);
  982. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  983. EXPECT_DOUBLE_EQ(v, 5.0);
  984. // Values outside [0, 1] still parse; the caller range-checks them.
  985. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  986. EXPECT_DOUBLE_EQ(v, 123.456);
  987. // Stops at the first byte that is not part of the number and reports where.
  988. std::string trailing = "0.9, text/html";
  989. auto r = parse(trailing, v);
  990. EXPECT_EQ(r.ec, std::errc{});
  991. EXPECT_DOUBLE_EQ(v, 0.9);
  992. EXPECT_EQ(*r.ptr, ',');
  993. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  994. // outright, and an 'e'/'E' simply ends the number.
  995. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  996. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  997. std::string exp_input = "1.5e3";
  998. r = parse(exp_input, v);
  999. EXPECT_EQ(r.ec, std::errc{});
  1000. EXPECT_DOUBLE_EQ(v, 1.5);
  1001. EXPECT_EQ(*r.ptr, 'e');
  1002. // Invalid inputs.
  1003. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1004. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1005. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1006. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1007. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1008. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1009. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1010. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1011. std::errc{});
  1012. EXPECT_DOUBLE_EQ(v, 0.0);
  1013. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1014. std::errc{});
  1015. EXPECT_GE(v, 0.0);
  1016. EXPECT_LE(v, 1.0);
  1017. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1018. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1019. }
  1020. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1021. // Simple case without quality values
  1022. std::vector<std::string> result1;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "text/html,application/json,text/plain", result1));
  1025. EXPECT_EQ(result1.size(), 3U);
  1026. EXPECT_EQ(result1[0], "text/html");
  1027. EXPECT_EQ(result1[1], "application/json");
  1028. EXPECT_EQ(result1[2], "text/plain");
  1029. // With quality values
  1030. std::vector<std::string> result2;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1033. EXPECT_EQ(result2.size(), 3U);
  1034. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1035. EXPECT_EQ(result2[1], "text/html");
  1036. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1037. }
  1038. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1039. // Mixed with and without quality values
  1040. std::vector<std::string> result;
  1041. EXPECT_TRUE(detail::parse_accept_header(
  1042. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1043. EXPECT_EQ(result.size(), 3U);
  1044. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1045. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1046. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1047. }
  1048. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1049. // Empty header
  1050. std::vector<std::string> empty_result;
  1051. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1052. EXPECT_TRUE(empty_result.empty());
  1053. // Single type
  1054. std::vector<std::string> single_result;
  1055. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1056. EXPECT_EQ(single_result.size(), 1U);
  1057. EXPECT_EQ(single_result[0], "application/json");
  1058. // Wildcard types
  1059. std::vector<std::string> wildcard_result;
  1060. EXPECT_TRUE(detail::parse_accept_header(
  1061. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1062. EXPECT_EQ(wildcard_result.size(), 3U);
  1063. EXPECT_EQ(wildcard_result[0], "application/json");
  1064. EXPECT_EQ(wildcard_result[1], "text/*");
  1065. EXPECT_EQ(wildcard_result[2], "*/*");
  1066. }
  1067. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1068. // Common browser Accept header
  1069. std::vector<std::string> browser_result;
  1070. EXPECT_TRUE(
  1071. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1072. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1073. browser_result));
  1074. EXPECT_EQ(browser_result.size(), 6U);
  1075. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1076. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1077. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1078. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1079. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1080. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1081. // API client header
  1082. std::vector<std::string> api_result;
  1083. EXPECT_TRUE(detail::parse_accept_header(
  1084. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1085. api_result));
  1086. EXPECT_EQ(api_result.size(), 3U);
  1087. EXPECT_EQ(api_result[0], "application/json");
  1088. EXPECT_EQ(api_result[1], "application/xml");
  1089. EXPECT_EQ(api_result[2], "text/plain");
  1090. }
  1091. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1092. // Quality value with 3 decimal places
  1093. std::vector<std::string> decimal_result;
  1094. EXPECT_TRUE(detail::parse_accept_header(
  1095. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1096. EXPECT_EQ(decimal_result.size(), 2U);
  1097. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1098. EXPECT_EQ(decimal_result[1], "text/html");
  1099. // Zero quality (should still be included but with lowest priority)
  1100. std::vector<std::string> zero_q_result;
  1101. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1102. zero_q_result));
  1103. EXPECT_EQ(zero_q_result.size(), 2U);
  1104. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1105. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1106. // No spaces around commas
  1107. std::vector<std::string> no_space_result;
  1108. EXPECT_TRUE(detail::parse_accept_header(
  1109. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1110. no_space_result));
  1111. EXPECT_EQ(no_space_result.size(), 3U);
  1112. EXPECT_EQ(no_space_result[0], "text/html");
  1113. EXPECT_EQ(no_space_result[1], "application/json");
  1114. EXPECT_EQ(no_space_result[2], "text/plain");
  1115. }
  1116. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1117. // Quality values always use '.' as the decimal separator, so parsing must
  1118. // not depend on the process locale. An embedding application may have
  1119. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1120. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1121. std::string saved = cur ? cur : "C";
  1122. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1123. "fr_FR.UTF-8"};
  1124. bool switched = false;
  1125. for (const auto loc : comma_locales) {
  1126. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1127. std::localeconv()->decimal_point[0] == ',') {
  1128. switched = true;
  1129. break;
  1130. }
  1131. }
  1132. if (!switched) {
  1133. std::setlocale(LC_NUMERIC, saved.c_str());
  1134. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1135. }
  1136. // The higher-weighted type appears later in the list, so a correct parse
  1137. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1138. // sensitive parse reads both weights as 0 and leaves the original order.
  1139. std::vector<std::string> result;
  1140. EXPECT_TRUE(detail::parse_accept_header(
  1141. "application/json;q=0.1,text/html;q=0.9", result));
  1142. ASSERT_EQ(result.size(), 2U);
  1143. EXPECT_EQ(result[0], "text/html");
  1144. EXPECT_EQ(result[1], "application/json");
  1145. std::setlocale(LC_NUMERIC, saved.c_str());
  1146. }
  1147. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1148. std::vector<std::string> result;
  1149. // Invalid quality value (> 1.0)
  1150. EXPECT_FALSE(
  1151. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1152. // Invalid quality value (< 0.0)
  1153. EXPECT_FALSE(
  1154. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1155. // Invalid quality value (not a number)
  1156. EXPECT_FALSE(detail::parse_accept_header(
  1157. "text/html;q=invalid,application/json", result));
  1158. // A valid numeric prefix does not make the entire quality value valid.
  1159. EXPECT_FALSE(detail::parse_accept_header(
  1160. "text/html;q=0.5junk,application/json", result));
  1161. // Empty quality value
  1162. EXPECT_FALSE(
  1163. detail::parse_accept_header("text/html;q=,application/json", result));
  1164. // Invalid media type format (no slash and not wildcard)
  1165. EXPECT_FALSE(
  1166. detail::parse_accept_header("invalidtype,application/json", result));
  1167. // Valid cases should still work
  1168. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1169. EXPECT_EQ(result.size(), 1U);
  1170. EXPECT_EQ(result[0], "*/*");
  1171. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1172. EXPECT_EQ(result.size(), 1U);
  1173. EXPECT_EQ(result[0], "*");
  1174. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1175. EXPECT_EQ(result.size(), 1U);
  1176. EXPECT_EQ(result[0], "text/*");
  1177. }
  1178. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1179. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1180. // and must not be answered with 400 Bad Request.
  1181. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1182. struct {
  1183. const char *value;
  1184. std::vector<std::string> expected;
  1185. } cases[] = {
  1186. {",application/json", {"application/json"}},
  1187. {"text/html,", {"text/html"}},
  1188. {"text/html,,*/*", {"text/html", "*/*"}},
  1189. // An empty element may be spelled with whitespace in it
  1190. {"text/html, , application/json", {"text/html", "application/json"}},
  1191. // Nothing but empty elements is an empty list, which means the same
  1192. // thing as no Accept header at all
  1193. {",,,", {}},
  1194. // Quality values still apply across ignored empty elements
  1195. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1196. };
  1197. for (const auto &c : cases) {
  1198. std::vector<std::string> result;
  1199. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1200. << "value: " << c.value;
  1201. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1202. }
  1203. // An invalid entry is still rejected when empty elements surround it
  1204. std::vector<std::string> result;
  1205. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1206. }
  1207. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1208. // or ';' inside one does not end the list element or the parameter. Section
  1209. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1210. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1211. struct {
  1212. const char *value;
  1213. std::vector<std::string> expected;
  1214. } cases[] = {
  1215. {"text/html;profile=\"a,b\",application/json",
  1216. {"text/html", "application/json"}},
  1217. // A "q=" inside a quoted value is not the weight
  1218. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1219. {"text/html", "application/json"}},
  1220. // The weight after a quoted value still applies
  1221. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1222. {"application/json", "text/html"}},
  1223. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1224. {"application/json", "text/html"}},
  1225. {"text/html;profile=\"a\\\"b\",application/json",
  1226. {"text/html", "application/json"}},
  1227. // An escaped backslash does not escape the '"' after it
  1228. {"text/html;profile=\"a\\\\\",application/json",
  1229. {"text/html", "application/json"}},
  1230. };
  1231. for (const auto &c : cases) {
  1232. std::vector<std::string> result;
  1233. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1234. << "value: " << c.value;
  1235. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1236. }
  1237. }
  1238. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1239. Server svr;
  1240. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1241. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1242. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1243. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1244. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1245. res.set_content("ok", "text/plain");
  1246. });
  1247. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1248. EXPECT_TRUE(false);
  1249. res.set_content("bad request", "text/plain");
  1250. });
  1251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1252. auto se = detail::scope_exit([&] {
  1253. svr.stop();
  1254. listen_thread.join();
  1255. ASSERT_FALSE(svr.is_running());
  1256. });
  1257. svr.wait_until_ready();
  1258. Client cli("localhost", PORT);
  1259. {
  1260. auto res = cli.Get(
  1261. "/accept_ok",
  1262. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1264. EXPECT_EQ(StatusCode::OK_200, res->status);
  1265. }
  1266. {
  1267. auto res = cli.Get("/accept_bad_request",
  1268. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1271. }
  1272. }
  1273. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1274. Server svr;
  1275. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1276. res.set_content("ok", "text/plain");
  1277. });
  1278. std::atomic<int> start_count{0};
  1279. std::atomic<bool> running_when_called{false};
  1280. svr.set_start_handler([&]() {
  1281. running_when_called = svr.is_running();
  1282. start_count++;
  1283. });
  1284. auto port = svr.bind_to_any_port(HOST);
  1285. std::thread t([&]() { svr.listen_after_bind(); });
  1286. auto se = detail::scope_exit([&] {
  1287. svr.stop();
  1288. t.join();
  1289. ASSERT_FALSE(svr.is_running());
  1290. });
  1291. svr.wait_until_ready();
  1292. // A successful request proves the accept loop is running, which the start
  1293. // handler precedes; so by now the handler must have run exactly once.
  1294. Client cli(HOST, port);
  1295. cli.set_connection_timeout(std::chrono::seconds(5));
  1296. auto res = cli.Get("/");
  1297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1298. EXPECT_EQ(StatusCode::OK_200, res->status);
  1299. EXPECT_EQ(1, start_count.load());
  1300. EXPECT_TRUE(running_when_called.load());
  1301. }
  1302. TEST(DivideTest, DivideStringTests) {
  1303. auto divide = [](const std::string &str, char d) {
  1304. std::string lhs;
  1305. std::string rhs;
  1306. detail::divide(str, d,
  1307. [&](const char *lhs_data, std::size_t lhs_size,
  1308. const char *rhs_data, std::size_t rhs_size) {
  1309. lhs.assign(lhs_data, lhs_size);
  1310. rhs.assign(rhs_data, rhs_size);
  1311. });
  1312. return std::make_pair(std::move(lhs), std::move(rhs));
  1313. };
  1314. {
  1315. const auto res = divide("", '=');
  1316. EXPECT_EQ(res.first, "");
  1317. EXPECT_EQ(res.second, "");
  1318. }
  1319. {
  1320. const auto res = divide("=", '=');
  1321. EXPECT_EQ(res.first, "");
  1322. EXPECT_EQ(res.second, "");
  1323. }
  1324. {
  1325. const auto res = divide(" ", '=');
  1326. EXPECT_EQ(res.first, " ");
  1327. EXPECT_EQ(res.second, "");
  1328. }
  1329. {
  1330. const auto res = divide("a", '=');
  1331. EXPECT_EQ(res.first, "a");
  1332. EXPECT_EQ(res.second, "");
  1333. }
  1334. {
  1335. const auto res = divide("a=", '=');
  1336. EXPECT_EQ(res.first, "a");
  1337. EXPECT_EQ(res.second, "");
  1338. }
  1339. {
  1340. const auto res = divide("=b", '=');
  1341. EXPECT_EQ(res.first, "");
  1342. EXPECT_EQ(res.second, "b");
  1343. }
  1344. {
  1345. const auto res = divide("a=b", '=');
  1346. EXPECT_EQ(res.first, "a");
  1347. EXPECT_EQ(res.second, "b");
  1348. }
  1349. {
  1350. const auto res = divide("a=b=", '=');
  1351. EXPECT_EQ(res.first, "a");
  1352. EXPECT_EQ(res.second, "b=");
  1353. }
  1354. {
  1355. const auto res = divide("a=b=c", '=');
  1356. EXPECT_EQ(res.first, "a");
  1357. EXPECT_EQ(res.second, "b=c");
  1358. }
  1359. }
  1360. TEST(SplitTest, ParseQueryString) {
  1361. string s = "key1=val1&key2=val2&key3=val3";
  1362. Params dic;
  1363. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1364. [&](const char *b, const char *e) {
  1365. string key, val;
  1366. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1367. if (key.empty()) {
  1368. key.assign(b2, e2);
  1369. } else {
  1370. val.assign(b2, e2);
  1371. }
  1372. });
  1373. dic.emplace(key, val);
  1374. });
  1375. EXPECT_EQ("val1", dic.find("key1")->second);
  1376. EXPECT_EQ("val2", dic.find("key2")->second);
  1377. EXPECT_EQ("val3", dic.find("key3")->second);
  1378. }
  1379. TEST(SplitTest, ParseInvalidQueryTests) {
  1380. {
  1381. string s = " ";
  1382. Params dict;
  1383. detail::parse_query_text(s, dict);
  1384. EXPECT_TRUE(dict.empty());
  1385. }
  1386. {
  1387. string s = " = =";
  1388. Params dict;
  1389. detail::parse_query_text(s, dict);
  1390. EXPECT_TRUE(dict.empty());
  1391. }
  1392. }
  1393. TEST(ParseQueryTest, ParseQueryString) {
  1394. {
  1395. std::string s = "key1=val1&key2=val2&key3=val3";
  1396. Params dic;
  1397. detail::parse_query_text(s, dic);
  1398. EXPECT_EQ("val1", dic.find("key1")->second);
  1399. EXPECT_EQ("val2", dic.find("key2")->second);
  1400. EXPECT_EQ("val3", dic.find("key3")->second);
  1401. }
  1402. {
  1403. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1404. Params dic;
  1405. detail::parse_query_text(s, dic);
  1406. EXPECT_EQ("", dic.find("key1")->second);
  1407. EXPECT_EQ("val1", dic.find("key2")->second);
  1408. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1409. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1410. }
  1411. }
  1412. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1413. Params dic;
  1414. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1415. dic.emplace("key1", "val1");
  1416. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1417. dic.emplace("key2", "val2");
  1418. dic.emplace("key3", "val3");
  1419. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1420. }
  1421. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1422. Params params;
  1423. params.emplace("a", "1");
  1424. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1425. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1426. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1427. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1428. // Long enough to overflow the stack when matched with std::regex.
  1429. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1430. EXPECT_EQ("/p?" + long_query + "&a=1",
  1431. append_query_params("/p?" + long_query, params));
  1432. }
  1433. // Joins every entry of a Headers or Params into "key=value " so a whole
  1434. // traversal can be compared in one assertion. Both are instantiations of the
  1435. // same insertion-ordered container, so one helper serves both.
  1436. template <typename Map> static std::string entries_to_string(const Map &m) {
  1437. std::string s;
  1438. for (const auto &entry : m) {
  1439. s += entry.first + "=" + entry.second + " ";
  1440. }
  1441. return s;
  1442. }
  1443. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1444. // Params used to be a std::multimap, which sorted by name and handed the
  1445. // caller's query back alphabetised. A client signing its query string could
  1446. // not reproduce the order it asked for.
  1447. Params dic;
  1448. dic.emplace("zulu", "1");
  1449. dic.emplace("alpha", "2");
  1450. dic.emplace("mike", "3");
  1451. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1452. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1453. }
  1454. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1455. Params dic;
  1456. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1457. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1458. }
  1459. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1460. Request req;
  1461. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1462. req.params);
  1463. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1464. EXPECT_EQ("first", req.get_param_value("tag"));
  1465. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1466. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1467. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1468. EXPECT_EQ("", req.get_param_value("tag", 3));
  1469. }
  1470. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1471. // Params shares its container with Headers, which matches field names
  1472. // case-insensitively. Parameter names must not pick that up.
  1473. Params dic;
  1474. dic.emplace("Key", "upper");
  1475. dic.emplace("key", "lower");
  1476. EXPECT_EQ(2U, dic.size());
  1477. EXPECT_EQ(1U, dic.count("Key"));
  1478. EXPECT_EQ(1U, dic.count("key"));
  1479. EXPECT_EQ("upper", dic.find("Key")->second);
  1480. EXPECT_EQ("lower", dic.find("key")->second);
  1481. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1482. }
  1483. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1484. Server svr;
  1485. std::string order;
  1486. svr.Get("/order", [&](const Request &req, Response &res) {
  1487. order = entries_to_string(req.params);
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, port);
  1499. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1502. }
  1503. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1504. Server svr;
  1505. std::string field_order, file_order;
  1506. svr.Post("/order", [&](const Request &req, Response &res) {
  1507. for (const auto &field : req.form.fields) {
  1508. field_order += field.first + "=" + field.second.content + " ";
  1509. }
  1510. for (const auto &file : req.form.files) {
  1511. file_order += file.first + "=" + file.second.filename + " ";
  1512. }
  1513. res.set_content("ok", "text/plain");
  1514. });
  1515. auto port = svr.bind_to_any_port(HOST);
  1516. thread t = thread([&] { svr.listen_after_bind(); });
  1517. auto se = detail::scope_exit([&] {
  1518. svr.stop();
  1519. t.join();
  1520. ASSERT_FALSE(svr.is_running());
  1521. });
  1522. svr.wait_until_ready();
  1523. UploadFormDataItems items = {
  1524. {"zulu", "1", "", ""},
  1525. {"alpha", "2", "", ""},
  1526. {"mike", "3", "", ""},
  1527. {"zebra", "z", "z.txt", "text/plain"},
  1528. {"apple", "a", "a.txt", "text/plain"},
  1529. };
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/order", items);
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1534. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1535. }
  1536. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1537. Server svr;
  1538. std::vector<std::string> values;
  1539. std::string first, second, out_of_range, order;
  1540. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1541. values = req.form.get_fields("tag");
  1542. first = req.form.get_field("tag", 0);
  1543. second = req.form.get_field("tag", 1);
  1544. out_of_range = req.form.get_field("tag", 2);
  1545. for (const auto &field : req.form.fields) {
  1546. order += field.first + "=" + field.second.content + " ";
  1547. }
  1548. res.set_content("ok", "text/plain");
  1549. });
  1550. auto port = svr.bind_to_any_port(HOST);
  1551. thread t = thread([&] { svr.listen_after_bind(); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. t.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1559. // not adjacent in the container.
  1560. UploadFormDataItems items = {
  1561. {"tag", "first", "", ""},
  1562. {"other", "x", "", ""},
  1563. {"tag", "second", "", ""},
  1564. };
  1565. Client cli(HOST, port);
  1566. auto res = cli.Post("/repeated", items);
  1567. ASSERT_TRUE(res);
  1568. ASSERT_EQ(2U, values.size());
  1569. EXPECT_EQ("first", values[0]);
  1570. EXPECT_EQ("second", values[1]);
  1571. EXPECT_EQ("first", first);
  1572. EXPECT_EQ("second", second);
  1573. // std::multimap already kept entries sharing a name in insertion order, so
  1574. // everything above passes without this change too. The whole traversal is
  1575. // what tells the two apart: sorting by name would hoist "other" to the front
  1576. // and the two "tag" parts would end up adjacent.
  1577. EXPECT_EQ("tag=first other=x tag=second ", order);
  1578. // Advancing past the last entry of a name used to run off the container;
  1579. // the container's saturating increment makes it return the default instead.
  1580. EXPECT_EQ("", out_of_range);
  1581. }
  1582. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1583. Server svr;
  1584. std::string file_names;
  1585. svr.Post("/upload", [&](const Request &req, Response &res) {
  1586. for (const auto &file : req.form.files) {
  1587. file_names += file.first + "|" + file.second.filename + " ";
  1588. }
  1589. res.set_content("ok", "text/plain");
  1590. });
  1591. auto port = svr.bind_to_any_port(HOST);
  1592. thread t = thread([&] { svr.listen_after_bind(); });
  1593. auto se = detail::scope_exit([&] {
  1594. svr.stop();
  1595. t.join();
  1596. ASSERT_FALSE(svr.is_running());
  1597. });
  1598. svr.wait_until_ready();
  1599. // A trailing backslash would otherwise escape the closing quote.
  1600. UploadFormDataItems items = {
  1601. {"dir\\", "x", "a.txt", "text/plain"},
  1602. {"b", "y", "a\\\\b.txt", "text/plain"},
  1603. };
  1604. Client cli(HOST, port);
  1605. auto res = cli.Post("/upload", items);
  1606. ASSERT_TRUE(res);
  1607. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1608. }
  1609. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1610. // Server::read_content() keeps a FormFields::iterator alive across the
  1611. // content callbacks that fill the part it points at. The container is
  1612. // vector-backed, so a later emplace can reallocate and invalidate an older
  1613. // iterator; 64 parts grow the vector through seven reallocations, which
  1614. // checks that every part's content still lands in its own entry.
  1615. const size_t part_count = 64;
  1616. // One formula for both the parts sent and the values expected back, so the
  1617. // two cannot drift apart.
  1618. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1619. auto content_of = [](size_t i) {
  1620. return std::string(64, static_cast<char>('a' + (i % 26)));
  1621. };
  1622. Server svr;
  1623. std::vector<std::pair<std::string, std::string>> received;
  1624. svr.Post("/many", [&](const Request &req, Response &res) {
  1625. for (const auto &field : req.form.fields) {
  1626. received.emplace_back(field.first, field.second.content);
  1627. }
  1628. res.set_content("ok", "text/plain");
  1629. });
  1630. auto port = svr.bind_to_any_port(HOST);
  1631. thread t = thread([&] { svr.listen_after_bind(); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. t.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. UploadFormDataItems items;
  1639. for (size_t i = 0; i < part_count; i++) {
  1640. items.push_back({name_of(i), content_of(i), "", ""});
  1641. }
  1642. Client cli(HOST, port);
  1643. auto res = cli.Post("/many", items);
  1644. ASSERT_TRUE(res);
  1645. ASSERT_EQ(part_count, received.size());
  1646. for (size_t i = 0; i < part_count; i++) {
  1647. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1648. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1649. }
  1650. }
  1651. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1652. string content_type = "multipart/form-data; boundary=something";
  1653. string boundary;
  1654. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(boundary, "something");
  1657. }
  1658. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1659. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1660. string boundary;
  1661. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1662. EXPECT_TRUE(ret);
  1663. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1666. string content_type =
  1667. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1668. string boundary;
  1669. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1670. EXPECT_TRUE(ret);
  1671. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1672. }
  1673. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1674. string content_type =
  1675. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1676. string boundary;
  1677. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1678. EXPECT_TRUE(ret);
  1679. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1680. }
  1681. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1682. const string boundary(70, 'a');
  1683. string content_type = "multipart/form-data; boundary=" + boundary;
  1684. string parsed;
  1685. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1686. EXPECT_TRUE(ret);
  1687. EXPECT_EQ(parsed, boundary);
  1688. }
  1689. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1690. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1691. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1692. string parsed;
  1693. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1694. EXPECT_FALSE(ret);
  1695. }
  1696. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1697. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1698. // is 72 characters on the wire and still valid.
  1699. const string boundary(70, 'a');
  1700. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1701. string parsed;
  1702. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1703. EXPECT_EQ(parsed, boundary);
  1704. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1705. parsed.clear();
  1706. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1709. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1710. // The parameter parser must not treat that '=' as the key/value separator.
  1711. string content_type =
  1712. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1713. "charset=UTF-8";
  1714. string parsed;
  1715. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1716. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1717. }
  1718. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1719. // A ';' inside the quoted-string is part of the value, not a parameter
  1720. // separator, so it must not truncate the boundary.
  1721. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1722. string parsed;
  1723. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1724. EXPECT_EQ(parsed, "a;b");
  1725. }
  1726. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1727. string parsed;
  1728. EXPECT_TRUE(detail::parse_multipart_boundary(
  1729. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1730. EXPECT_EQ("a\\b", parsed);
  1731. EXPECT_TRUE(detail::parse_multipart_boundary(
  1732. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1733. EXPECT_EQ("a\"b", parsed);
  1734. }
  1735. TEST(ParseDispositionParamsTest, QuotedValues) {
  1736. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1737. // ';' and '=' are ordinary characters inside one.
  1738. struct {
  1739. const char *value;
  1740. std::vector<std::pair<const char *, const char *>> expected;
  1741. } cases[] = {
  1742. {"name=\"file1\"; filename=\"a.txt\"",
  1743. {{"name", "file1"}, {"filename", "a.txt"}}},
  1744. // Whitespace around '=' and ';' is still trimmed
  1745. {"name=\"file2\" ;filename = \"a.html\"",
  1746. {{"name", "file2"}, {"filename", "a.html"}}},
  1747. // '=' inside the value used to leave only the text after the last one
  1748. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1749. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1750. {"name=\"x=y\"", {{"name", "x=y"}}},
  1751. // ';' inside the value used to truncate the pair and leave a bogus one
  1752. {"name=\"file3\"; filename=\"a;b.txt\"",
  1753. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1754. // An unquoted value keeps working, and so does filename*
  1755. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1756. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1757. // A parameter with no key is dropped rather than turned into one whose
  1758. // key is the value
  1759. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1760. // An escaped quote does not end the value
  1761. {"name=\"a\\\"; filename=evil.php\"",
  1762. {{"name", "a\"; filename=evil.php"}}},
  1763. // Other backslashes, as in a Windows path, are kept
  1764. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1765. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1766. };
  1767. for (const auto &c : cases) {
  1768. Params params;
  1769. detail::parse_disposition_params(c.value, params);
  1770. for (const auto &kv : c.expected) {
  1771. auto it = params.find(kv.first);
  1772. ASSERT_NE(it, params.end())
  1773. << "value: " << c.value << ", key: " << kv.first;
  1774. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1775. }
  1776. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1777. }
  1778. }
  1779. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1780. Server svr;
  1781. std::string filename;
  1782. std::string content;
  1783. svr.Post("/upload", [&](const Request &req, Response &) {
  1784. const auto &file = req.form.get_file("file");
  1785. filename = file.filename;
  1786. content = file.content;
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. std::string body = "--B\r\n"
  1796. "Content-Disposition: form-data; name=\"file\"; "
  1797. "filename=\"a.txt\"\r\n"
  1798. "Content-Type: text/plain\r\n"
  1799. "\r\n"
  1800. "hello\r\n"
  1801. "--B--\r\n";
  1802. Client cli(HOST, PORT);
  1803. auto res = cli.Post(
  1804. "/upload",
  1805. [&](size_t offset, DataSink &sink) {
  1806. if (offset < body.size()) {
  1807. sink.write(&body[offset], 1);
  1808. } else {
  1809. sink.done();
  1810. }
  1811. return true;
  1812. },
  1813. "multipart/form-data; boundary=B");
  1814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1815. EXPECT_EQ(StatusCode::OK_200, res->status);
  1816. EXPECT_EQ("a.txt", filename);
  1817. EXPECT_EQ("hello", content);
  1818. }
  1819. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1820. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1821. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1822. Server svr;
  1823. std::string field_value, file_name, file_filename;
  1824. bool has_field = false, has_file = false;
  1825. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1826. has_field = req.form.has_field("x=y");
  1827. field_value = req.form.get_field("x=y");
  1828. has_file = req.form.has_file("file1");
  1829. const auto &file = req.form.get_file("file1");
  1830. file_name = file.name;
  1831. file_filename = file.filename;
  1832. res.set_content("ok", "text/plain");
  1833. });
  1834. auto port = svr.bind_to_any_port(HOST);
  1835. thread t = thread([&] { svr.listen_after_bind(); });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. t.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. UploadFormDataItems items = {
  1843. {"x=y", "field-value", "", ""},
  1844. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1845. };
  1846. Client cli(HOST, port);
  1847. auto res = cli.Post("/quoted", items);
  1848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1849. ASSERT_EQ(StatusCode::OK_200, res->status);
  1850. EXPECT_TRUE(has_field);
  1851. EXPECT_EQ("field-value", field_value);
  1852. EXPECT_TRUE(has_file);
  1853. EXPECT_EQ("file1", file_name);
  1854. EXPECT_EQ("a;b=report.pdf", file_filename);
  1855. }
  1856. TEST(GetHeaderValueTest, DefaultValue) {
  1857. Headers headers = {{"Dummy", "Dummy"}};
  1858. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1859. EXPECT_STREQ("text/plain", val);
  1860. }
  1861. TEST(GetHeaderValueTest, DefaultValueInt) {
  1862. Headers headers = {{"Dummy", "Dummy"}};
  1863. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1864. EXPECT_EQ(100ull, val);
  1865. }
  1866. TEST(GetHeaderValueTest, RegularValue) {
  1867. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1868. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1869. EXPECT_STREQ("text/html", val);
  1870. }
  1871. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1872. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1873. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1874. EXPECT_STREQ("text/html", val);
  1875. }
  1876. TEST(GetHeaderValueTest, SetContent) {
  1877. Response res;
  1878. res.set_content("html", "text/html");
  1879. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1880. res.set_content("text", "text/plain");
  1881. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1882. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1883. }
  1884. TEST(GetHeaderValueTest, RegularValueInt) {
  1885. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1887. EXPECT_EQ(100ull, val);
  1888. }
  1889. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1890. Headers headers = {{"Content-Length", "x"}};
  1891. auto is_invalid_value = false;
  1892. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1893. is_invalid_value);
  1894. EXPECT_EQ(0ull, val);
  1895. EXPECT_TRUE(is_invalid_value);
  1896. }
  1897. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1898. // An all-digit value that overflows size_t must be reported as invalid, not
  1899. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1900. // a large length to a small one on 32-bit builds, leaving the framing length
  1901. // wrong while is_invalid_value stayed false.
  1902. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1903. auto is_invalid_value = false;
  1904. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1905. is_invalid_value);
  1906. EXPECT_TRUE(is_invalid_value);
  1907. // A well-formed length is unaffected.
  1908. Headers ok = {{"Content-Length", "1234"}};
  1909. is_invalid_value = false;
  1910. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1911. is_invalid_value);
  1912. EXPECT_EQ(1234ull, val);
  1913. EXPECT_FALSE(is_invalid_value);
  1914. }
  1915. TEST(GetHeaderValueTest, Range) {
  1916. {
  1917. Headers headers = {make_range_header({{1, -1}})};
  1918. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1919. EXPECT_STREQ("bytes=1-", val);
  1920. }
  1921. {
  1922. Headers headers = {make_range_header({{-1, 1}})};
  1923. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1924. EXPECT_STREQ("bytes=-1", val);
  1925. }
  1926. {
  1927. Headers headers = {make_range_header({{1, 10}})};
  1928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1929. EXPECT_STREQ("bytes=1-10", val);
  1930. }
  1931. {
  1932. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1934. EXPECT_STREQ("bytes=1-10, 100-", val);
  1935. }
  1936. {
  1937. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1938. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1939. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1940. }
  1941. {
  1942. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1943. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1944. EXPECT_STREQ("bytes=0-0, -1", val);
  1945. }
  1946. }
  1947. TEST(BearerTokenAuthTest, SchemeValidation) {
  1948. // A value shorter than "Bearer " must not throw from the fixed-length
  1949. // substr, and a non-Bearer scheme must not be reported as a token.
  1950. struct {
  1951. const char *value;
  1952. const char *expected;
  1953. } cases[] = {
  1954. {"x", ""},
  1955. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1956. {"Bearer abc123", "abc123"},
  1957. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1958. };
  1959. for (const auto &c : cases) {
  1960. Request req;
  1961. req.set_header("Authorization", c.value);
  1962. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1963. }
  1964. }
  1965. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1966. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1967. // to depend on the standard library (libstdc++ handed back duplicates in
  1968. // reverse insertion order, libc++ in insertion order).
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "gzip");
  1971. req.set_header("Accept-Encoding", "deflate");
  1972. req.set_header("Accept-Encoding", "br");
  1973. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1974. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1975. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1976. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1977. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1978. }
  1979. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1980. Request req;
  1981. req.set_header("X-Test", "only");
  1982. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1983. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1984. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1985. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1986. }
  1987. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1988. Request req;
  1989. req.set_header("X-First", "1");
  1990. req.set_header("X-Test", "2");
  1991. req.params.emplace("first", "1");
  1992. req.params.emplace("test", "2");
  1993. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1994. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1995. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1996. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1997. // The second one is negative when read as a signed value
  1998. const auto max_id = (std::numeric_limits<size_t>::max)();
  1999. for (auto id : {max_id / 2, max_id}) {
  2000. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2001. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2002. EXPECT_EQ("", req.get_param_value("test", id));
  2003. EXPECT_EQ("", req.form.get_field("test", id));
  2004. EXPECT_EQ("", req.form.get_file("test", id).content);
  2005. }
  2006. }
  2007. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2008. Headers headers;
  2009. headers.emplace("Host", "example.com");
  2010. headers.emplace("Accept-Encoding", "gzip");
  2011. headers.emplace("User-Agent", "test");
  2012. headers.emplace("Accept-Encoding", "deflate");
  2013. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2014. "Accept-Encoding=deflate ",
  2015. entries_to_string(headers));
  2016. }
  2017. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2018. Headers headers = {{"Content-Type", "text/html"},
  2019. {"CONTENT-TYPE", "text/xml"}};
  2020. EXPECT_EQ(2U, headers.count("content-type"));
  2021. auto it = headers.find("content-type");
  2022. ASSERT_TRUE(it != headers.end());
  2023. EXPECT_EQ("text/html", it->second);
  2024. }
  2025. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2026. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2027. // drop only those fields and leave everything positioned between them.
  2028. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2029. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2030. auto rng = headers.equal_range("a");
  2031. headers.erase(rng.first, rng.second);
  2032. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2033. }
  2034. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2035. Headers headers = {
  2036. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2037. EXPECT_EQ(3U, headers.erase("A"));
  2038. EXPECT_EQ(0U, headers.count("A"));
  2039. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2040. }
  2041. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2042. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2043. headers.emplace_front("Host", "example.com");
  2044. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2045. entries_to_string(headers));
  2046. }
  2047. TEST(ParseHeaderValueTest, Range) {
  2048. {
  2049. Ranges ranges;
  2050. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2051. EXPECT_TRUE(ret);
  2052. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2053. }
  2054. {
  2055. Ranges ranges;
  2056. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2057. EXPECT_TRUE(ret);
  2058. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2059. }
  2060. {
  2061. Ranges ranges;
  2062. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2063. EXPECT_TRUE(ret);
  2064. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2065. }
  2066. {
  2067. Ranges ranges;
  2068. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2069. EXPECT_FALSE(ret);
  2070. }
  2071. {
  2072. Ranges ranges;
  2073. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2074. EXPECT_TRUE(ret);
  2075. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2076. }
  2077. {
  2078. Ranges ranges;
  2079. auto ret =
  2080. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2081. EXPECT_TRUE(ret);
  2082. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2083. }
  2084. {
  2085. Ranges ranges;
  2086. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2087. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2088. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2089. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2090. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2091. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2092. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2093. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2094. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2095. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2096. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2097. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2098. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2099. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2100. EXPECT_FALSE(
  2101. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2102. EXPECT_TRUE(ranges.empty());
  2103. }
  2104. {
  2105. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2106. // remainder of the representation, so it stays accepted.
  2107. Ranges ranges;
  2108. auto ret =
  2109. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2110. EXPECT_TRUE(ret);
  2111. ASSERT_EQ(1u, ranges.size());
  2112. EXPECT_EQ(0, ranges[0].first);
  2113. EXPECT_EQ(-1, ranges[0].second);
  2114. }
  2115. // RFC 9110 14.1: range unit names are case-insensitive.
  2116. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2117. Ranges ranges;
  2118. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2119. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2120. }
  2121. }
  2122. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2123. Request req;
  2124. req.set_header("Accept-Encoding", "gzip");
  2125. Response res;
  2126. res.set_header("Content-Type", "text/plain");
  2127. auto ret = detail::encoding_type(req, res);
  2128. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2129. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2130. #else
  2131. EXPECT_TRUE(ret == detail::EncodingType::None);
  2132. #endif
  2133. }
  2134. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2135. Request req;
  2136. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2137. Response res;
  2138. res.set_header("Content-Type", "text/plain");
  2139. auto ret = detail::encoding_type(req, res);
  2140. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2141. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2142. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2143. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2144. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2145. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2146. #else
  2147. EXPECT_TRUE(ret == detail::EncodingType::None);
  2148. #endif
  2149. }
  2150. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2151. Request req;
  2152. req.set_header("Accept-Encoding",
  2153. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2154. Response res;
  2155. res.set_header("Content-Type", "text/plain");
  2156. auto ret = detail::encoding_type(req, res);
  2157. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2158. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2159. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2160. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2161. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2162. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2163. #else
  2164. EXPECT_TRUE(ret == detail::EncodingType::None);
  2165. #endif
  2166. }
  2167. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2168. // All supported encodings rejected with q=0 should return None
  2169. Request req;
  2170. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2171. Response res;
  2172. res.set_header("Content-Type", "text/plain");
  2173. auto ret = detail::encoding_type(req, res);
  2174. EXPECT_TRUE(ret == detail::EncodingType::None);
  2175. }
  2176. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2177. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2178. Request req;
  2179. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2180. Response res;
  2181. res.set_header("Content-Type", "text/plain");
  2182. auto ret = detail::encoding_type(req, res);
  2183. EXPECT_TRUE(ret == detail::EncodingType::None);
  2184. }
  2185. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2186. Request req;
  2187. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2188. Response res;
  2189. res.set_header("Content-Type", "text/plain");
  2190. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2191. }
  2192. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2193. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2194. Request req;
  2195. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2196. Response res;
  2197. res.set_header("Content-Type", "text/plain");
  2198. auto ret = detail::encoding_type(req, res);
  2199. EXPECT_TRUE(ret == detail::EncodingType::None);
  2200. }
  2201. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2202. // RFC 7231: Accept-Encoding values are case-insensitive
  2203. Request req;
  2204. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2205. Response res;
  2206. res.set_header("Content-Type", "text/plain");
  2207. auto ret = detail::encoding_type(req, res);
  2208. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2209. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2210. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2211. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2212. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2213. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2214. #else
  2215. EXPECT_TRUE(ret == detail::EncodingType::None);
  2216. #endif
  2217. }
  2218. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2219. // q value should determine priority, not hardcoded order
  2220. Request req;
  2221. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2222. Response res;
  2223. res.set_header("Content-Type", "text/plain");
  2224. auto ret = detail::encoding_type(req, res);
  2225. // gzip has highest q=1.0, so it should be selected even though
  2226. // br and zstd are also supported
  2227. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2228. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2229. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2230. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2231. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2232. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2233. #else
  2234. EXPECT_TRUE(ret == detail::EncodingType::None);
  2235. #endif
  2236. }
  2237. TEST(BufferStreamTest, read) {
  2238. detail::BufferStream strm1;
  2239. Stream &strm = strm1;
  2240. EXPECT_EQ(5, strm.write("hello"));
  2241. char buf[512];
  2242. EXPECT_EQ(2, strm.read(buf, 2));
  2243. EXPECT_EQ('h', buf[0]);
  2244. EXPECT_EQ('e', buf[1]);
  2245. EXPECT_EQ(2, strm.read(buf, 2));
  2246. EXPECT_EQ('l', buf[0]);
  2247. EXPECT_EQ('l', buf[1]);
  2248. EXPECT_EQ(1, strm.read(buf, 1));
  2249. EXPECT_EQ('o', buf[0]);
  2250. EXPECT_EQ(0, strm.read(buf, 1));
  2251. }
  2252. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2253. auto host = "www.httpwatch.com";
  2254. auto ip = hosted_at(host);
  2255. EXPECT_EQ("23.96.13.243", ip);
  2256. std::vector<std::string> addrs;
  2257. hosted_at(host, addrs);
  2258. EXPECT_EQ(1u, addrs.size());
  2259. }
  2260. #if 0 // It depends on each test environment...
  2261. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2262. auto host = "www.youtube.com";
  2263. std::vector<std::string> addrs;
  2264. hosted_at(host, addrs);
  2265. EXPECT_EQ(20u, addrs.size());
  2266. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2267. EXPECT_TRUE(it != addrs.end());
  2268. }
  2269. #endif
  2270. class ChunkedEncodingTest : public ::testing::Test {
  2271. protected:
  2272. ChunkedEncodingTest()
  2273. : cli_(HOST, PORT)
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. ,
  2276. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2277. #endif
  2278. {
  2279. cli_.set_connection_timeout(2);
  2280. #ifdef CPPHTTPLIB_SSL_ENABLED
  2281. cli_.enable_server_certificate_verification(false);
  2282. #endif
  2283. }
  2284. virtual void SetUp() {
  2285. read_file("./image.jpg", image_data_);
  2286. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2287. res.set_content("Hello World!", "text/plain");
  2288. });
  2289. svr_.Get(
  2290. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2291. res.set_chunked_content_provider(
  2292. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2293. size_t remaining = image_data_.size() - offset;
  2294. if (remaining == 0) {
  2295. sink.done();
  2296. } else {
  2297. constexpr size_t CHUNK_SIZE = 1024;
  2298. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2299. sink.write(&image_data_[offset], send_size);
  2300. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2301. }
  2302. return true;
  2303. });
  2304. });
  2305. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2306. svr_.wait_until_ready();
  2307. }
  2308. virtual void TearDown() {
  2309. svr_.stop();
  2310. if (!request_threads_.empty()) {
  2311. std::this_thread::sleep_for(std::chrono::seconds(1));
  2312. for (auto &t : request_threads_) {
  2313. t.join();
  2314. }
  2315. }
  2316. t_.join();
  2317. }
  2318. #ifdef CPPHTTPLIB_SSL_ENABLED
  2319. SSLClient cli_;
  2320. SSLServer svr_;
  2321. #else
  2322. Client cli_;
  2323. Server svr_;
  2324. #endif
  2325. thread t_;
  2326. std::vector<thread> request_threads_;
  2327. std::string image_data_;
  2328. };
  2329. TEST_F(ChunkedEncodingTest, NormalGet) {
  2330. auto res = cli_.Get("/chunked");
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. std::string out;
  2333. read_file("./image.jpg", out);
  2334. EXPECT_EQ(StatusCode::OK_200, res->status);
  2335. EXPECT_EQ(out, res->body);
  2336. }
  2337. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2338. std::string body;
  2339. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2340. body.append(data, data_length);
  2341. return true;
  2342. });
  2343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2344. std::string out;
  2345. read_file("./image.jpg", out);
  2346. EXPECT_EQ(StatusCode::OK_200, res->status);
  2347. EXPECT_EQ(out, body);
  2348. }
  2349. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2350. std::string body;
  2351. auto res = cli_.Get(
  2352. "/chunked",
  2353. [&](const Response &response) {
  2354. EXPECT_EQ(StatusCode::OK_200, response.status);
  2355. return true;
  2356. },
  2357. [&](const char *data, size_t data_length) {
  2358. body.append(data, data_length);
  2359. return true;
  2360. });
  2361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2362. std::string out;
  2363. read_file("./image.jpg", out);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. EXPECT_EQ(out, body);
  2366. }
  2367. TEST(RangeTest, FromHTTPBin_Online) {
  2368. auto host = "httpbingo.org";
  2369. auto path = std::string{"/range/32"};
  2370. #ifdef CPPHTTPLIB_SSL_ENABLED
  2371. auto port = 443;
  2372. SSLClient cli(host, port);
  2373. #else
  2374. auto port = 80;
  2375. Client cli(host, port);
  2376. #endif
  2377. cli.set_connection_timeout(5);
  2378. {
  2379. auto res = cli.Get(path);
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2382. EXPECT_EQ(StatusCode::OK_200, res->status);
  2383. }
  2384. {
  2385. Headers headers = {make_range_header({{1, -1}})};
  2386. auto res = cli.Get(path, headers);
  2387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2388. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2390. }
  2391. {
  2392. Headers headers = {make_range_header({{1, 10}})};
  2393. auto res = cli.Get(path, headers);
  2394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2395. EXPECT_EQ("bcdefghijk", res->body);
  2396. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2397. }
  2398. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2399. // entire resource, while the original httpbin returned 200. Both are
  2400. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2401. {
  2402. Headers headers = {make_range_header({{0, 31}})};
  2403. auto res = cli.Get(path, headers);
  2404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2405. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2406. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2407. res->status == StatusCode::PartialContent_206);
  2408. }
  2409. {
  2410. Headers headers = {make_range_header({{0, -1}})};
  2411. auto res = cli.Get(path, headers);
  2412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2413. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2414. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2415. res->status == StatusCode::PartialContent_206);
  2416. }
  2417. // go-httpbin returns 206 with clamped range for over-range requests,
  2418. // while the original httpbin returned 416. Both behaviors are observed
  2419. // in real servers, so we only verify the request succeeds.
  2420. {
  2421. Headers headers = {make_range_header({{0, 32}})};
  2422. auto res = cli.Get(path, headers);
  2423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2424. }
  2425. }
  2426. TEST(RangeTest, IgnoredForPost) {
  2427. Server svr;
  2428. svr.Post("/", [](const Request &, Response &res) {
  2429. res.set_content("abcdefg", "text/plain");
  2430. });
  2431. auto port = svr.bind_to_any_port(HOST);
  2432. ASSERT_GT(port, 0);
  2433. thread t = thread([&] { svr.listen_after_bind(); });
  2434. auto se = detail::scope_exit([&] {
  2435. svr.stop();
  2436. t.join();
  2437. ASSERT_FALSE(svr.is_running());
  2438. });
  2439. svr.wait_until_ready();
  2440. Client cli(HOST, port);
  2441. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2442. auto res = cli.Post("/", Headers{{"Range", range}});
  2443. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2444. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2445. EXPECT_EQ("abcdefg", res->body) << range;
  2446. }
  2447. }
  2448. TEST(RangeTest, IgnoredForUnknownUnit) {
  2449. Server svr;
  2450. svr.Get("/", [](const Request &, Response &res) {
  2451. res.set_content("abcdefg", "text/plain");
  2452. });
  2453. auto port = svr.bind_to_any_port(HOST);
  2454. ASSERT_GT(port, 0);
  2455. thread t = thread([&] { svr.listen_after_bind(); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. t.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, port);
  2463. for (auto range : {"items=1-2", "none=x"}) {
  2464. auto res = cli.Get("/", Headers{{"Range", range}});
  2465. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2466. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2467. EXPECT_EQ("abcdefg", res->body) << range;
  2468. }
  2469. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2470. ASSERT_TRUE(res) << to_string(res.error());
  2471. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2472. }
  2473. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2474. auto host = "unresolvableaddress.local";
  2475. auto path = std::string{"/"};
  2476. #ifdef CPPHTTPLIB_SSL_ENABLED
  2477. auto port = 443;
  2478. SSLClient cli(host, port);
  2479. #else
  2480. auto port = 80;
  2481. Client cli(host, port);
  2482. #endif
  2483. cli.set_connection_timeout(1);
  2484. {
  2485. auto res = cli.Get(path);
  2486. ASSERT_FALSE(res);
  2487. }
  2488. std::this_thread::sleep_for(std::chrono::seconds(8));
  2489. }
  2490. #if defined(__linux__) && defined(__GLIBC__) && \
  2491. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2492. // Forward declaration: in split builds split.py strips `inline` and moves the
  2493. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2494. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2495. // against the symbol in both header-only and split builds.
  2496. namespace httplib {
  2497. namespace detail {
  2498. int getaddrinfo_with_timeout(const char *node, const char *service,
  2499. const struct addrinfo *hints,
  2500. struct addrinfo **res, time_t timeout_sec);
  2501. } // namespace detail
  2502. } // namespace httplib
  2503. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2504. //
  2505. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2506. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2507. // gai_suspend() call hits the connection timeout the function calls
  2508. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2509. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2510. // still alive and still references the now-destroyed stack frame.
  2511. //
  2512. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2513. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2514. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2515. // and runs them in a container.
  2516. namespace {
  2517. bool should_run_issue_2431_tests() {
  2518. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2519. return v && *v && std::string(v) != "0";
  2520. }
  2521. std::string unique_unresolvable_host(int n) {
  2522. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2523. // glibc still asks the configured nameserver — which is exactly the path
  2524. // we want to exercise. A unique label per call avoids the resolver cache.
  2525. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2526. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2527. std::to_string(n) + ".invalid";
  2528. }
  2529. } // namespace
  2530. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2531. if (!should_run_issue_2431_tests()) {
  2532. GTEST_SKIP()
  2533. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2534. }
  2535. for (int i = 0; i < 8; ++i) {
  2536. struct addrinfo hints;
  2537. memset(&hints, 0, sizeof(hints));
  2538. hints.ai_family = AF_UNSPEC;
  2539. hints.ai_socktype = SOCK_STREAM;
  2540. auto host = unique_unresolvable_host(i);
  2541. struct addrinfo *result = nullptr;
  2542. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2543. &result, /*timeout_sec=*/1);
  2544. if (rc == 0 && result) { freeaddrinfo(result); }
  2545. }
  2546. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2547. // stack region they still believe holds their gaicb.
  2548. std::this_thread::sleep_for(std::chrono::seconds(3));
  2549. }
  2550. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2551. if (!should_run_issue_2431_tests()) {
  2552. GTEST_SKIP()
  2553. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2554. }
  2555. std::atomic<bool> stop{false};
  2556. std::vector<std::thread> threads;
  2557. for (int t = 0; t < 8; ++t) {
  2558. threads.emplace_back([t, &stop] {
  2559. int i = 0;
  2560. while (!stop.load(std::memory_order_relaxed)) {
  2561. struct addrinfo hints;
  2562. memset(&hints, 0, sizeof(hints));
  2563. hints.ai_family = AF_UNSPEC;
  2564. hints.ai_socktype = SOCK_STREAM;
  2565. auto host = unique_unresolvable_host(t * 100000 + i++);
  2566. struct addrinfo *result = nullptr;
  2567. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2568. &result, /*timeout_sec=*/1);
  2569. if (rc == 0 && result) { freeaddrinfo(result); }
  2570. }
  2571. });
  2572. }
  2573. std::this_thread::sleep_for(std::chrono::seconds(8));
  2574. stop.store(true, std::memory_order_relaxed);
  2575. for (auto &th : threads) {
  2576. th.join();
  2577. }
  2578. std::this_thread::sleep_for(std::chrono::seconds(3));
  2579. }
  2580. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2581. if (!should_run_issue_2431_tests()) {
  2582. GTEST_SKIP()
  2583. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2584. }
  2585. std::atomic<bool> stop{false};
  2586. std::vector<std::thread> threads;
  2587. for (int t = 0; t < 8; ++t) {
  2588. threads.emplace_back([t, &stop] {
  2589. int i = 0;
  2590. while (!stop.load(std::memory_order_relaxed)) {
  2591. auto host = unique_unresolvable_host(t * 100000 + i++);
  2592. Client cli(host, 80);
  2593. cli.set_connection_timeout(1, 0);
  2594. cli.set_read_timeout(1, 0);
  2595. cli.set_write_timeout(1, 0);
  2596. (void)cli.Get("/");
  2597. }
  2598. });
  2599. }
  2600. std::this_thread::sleep_for(std::chrono::seconds(8));
  2601. stop.store(true, std::memory_order_relaxed);
  2602. for (auto &th : threads) {
  2603. th.join();
  2604. }
  2605. std::this_thread::sleep_for(std::chrono::seconds(3));
  2606. }
  2607. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2608. TEST(ConnectionErrorTest, InvalidHost) {
  2609. auto host = "-abcde.com";
  2610. #ifdef CPPHTTPLIB_SSL_ENABLED
  2611. auto port = 443;
  2612. SSLClient cli(host, port);
  2613. #else
  2614. auto port = 80;
  2615. Client cli(host, port);
  2616. #endif
  2617. cli.set_connection_timeout(std::chrono::seconds(2));
  2618. auto res = cli.Get("/");
  2619. ASSERT_TRUE(!res);
  2620. EXPECT_EQ(Error::Connection, res.error());
  2621. }
  2622. TEST(ConnectionErrorTest, InvalidHost2) {
  2623. auto host = "httpcan.org/";
  2624. #ifdef CPPHTTPLIB_SSL_ENABLED
  2625. SSLClient cli(host);
  2626. #else
  2627. Client cli(host);
  2628. #endif
  2629. cli.set_connection_timeout(std::chrono::seconds(2));
  2630. auto res = cli.Get("/");
  2631. ASSERT_TRUE(!res);
  2632. EXPECT_EQ(Error::Connection, res.error());
  2633. }
  2634. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2635. auto host = "httpcan.org/";
  2636. #ifdef CPPHTTPLIB_SSL_ENABLED
  2637. SSLClient cli(host);
  2638. #else
  2639. Client cli(host);
  2640. #endif
  2641. cli.set_connection_timeout(std::chrono::seconds(2));
  2642. auto res = cli.Get("/");
  2643. ASSERT_TRUE(!res);
  2644. stringstream s;
  2645. s << "error code: " << res.error();
  2646. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2647. }
  2648. TEST(ConnectionErrorTest, InvalidPort) {
  2649. auto host = "localhost";
  2650. auto port = 44380;
  2651. #ifdef CPPHTTPLIB_SSL_ENABLED
  2652. SSLClient cli(host, port);
  2653. #else
  2654. Client cli(host, port);
  2655. #endif
  2656. cli.set_connection_timeout(std::chrono::seconds(2));
  2657. auto res = cli.Get("/");
  2658. ASSERT_TRUE(!res);
  2659. EXPECT_TRUE(Error::Connection == res.error() ||
  2660. Error::ConnectionTimeout == res.error());
  2661. }
  2662. TEST(ConnectionErrorTest, Timeout_Online) {
  2663. auto host = "google.com";
  2664. #ifdef CPPHTTPLIB_SSL_ENABLED
  2665. auto port = 44380;
  2666. SSLClient cli(host, port);
  2667. #else
  2668. auto port = 8080;
  2669. Client cli(host, port);
  2670. #endif
  2671. cli.set_connection_timeout(std::chrono::seconds(2));
  2672. // only probe one address type so that the error reason
  2673. // correlates to the timed-out IPv4, not the unsupported
  2674. // IPv6 connection attempt
  2675. cli.set_address_family(AF_INET);
  2676. auto res = cli.Get("/");
  2677. ASSERT_TRUE(!res);
  2678. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2679. }
  2680. TEST(CancelTest, NoCancel_Online) {
  2681. auto host = "httpbingo.org";
  2682. auto path = std::string{"/range/32"};
  2683. #ifdef CPPHTTPLIB_SSL_ENABLED
  2684. auto port = 443;
  2685. SSLClient cli(host, port);
  2686. #else
  2687. auto port = 80;
  2688. Client cli(host, port);
  2689. #endif
  2690. cli.set_connection_timeout(std::chrono::seconds(5));
  2691. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2693. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2694. EXPECT_EQ(StatusCode::OK_200, res->status);
  2695. }
  2696. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2697. // Use /bytes with a large payload so that the DownloadProgress callback
  2698. // (which only fires for Content-Length responses) is invoked before the
  2699. // entire body is received, giving cancellation a chance to fire.
  2700. auto host = "httpbingo.org";
  2701. auto path = std::string{"/bytes/524288"};
  2702. #ifdef CPPHTTPLIB_SSL_ENABLED
  2703. auto port = 443;
  2704. SSLClient cli(host, port);
  2705. #else
  2706. auto port = 80;
  2707. Client cli(host, port);
  2708. #endif
  2709. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2710. cli.set_connection_timeout(std::chrono::seconds(5));
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, WithCancelLargePayload_Online) {
  2715. auto host = "httpbingo.org";
  2716. auto path = std::string{"/bytes/524288"};
  2717. #ifdef CPPHTTPLIB_SSL_ENABLED
  2718. auto port = 443;
  2719. SSLClient cli(host, port);
  2720. #else
  2721. auto port = 80;
  2722. Client cli(host, port);
  2723. #endif
  2724. cli.set_connection_timeout(std::chrono::seconds(5));
  2725. uint32_t count = 0;
  2726. auto res =
  2727. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2728. ASSERT_TRUE(!res);
  2729. EXPECT_EQ(Error::Canceled, res.error());
  2730. }
  2731. TEST(CancelTest, NoCancelPost) {
  2732. Server svr;
  2733. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2734. res.set_content("Hello World!", "text/plain");
  2735. });
  2736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2737. auto se = detail::scope_exit([&] {
  2738. svr.stop();
  2739. thread.join();
  2740. ASSERT_FALSE(svr.is_running());
  2741. });
  2742. svr.wait_until_ready();
  2743. Client cli(HOST, PORT);
  2744. cli.set_connection_timeout(std::chrono::seconds(5));
  2745. auto res =
  2746. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2747. "application/json", [](uint64_t, uint64_t) { return true; });
  2748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2749. EXPECT_EQ("Hello World!", res->body);
  2750. EXPECT_EQ(StatusCode::OK_200, res->status);
  2751. }
  2752. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2753. Server svr;
  2754. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2755. res.set_content("Hello World!", "text/plain");
  2756. });
  2757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2758. auto se = detail::scope_exit([&] {
  2759. svr.stop();
  2760. thread.join();
  2761. ASSERT_FALSE(svr.is_running());
  2762. });
  2763. svr.wait_until_ready();
  2764. Client cli(HOST, PORT);
  2765. cli.set_connection_timeout(std::chrono::seconds(5));
  2766. auto res =
  2767. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2768. "application/json", [](uint64_t, uint64_t) { return false; });
  2769. ASSERT_TRUE(!res);
  2770. EXPECT_EQ(Error::Canceled, res.error());
  2771. }
  2772. TEST(CancelTest, WithCancelLargePayloadPost) {
  2773. Server svr;
  2774. svr.set_payload_max_length(200 * 1024 * 1024);
  2775. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2776. res.set_content(LARGE_DATA, "text/plain");
  2777. });
  2778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2779. auto se = detail::scope_exit([&] {
  2780. svr.stop();
  2781. thread.join();
  2782. ASSERT_FALSE(svr.is_running());
  2783. });
  2784. svr.wait_until_ready();
  2785. Client cli(HOST, PORT);
  2786. cli.set_payload_max_length(200 * 1024 * 1024);
  2787. cli.set_connection_timeout(std::chrono::seconds(5));
  2788. auto res =
  2789. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2790. "application/json", [](uint64_t, uint64_t) { return false; });
  2791. ASSERT_TRUE(!res);
  2792. EXPECT_EQ(Error::Canceled, res.error());
  2793. }
  2794. TEST(CancelTest, NoCancelPut) {
  2795. Server svr;
  2796. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2797. res.set_content("Hello World!", "text/plain");
  2798. });
  2799. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2800. auto se = detail::scope_exit([&] {
  2801. svr.stop();
  2802. thread.join();
  2803. ASSERT_FALSE(svr.is_running());
  2804. });
  2805. svr.wait_until_ready();
  2806. Client cli(HOST, PORT);
  2807. cli.set_connection_timeout(std::chrono::seconds(5));
  2808. auto res =
  2809. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2810. "application/json", [](uint64_t, uint64_t) { return true; });
  2811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2812. EXPECT_EQ("Hello World!", res->body);
  2813. EXPECT_EQ(StatusCode::OK_200, res->status);
  2814. }
  2815. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2816. Server svr;
  2817. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2818. res.set_content("Hello World!", "text/plain");
  2819. });
  2820. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2821. auto se = detail::scope_exit([&] {
  2822. svr.stop();
  2823. thread.join();
  2824. ASSERT_FALSE(svr.is_running());
  2825. });
  2826. svr.wait_until_ready();
  2827. Client cli(HOST, PORT);
  2828. cli.set_connection_timeout(std::chrono::seconds(5));
  2829. auto res =
  2830. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2831. "application/json", [](uint64_t, uint64_t) { return false; });
  2832. ASSERT_TRUE(!res);
  2833. EXPECT_EQ(Error::Canceled, res.error());
  2834. }
  2835. TEST(CancelTest, WithCancelLargePayloadPut) {
  2836. Server svr;
  2837. svr.set_payload_max_length(200 * 1024 * 1024);
  2838. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2839. res.set_content(LARGE_DATA, "text/plain");
  2840. });
  2841. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2842. auto se = detail::scope_exit([&] {
  2843. svr.stop();
  2844. thread.join();
  2845. ASSERT_FALSE(svr.is_running());
  2846. });
  2847. svr.wait_until_ready();
  2848. Client cli(HOST, PORT);
  2849. cli.set_payload_max_length(200 * 1024 * 1024);
  2850. cli.set_connection_timeout(std::chrono::seconds(5));
  2851. auto res =
  2852. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2853. "application/json", [](uint64_t, uint64_t) { return false; });
  2854. ASSERT_TRUE(!res);
  2855. EXPECT_EQ(Error::Canceled, res.error());
  2856. }
  2857. TEST(CancelTest, NoCancelPatch) {
  2858. Server svr;
  2859. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2860. res.set_content("Hello World!", "text/plain");
  2861. });
  2862. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2863. auto se = detail::scope_exit([&] {
  2864. svr.stop();
  2865. thread.join();
  2866. ASSERT_FALSE(svr.is_running());
  2867. });
  2868. svr.wait_until_ready();
  2869. Client cli(HOST, PORT);
  2870. cli.set_connection_timeout(std::chrono::seconds(5));
  2871. auto res =
  2872. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2873. "application/json", [](uint64_t, uint64_t) { return true; });
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. EXPECT_EQ("Hello World!", res->body);
  2876. EXPECT_EQ(StatusCode::OK_200, res->status);
  2877. }
  2878. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2879. Server svr;
  2880. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2881. res.set_content("Hello World!", "text/plain");
  2882. });
  2883. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2884. auto se = detail::scope_exit([&] {
  2885. svr.stop();
  2886. thread.join();
  2887. ASSERT_FALSE(svr.is_running());
  2888. });
  2889. svr.wait_until_ready();
  2890. Client cli(HOST, PORT);
  2891. cli.set_connection_timeout(std::chrono::seconds(5));
  2892. auto res =
  2893. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2894. "application/json", [](uint64_t, uint64_t) { return false; });
  2895. ASSERT_TRUE(!res);
  2896. EXPECT_EQ(Error::Canceled, res.error());
  2897. }
  2898. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2899. Server svr;
  2900. svr.set_payload_max_length(200 * 1024 * 1024);
  2901. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2902. res.set_content(LARGE_DATA, "text/plain");
  2903. });
  2904. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2905. auto se = detail::scope_exit([&] {
  2906. svr.stop();
  2907. thread.join();
  2908. ASSERT_FALSE(svr.is_running());
  2909. });
  2910. svr.wait_until_ready();
  2911. Client cli(HOST, PORT);
  2912. cli.set_payload_max_length(200 * 1024 * 1024);
  2913. cli.set_connection_timeout(std::chrono::seconds(5));
  2914. auto res =
  2915. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2916. "application/json", [](uint64_t, uint64_t) { return false; });
  2917. ASSERT_TRUE(!res);
  2918. EXPECT_EQ(Error::Canceled, res.error());
  2919. }
  2920. TEST(CancelTest, NoCancelDelete) {
  2921. Server svr;
  2922. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2923. res.set_content("Hello World!", "text/plain");
  2924. });
  2925. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2926. auto se = detail::scope_exit([&] {
  2927. svr.stop();
  2928. thread.join();
  2929. ASSERT_FALSE(svr.is_running());
  2930. });
  2931. svr.wait_until_ready();
  2932. Client cli(HOST, PORT);
  2933. cli.set_connection_timeout(std::chrono::seconds(5));
  2934. auto res =
  2935. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2936. "application/json", [](uint64_t, uint64_t) { return true; });
  2937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2938. EXPECT_EQ("Hello World!", res->body);
  2939. EXPECT_EQ(StatusCode::OK_200, res->status);
  2940. }
  2941. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2942. Server svr;
  2943. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2944. res.set_content("Hello World!", "text/plain");
  2945. });
  2946. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2947. auto se = detail::scope_exit([&] {
  2948. svr.stop();
  2949. thread.join();
  2950. ASSERT_FALSE(svr.is_running());
  2951. });
  2952. svr.wait_until_ready();
  2953. Client cli(HOST, PORT);
  2954. cli.set_connection_timeout(std::chrono::seconds(5));
  2955. auto res =
  2956. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2957. "application/json", [](uint64_t, uint64_t) { return false; });
  2958. ASSERT_TRUE(!res);
  2959. EXPECT_EQ(Error::Canceled, res.error());
  2960. }
  2961. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2962. Server svr;
  2963. svr.set_payload_max_length(200 * 1024 * 1024);
  2964. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2965. res.set_content(LARGE_DATA, "text/plain");
  2966. });
  2967. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2968. auto se = detail::scope_exit([&] {
  2969. svr.stop();
  2970. thread.join();
  2971. ASSERT_FALSE(svr.is_running());
  2972. });
  2973. svr.wait_until_ready();
  2974. Client cli(HOST, PORT);
  2975. cli.set_payload_max_length(200 * 1024 * 1024);
  2976. cli.set_connection_timeout(std::chrono::seconds(5));
  2977. auto res =
  2978. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2979. "application/json", [](uint64_t, uint64_t) { return false; });
  2980. ASSERT_TRUE(!res);
  2981. EXPECT_EQ(Error::Canceled, res.error());
  2982. }
  2983. // One stop() from another thread ends a request that waits for the response
  2984. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2985. Server svr;
  2986. std::atomic<bool> received{false};
  2987. std::atomic<bool> done{false};
  2988. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2989. received.store(true);
  2990. while (!done.load()) {
  2991. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2992. }
  2993. res.set_content("Hello World!", "text/plain");
  2994. });
  2995. auto port = svr.bind_to_any_port(HOST);
  2996. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2997. Client cli(HOST, port);
  2998. cli.set_read_timeout(std::chrono::seconds(30));
  2999. std::future<Result> request;
  3000. auto se = detail::scope_exit([&] {
  3001. done.store(true);
  3002. svr.stop();
  3003. thread.join();
  3004. ASSERT_FALSE(svr.is_running());
  3005. });
  3006. svr.wait_until_ready();
  3007. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3008. for (int i = 0; i < 500 && !received.load(); ++i) {
  3009. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3010. }
  3011. ASSERT_TRUE(received.load());
  3012. // Let the client block in the wait for the response
  3013. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3014. auto start = std::chrono::steady_clock::now();
  3015. cli.stop();
  3016. ASSERT_EQ(std::future_status::ready,
  3017. request.wait_for(std::chrono::seconds(5)));
  3018. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3019. auto res = request.get();
  3020. ASSERT_TRUE(!res);
  3021. EXPECT_EQ(Error::Read, res.error());
  3022. }
  3023. static std::string remove_whitespace(const std::string &input) {
  3024. std::string output;
  3025. output.reserve(input.size());
  3026. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3027. [](unsigned char c) { return !std::isspace(c); });
  3028. return output;
  3029. }
  3030. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3031. auto host = "httpbingo.org";
  3032. auto path = std::string{"/basic-auth/hello/world"};
  3033. #ifdef CPPHTTPLIB_SSL_ENABLED
  3034. auto port = 443;
  3035. SSLClient cli(host, port);
  3036. #else
  3037. auto port = 80;
  3038. Client cli(host, port);
  3039. #endif
  3040. {
  3041. auto res = cli.Get(path);
  3042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3043. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3044. }
  3045. {
  3046. auto res = cli.Get(
  3047. path, Headers{make_basic_authentication_header("hello", "world")});
  3048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3049. auto body = remove_whitespace(res->body);
  3050. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3051. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3052. EXPECT_EQ(StatusCode::OK_200, res->status);
  3053. }
  3054. {
  3055. cli.set_basic_auth("hello", "world");
  3056. auto res = cli.Get(path);
  3057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3058. auto body = remove_whitespace(res->body);
  3059. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3060. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3061. EXPECT_EQ(StatusCode::OK_200, res->status);
  3062. }
  3063. {
  3064. cli.set_basic_auth("hello", "bad");
  3065. auto res = cli.Get(path);
  3066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3067. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3068. }
  3069. {
  3070. cli.set_basic_auth("bad", "world");
  3071. auto res = cli.Get(path);
  3072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3073. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3074. }
  3075. }
  3076. #ifdef CPPHTTPLIB_SSL_ENABLED
  3077. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3078. auto host = "httpbingo.org";
  3079. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3080. auto paths = std::vector<std::string>{
  3081. "/digest-auth/auth/hello/world/MD5",
  3082. "/digest-auth/auth/hello/world/SHA-256",
  3083. };
  3084. auto port = 443;
  3085. SSLClient cli(host, port);
  3086. {
  3087. auto res = cli.Get(unauth_path);
  3088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3089. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3090. }
  3091. {
  3092. cli.set_digest_auth("hello", "world");
  3093. for (const auto &path : paths) {
  3094. auto res = cli.Get(path.c_str());
  3095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3096. auto body = remove_whitespace(res->body);
  3097. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3098. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3099. EXPECT_EQ(StatusCode::OK_200, res->status);
  3100. }
  3101. cli.set_digest_auth("hello", "bad");
  3102. for (const auto &path : paths) {
  3103. auto res = cli.Get(path.c_str());
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3106. }
  3107. }
  3108. }
  3109. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3110. // comma-separated list of challenges, and each challenge may itself carry a
  3111. // comma-separated auth-param list, so a server can legally offer Basic
  3112. // before Digest, either as two field lines or packed into one. Runs one 401
  3113. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3114. // value() joins them in receipt order) and checks that the retry carries a
  3115. // well-formed Digest Authorization header naming expected_realm.
  3116. static void
  3117. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3118. const std::string &expected_realm) {
  3119. std::atomic<int> hits{0};
  3120. Server svr;
  3121. svr.Get("/x", [&](const Request &req, Response &res) {
  3122. if (++hits == 1) {
  3123. res.status = StatusCode::Unauthorized_401;
  3124. for (const auto &challenge : challenges) {
  3125. res.set_header("WWW-Authenticate", challenge);
  3126. }
  3127. } else {
  3128. auto authorization = req.get_header_value("Authorization");
  3129. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3130. EXPECT_NE(std::string::npos,
  3131. authorization.find("realm=\"" + expected_realm + "\""));
  3132. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3133. res.set_content("ok", "text/plain");
  3134. }
  3135. });
  3136. auto port = svr.bind_to_any_port(HOST);
  3137. std::thread t([&]() { svr.listen_after_bind(); });
  3138. auto se = detail::scope_exit([&] {
  3139. svr.stop();
  3140. t.join();
  3141. });
  3142. svr.wait_until_ready();
  3143. Client cli(HOST, port);
  3144. cli.set_digest_auth("hello", "world");
  3145. auto res = cli.Get("/x");
  3146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3147. EXPECT_EQ(2, hits.load());
  3148. }
  3149. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3150. static const char *kDigestChallenge =
  3151. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3152. "algorithm=MD5";
  3153. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3154. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3155. "testrealm");
  3156. }
  3157. // Same challenge list with the schemes in the opposite order, to make sure
  3158. // the fix above didn't just special-case "Basic first".
  3159. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3160. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3161. "testrealm");
  3162. }
  3163. // A comma inside a quoted auth-param value must not be mistaken for the
  3164. // separator between two challenges (or two auth-params).
  3165. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3166. run_digest_challenge_list_test(
  3167. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3168. "algorithm=MD5"},
  3169. "test,realm");
  3170. }
  3171. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3172. // the params and leaves out the fragment.
  3173. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3174. Server svr;
  3175. std::string uri, target;
  3176. svr.Get("/a b", [&](const Request &req, Response &res) {
  3177. auto auth = req.get_header_value("Authorization");
  3178. if (auth.empty()) {
  3179. res.status = StatusCode::Unauthorized_401;
  3180. res.set_header("WWW-Authenticate",
  3181. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3182. return;
  3183. }
  3184. auto b = auth.find("uri=\"") + 5;
  3185. uri = auth.substr(b, auth.find('"', b) - b);
  3186. target = req.target;
  3187. });
  3188. auto port = svr.bind_to_any_port(HOST);
  3189. std::thread t([&]() { svr.listen_after_bind(); });
  3190. auto se = detail::scope_exit([&] {
  3191. svr.stop();
  3192. t.join();
  3193. });
  3194. svr.wait_until_ready();
  3195. Client cli(HOST, port);
  3196. cli.set_digest_auth("hello", "world");
  3197. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3199. EXPECT_EQ("/a%20b?x=1", target);
  3200. EXPECT_EQ(target, uri);
  3201. }
  3202. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3203. // make_digest_authentication_header() dereferences both unconditionally, so
  3204. // a server sending a challenge missing either one must not be treated as
  3205. // usable -- doing so used to crash the client with std::out_of_range.
  3206. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3207. Server svr;
  3208. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3209. res.status = StatusCode::Unauthorized_401;
  3210. res.set_header("WWW-Authenticate", challenge);
  3211. });
  3212. auto port = svr.bind_to_any_port(HOST);
  3213. std::thread t([&]() { svr.listen_after_bind(); });
  3214. auto se = detail::scope_exit([&] {
  3215. svr.stop();
  3216. t.join();
  3217. });
  3218. svr.wait_until_ready();
  3219. Client cli(HOST, port);
  3220. cli.set_digest_auth("hello", "world");
  3221. auto res = cli.Get("/x");
  3222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3223. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3224. }
  3225. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3226. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3227. }
  3228. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3229. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3230. }
  3231. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3232. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3233. }
  3234. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3235. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3236. // when storing the values, so the header builder has to re-escape them (and
  3237. // keep algorithm a bare token); otherwise the value breaks out of its
  3238. // quoted-string and injects extra auth-params into the client's Authorization.
  3239. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3240. std::atomic<int> hits{0};
  3241. std::string authorization;
  3242. Server svr;
  3243. svr.Get("/x", [&](const Request &req, Response &res) {
  3244. if (++hits == 1) {
  3245. res.status = StatusCode::Unauthorized_401;
  3246. // On the wire the quotes embedded in the values are backslash-escaped.
  3247. res.set_header("WWW-Authenticate",
  3248. "Digest realm=\"testrealm\", "
  3249. "nonce=\"n\\\"; injected=\\\"x\", "
  3250. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3251. } else {
  3252. authorization = req.get_header_value("Authorization");
  3253. res.set_content("ok", "text/plain");
  3254. }
  3255. });
  3256. auto port = svr.bind_to_any_port(HOST);
  3257. std::thread t([&]() { svr.listen_after_bind(); });
  3258. auto se = detail::scope_exit([&] {
  3259. svr.stop();
  3260. t.join();
  3261. });
  3262. svr.wait_until_ready();
  3263. Client cli(HOST, port);
  3264. cli.set_digest_auth("hello", "world");
  3265. auto res = cli.Get("/x");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(2, hits.load());
  3268. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3269. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3270. // inside its quoted-string rather than starting an "injected" auth-param.
  3271. EXPECT_NE(std::string::npos,
  3272. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3273. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3274. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3275. }
  3276. #endif
  3277. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3278. auto host = "google.com";
  3279. auto another_host = "example.com";
  3280. auto wrong_ip = "0.0.0.0";
  3281. #ifdef CPPHTTPLIB_SSL_ENABLED
  3282. SSLClient cli(host);
  3283. #else
  3284. Client cli(host);
  3285. #endif
  3286. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3287. auto res = cli.Get("/");
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3290. }
  3291. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3292. auto host = "google.com";
  3293. auto wrong_ip = "0.0.0.0";
  3294. #ifdef CPPHTTPLIB_SSL_ENABLED
  3295. SSLClient cli(host);
  3296. #else
  3297. Client cli(host);
  3298. #endif
  3299. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3300. auto res = cli.Get("/");
  3301. ASSERT_TRUE(!res);
  3302. EXPECT_EQ(Error::Connection, res.error());
  3303. }
  3304. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3305. // A mapped value that is not an IP literal must be resolved. "localhost"
  3306. // resolves from the hosts file, so this test needs no external DNS.
  3307. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3308. auto host = "target.invalid";
  3309. Server svr;
  3310. std::string received_host;
  3311. svr.Get("/hi", [&](const Request &req, Response &res) {
  3312. received_host = req.get_header_value("Host");
  3313. res.set_content("Hello World!", "text/plain");
  3314. });
  3315. auto port = svr.bind_to_any_port(HOST);
  3316. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3317. auto se = detail::scope_exit([&] {
  3318. svr.stop();
  3319. thread.join();
  3320. ASSERT_FALSE(svr.is_running());
  3321. });
  3322. svr.wait_until_ready();
  3323. Client cli(host, port);
  3324. cli.set_direct_hostname_addr_map({{host, HOST}});
  3325. auto res = cli.Get("/hi");
  3326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3327. EXPECT_EQ(StatusCode::OK_200, res->status);
  3328. // The mapping only redirects the connection; the identity stays host_.
  3329. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3330. }
  3331. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3332. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3333. auto host = "target.invalid";
  3334. Server svr;
  3335. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3336. res.set_content("Hello World!", "text/plain");
  3337. });
  3338. auto port = svr.bind_to_any_port("127.0.0.1");
  3339. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3340. auto se = detail::scope_exit([&] {
  3341. svr.stop();
  3342. thread.join();
  3343. ASSERT_FALSE(svr.is_running());
  3344. });
  3345. svr.wait_until_ready();
  3346. Client cli(host, port);
  3347. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3348. auto res = cli.Get("/hi");
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. }
  3352. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3353. // An empty mapped value must leave host_ as the connection target. Without
  3354. // that guard the empty value would become the host argument, getaddrinfo
  3355. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3356. // loopback - silently connecting somewhere the caller never asked for.
  3357. // The server listens on loopback, so such a fallback would succeed and is
  3358. // therefore observable as a failure of this test.
  3359. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3360. Server svr;
  3361. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3362. res.set_content("Hello World!", "text/plain");
  3363. });
  3364. auto port = svr.bind_to_any_port(HOST);
  3365. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3366. auto se = detail::scope_exit([&] {
  3367. svr.stop();
  3368. thread.join();
  3369. ASSERT_FALSE(svr.is_running());
  3370. });
  3371. svr.wait_until_ready();
  3372. Client cli(blackhole, port);
  3373. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3374. cli.set_connection_timeout(1);
  3375. auto res = cli.Get("/hi");
  3376. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3377. }
  3378. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3379. auto host = "target.invalid";
  3380. Server svr;
  3381. std::string received_host;
  3382. svr.Get("/hi", [&](const Request &req, Response &res) {
  3383. received_host = req.get_header_value("Host");
  3384. res.set_content("Hello World!", "text/plain");
  3385. });
  3386. auto port = svr.bind_to_any_port("127.0.0.1");
  3387. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3388. auto se = detail::scope_exit([&] {
  3389. svr.stop();
  3390. thread.join();
  3391. ASSERT_FALSE(svr.is_running());
  3392. });
  3393. svr.wait_until_ready();
  3394. Client cli(host, port);
  3395. #pragma GCC diagnostic push
  3396. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3397. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3398. #pragma GCC diagnostic pop
  3399. auto res = cli.Get("/hi");
  3400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3401. EXPECT_EQ(StatusCode::OK_200, res->status);
  3402. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3403. }
  3404. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3405. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3406. Server svr;
  3407. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3408. res.set_content("Hello World!", "text/plain");
  3409. });
  3410. auto port = svr.bind_to_any_port("127.0.0.1");
  3411. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3412. auto se = detail::scope_exit([&] {
  3413. svr.stop();
  3414. thread.join();
  3415. ASSERT_FALSE(svr.is_running());
  3416. });
  3417. svr.wait_until_ready();
  3418. Client cli("127.0.0.1", port);
  3419. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3420. cli.set_connection_timeout(1);
  3421. auto res = cli.Get("/hi");
  3422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3423. EXPECT_EQ(StatusCode::OK_200, res->status);
  3424. }
  3425. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3426. auto host = "httpbingo.org";
  3427. auto path = std::string{"/absolute-redirect/3"};
  3428. #ifdef CPPHTTPLIB_SSL_ENABLED
  3429. SSLClient cli(host);
  3430. #else
  3431. Client cli(host);
  3432. #endif
  3433. cli.set_follow_location(true);
  3434. auto res = cli.Get(path);
  3435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3436. EXPECT_EQ(StatusCode::OK_200, res->status);
  3437. }
  3438. TEST(RedirectTest, Redirect_Online) {
  3439. auto host = "httpbingo.org";
  3440. auto path = std::string{"/redirect/3"};
  3441. #ifdef CPPHTTPLIB_SSL_ENABLED
  3442. SSLClient cli(host);
  3443. #else
  3444. Client cli(host);
  3445. #endif
  3446. cli.set_follow_location(true);
  3447. auto res = cli.Get(path);
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. }
  3451. TEST(RelativeRedirectTest, Redirect_Online) {
  3452. auto host = "httpbingo.org";
  3453. auto path = std::string{"/relative-redirect/3"};
  3454. #ifdef CPPHTTPLIB_SSL_ENABLED
  3455. SSLClient cli(host);
  3456. #else
  3457. Client cli(host);
  3458. #endif
  3459. cli.set_follow_location(true);
  3460. auto res = cli.Get(path);
  3461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3462. EXPECT_EQ(StatusCode::OK_200, res->status);
  3463. }
  3464. TEST(TooManyRedirectTest, Redirect_Online) {
  3465. auto host = "httpbingo.org";
  3466. auto path = std::string{"/redirect/21"};
  3467. #ifdef CPPHTTPLIB_SSL_ENABLED
  3468. SSLClient cli(host);
  3469. #else
  3470. Client cli(host);
  3471. #endif
  3472. cli.set_follow_location(true);
  3473. auto res = cli.Get(path);
  3474. ASSERT_TRUE(!res);
  3475. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3476. }
  3477. #ifdef CPPHTTPLIB_SSL_ENABLED
  3478. TEST(YahooRedirectTest, Redirect_Online) {
  3479. Client cli("yahoo.com");
  3480. auto res = cli.Get("/");
  3481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3482. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3483. cli.set_follow_location(true);
  3484. res = cli.Get("/");
  3485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3486. EXPECT_EQ(StatusCode::OK_200, res->status);
  3487. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3488. }
  3489. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3490. #define REDIR_HOST "httpbingo.org"
  3491. #define REDIR_PATH "/redirect-to"
  3492. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3493. SSLClient cli(REDIR_HOST);
  3494. cli.set_follow_location(true);
  3495. auto res =
  3496. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3498. EXPECT_EQ(StatusCode::OK_200, res->status);
  3499. }
  3500. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3501. SSLClient cli(REDIR_HOST);
  3502. cli.set_follow_location(true);
  3503. Params params;
  3504. params.emplace("url", "http://example.com");
  3505. params.emplace("status_code", "302");
  3506. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. }
  3510. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3511. SSLClient cli(REDIR_HOST);
  3512. cli.set_follow_location(true);
  3513. Params params;
  3514. params.emplace("url", "http://example.com");
  3515. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3517. EXPECT_EQ(StatusCode::OK_200, res->status);
  3518. }
  3519. TEST(UrlWithSpace, Redirect_Online) {
  3520. SSLClient cli("edge.forgecdn.net");
  3521. cli.set_follow_location(true);
  3522. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3524. EXPECT_EQ(StatusCode::OK_200, res->status);
  3525. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3526. }
  3527. #endif
  3528. #if !defined(_WIN32) && !defined(_WIN64)
  3529. TEST(ReceiveSignals, Signal) {
  3530. auto setupSignalHandlers = []() {
  3531. struct sigaction act;
  3532. sigemptyset(&act.sa_mask);
  3533. act.sa_flags = SA_SIGINFO;
  3534. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3535. switch (sig) {
  3536. case SIGINT:
  3537. default: break;
  3538. }
  3539. };
  3540. ::sigaction(SIGINT, &act, nullptr);
  3541. };
  3542. Server svr;
  3543. int port = 0;
  3544. auto thread = std::thread([&]() {
  3545. setupSignalHandlers();
  3546. port = svr.bind_to_any_port(HOST);
  3547. svr.listen_after_bind();
  3548. });
  3549. auto se = detail::scope_exit([&] {
  3550. svr.stop();
  3551. thread.join();
  3552. ASSERT_FALSE(svr.is_running());
  3553. });
  3554. svr.wait_until_ready();
  3555. ASSERT_TRUE(svr.is_running());
  3556. pthread_kill(thread.native_handle(), SIGINT);
  3557. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3558. ASSERT_TRUE(svr.is_running());
  3559. }
  3560. #endif
  3561. TEST(RedirectToDifferentPort, Redirect) {
  3562. Server svr1;
  3563. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("Hello World!", "text/plain");
  3565. });
  3566. int svr1_port = 0;
  3567. auto thread1 = std::thread([&]() {
  3568. svr1_port = svr1.bind_to_any_port(HOST);
  3569. svr1.listen_after_bind();
  3570. });
  3571. Server svr2;
  3572. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3573. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3574. });
  3575. int svr2_port = 0;
  3576. auto thread2 = std::thread([&]() {
  3577. svr2_port = svr2.bind_to_any_port(HOST);
  3578. svr2.listen_after_bind();
  3579. });
  3580. auto se = detail::scope_exit([&] {
  3581. svr2.stop();
  3582. thread2.join();
  3583. svr1.stop();
  3584. thread1.join();
  3585. ASSERT_FALSE(svr2.is_running());
  3586. ASSERT_FALSE(svr1.is_running());
  3587. });
  3588. svr1.wait_until_ready();
  3589. svr2.wait_until_ready();
  3590. Client cli("localhost", svr2_port);
  3591. cli.set_follow_location(true);
  3592. auto res = cli.Get("/2");
  3593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3594. EXPECT_EQ(StatusCode::OK_200, res->status);
  3595. EXPECT_EQ("Hello World!", res->body);
  3596. }
  3597. // GET /redir on one server redirects to /target on another port, so the
  3598. // client follows it with a new client.
  3599. static Result
  3600. GetThroughRedirectToDifferentPort(Server::Handler target,
  3601. const std::function<void(Client &)> &setup,
  3602. const Headers &headers = Headers()) {
  3603. Server target_svr;
  3604. target_svr.Get("/target", target);
  3605. int target_port = 0;
  3606. auto target_thread = std::thread([&]() {
  3607. target_port = target_svr.bind_to_any_port(HOST);
  3608. target_svr.listen_after_bind();
  3609. });
  3610. Server origin_svr;
  3611. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3612. res.set_redirect(
  3613. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3614. });
  3615. int origin_port = 0;
  3616. auto origin_thread = std::thread([&]() {
  3617. origin_port = origin_svr.bind_to_any_port(HOST);
  3618. origin_svr.listen_after_bind();
  3619. });
  3620. auto se = detail::scope_exit([&] {
  3621. origin_svr.stop();
  3622. origin_thread.join();
  3623. target_svr.stop();
  3624. target_thread.join();
  3625. });
  3626. target_svr.wait_until_ready();
  3627. origin_svr.wait_until_ready();
  3628. Client cli("localhost", origin_port);
  3629. cli.set_follow_location(true);
  3630. setup(cli);
  3631. return cli.Get("/redir", headers);
  3632. }
  3633. static void
  3634. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3635. std::string captured_authorization;
  3636. auto result = GetThroughRedirectToDifferentPort(
  3637. [&](const Request &req, Response &res) {
  3638. captured_authorization = req.get_header_value("Authorization");
  3639. res.set_content("OK", "text/plain");
  3640. },
  3641. set_auth);
  3642. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3643. EXPECT_EQ(StatusCode::OK_200, result->status);
  3644. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3645. EXPECT_TRUE(captured_authorization.empty());
  3646. }
  3647. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3648. TestDoNotForwardCredentialsOnRedirect(
  3649. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3650. }
  3651. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3652. TestDoNotForwardCredentialsOnRedirect(
  3653. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3654. }
  3655. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3656. std::string captured_cookie;
  3657. auto result = GetThroughRedirectToDifferentPort(
  3658. [&](const Request &req, Response &res) {
  3659. captured_cookie = req.get_header_value("Cookie");
  3660. res.set_content("OK", "text/plain");
  3661. },
  3662. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3663. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3664. EXPECT_EQ(StatusCode::OK_200, result->status);
  3665. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3666. EXPECT_TRUE(captured_cookie.empty());
  3667. }
  3668. TEST(RedirectToSamePort, ForwardCookie) {
  3669. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3670. // header so that ordinary session flows keep working.
  3671. Server svr;
  3672. std::string captured_cookie;
  3673. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3674. res.set_redirect("/target", 302);
  3675. });
  3676. svr.Get("/target", [&](const Request &req, Response &res) {
  3677. captured_cookie = req.get_header_value("Cookie");
  3678. res.set_content("OK", "text/plain");
  3679. });
  3680. auto port = svr.bind_to_any_port(HOST);
  3681. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3682. auto se = detail::scope_exit([&] {
  3683. svr.stop();
  3684. thread.join();
  3685. ASSERT_FALSE(svr.is_running());
  3686. });
  3687. svr.wait_until_ready();
  3688. Client cli(HOST, port);
  3689. cli.set_follow_location(true);
  3690. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3691. auto res = cli.Get("/redir", headers);
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::OK_200, res->status);
  3694. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3695. }
  3696. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3697. // The Location alone names the next target, on any origin.
  3698. Server target_svr;
  3699. std::string cross_target;
  3700. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3701. cross_target = req.target;
  3702. res.set_content("OK", "text/plain");
  3703. });
  3704. auto target_port = target_svr.bind_to_any_port(HOST);
  3705. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3706. Server origin_svr;
  3707. std::string same_target;
  3708. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3709. res.set_redirect(
  3710. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3711. });
  3712. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3713. res.set_redirect("/landing", 302);
  3714. });
  3715. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3716. same_target = req.target;
  3717. res.set_content("OK", "text/plain");
  3718. });
  3719. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3720. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3721. auto se = detail::scope_exit([&] {
  3722. origin_svr.stop();
  3723. origin_thread.join();
  3724. target_svr.stop();
  3725. target_thread.join();
  3726. });
  3727. target_svr.wait_until_ready();
  3728. origin_svr.wait_until_ready();
  3729. Client cli("localhost", origin_port);
  3730. cli.set_follow_location(true);
  3731. Request req;
  3732. req.method = "GET";
  3733. req.params = {{"api_key", "SECRET"}};
  3734. req.path = "/cross";
  3735. auto res = cli.send(req);
  3736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3737. EXPECT_EQ("/landing", cross_target);
  3738. req.path = "/same";
  3739. res = cli.send(req);
  3740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3741. EXPECT_EQ("/landing", same_target);
  3742. }
  3743. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3744. std::string authorization;
  3745. std::string trace_id;
  3746. auto result = GetThroughRedirectToDifferentPort(
  3747. [&](const Request &req, Response &res) {
  3748. authorization = req.get_header_value("Authorization");
  3749. trace_id = req.get_header_value("X-Trace-Id");
  3750. res.set_content("OK", "text/plain");
  3751. },
  3752. [](Client &cli) {
  3753. cli.set_default_headers(
  3754. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3755. });
  3756. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3757. EXPECT_EQ(StatusCode::OK_200, result->status);
  3758. // Like a header given with the request, a default one goes along unless it
  3759. // carries credentials (RFC 9110 15.4).
  3760. EXPECT_TRUE(authorization.empty());
  3761. EXPECT_EQ("42", trace_id);
  3762. }
  3763. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3764. auto result = GetThroughRedirectToDifferentPort(
  3765. [](const Request &, Response &res) {
  3766. res.set_content(std::string(2048, 'x'), "text/plain");
  3767. },
  3768. [](Client &cli) { cli.set_payload_max_length(1024); });
  3769. EXPECT_FALSE(result);
  3770. }
  3771. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3772. auto result = GetThroughRedirectToDifferentPort(
  3773. [](const Request &req, Response &res) {
  3774. // Answer after a second, or once the client gives up.
  3775. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3776. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3777. }
  3778. res.set_content("late", "text/plain");
  3779. },
  3780. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3781. ASSERT_FALSE(result);
  3782. EXPECT_EQ(Error::Read, result.error());
  3783. }
  3784. #ifdef CPPHTTPLIB_SSL_ENABLED
  3785. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3786. auto result = GetThroughRedirectToDifferentPort(
  3787. [](const Request &, Response &res) {
  3788. res.status = StatusCode::Unauthorized_401;
  3789. res.set_header("WWW-Authenticate",
  3790. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3791. },
  3792. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3793. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3794. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3795. }
  3796. #endif
  3797. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3798. Server svr;
  3799. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3800. // Port number that overflows int — should not crash
  3801. res.set_redirect("http://localhost:99999999999999999999/target");
  3802. });
  3803. auto port = svr.bind_to_any_port(HOST);
  3804. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3805. auto se = detail::scope_exit([&] {
  3806. svr.stop();
  3807. thread.join();
  3808. ASSERT_FALSE(svr.is_running());
  3809. });
  3810. svr.wait_until_ready();
  3811. Client cli(HOST, port);
  3812. cli.set_follow_location(true);
  3813. auto res = cli.Get("/redir");
  3814. // Should fail gracefully, not crash (no valid response due to bad port)
  3815. EXPECT_FALSE(res);
  3816. }
  3817. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3818. Server svr;
  3819. auto port = svr.bind_to_any_port(HOST);
  3820. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3821. // The server's own port followed by junk must not be followed
  3822. res.set_redirect("http://" + std::string(HOST) + ":" +
  3823. std::to_string(port) + "junk/target");
  3824. });
  3825. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3826. res.set_content("target", "text/plain");
  3827. });
  3828. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3829. auto se = detail::scope_exit([&] {
  3830. svr.stop();
  3831. thread.join();
  3832. ASSERT_FALSE(svr.is_running());
  3833. });
  3834. svr.wait_until_ready();
  3835. Client cli(HOST, port);
  3836. cli.set_follow_location(true);
  3837. auto res = cli.Get("/redir");
  3838. EXPECT_FALSE(res);
  3839. }
  3840. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3841. Server svr;
  3842. std::atomic<bool> followed{false};
  3843. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3844. res.status = StatusCode::NotModified_304;
  3845. res.set_header("Location", "/target");
  3846. });
  3847. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3848. res.status = StatusCode::UseProxy_305;
  3849. res.set_header("Location", "/target");
  3850. });
  3851. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3852. followed = true;
  3853. res.set_content("target", "text/plain");
  3854. });
  3855. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3856. auto se = detail::scope_exit([&] {
  3857. svr.stop();
  3858. th.join();
  3859. ASSERT_FALSE(svr.is_running());
  3860. });
  3861. svr.wait_until_ready();
  3862. Client cli("localhost", PORT);
  3863. cli.set_follow_location(true);
  3864. auto res = cli.Get("/304");
  3865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3866. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3867. res = cli.Get("/305");
  3868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3869. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3870. EXPECT_FALSE(followed);
  3871. }
  3872. TEST(RedirectFromPageWithContent, Redirect) {
  3873. Server svr;
  3874. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3875. res.set_content("___", "text/plain");
  3876. res.set_redirect("/2");
  3877. });
  3878. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3879. res.set_content("Hello World!", "text/plain");
  3880. });
  3881. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3882. auto se = detail::scope_exit([&] {
  3883. svr.stop();
  3884. th.join();
  3885. ASSERT_FALSE(svr.is_running());
  3886. });
  3887. svr.wait_until_ready();
  3888. {
  3889. Client cli("localhost", PORT);
  3890. cli.set_follow_location(true);
  3891. std::string body;
  3892. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3893. body.append(data, data_length);
  3894. return true;
  3895. });
  3896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3897. EXPECT_EQ(StatusCode::OK_200, res->status);
  3898. EXPECT_EQ("Hello World!", body);
  3899. }
  3900. {
  3901. Client cli("localhost", PORT);
  3902. std::string body;
  3903. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3904. body.append(data, data_length);
  3905. return true;
  3906. });
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ(StatusCode::Found_302, res->status);
  3909. EXPECT_EQ("___", body);
  3910. }
  3911. }
  3912. // A server can close the connection after a request with "Connection: close"
  3913. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3914. // redirected request must go out on a new connection.
  3915. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3916. #ifndef _WIN32
  3917. signal(SIGPIPE, SIG_IGN);
  3918. #endif
  3919. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3920. default_socket_options(srv);
  3921. sockaddr_in addr{};
  3922. addr.sin_family = AF_INET;
  3923. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3924. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3925. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3926. ASSERT_EQ(0, ::listen(srv, 2));
  3927. auto send_text = [](socket_t sock, const std::string &text) {
  3928. ::send(sock,
  3929. #ifdef _WIN32
  3930. static_cast<const char *>(text.c_str()),
  3931. static_cast<int>(text.size()),
  3932. #else
  3933. text.c_str(), text.size(),
  3934. #endif
  3935. 0);
  3936. };
  3937. auto reused = false;
  3938. auto server_thread = std::thread([&] {
  3939. char buf[4096];
  3940. auto first = ::accept(srv, nullptr, nullptr);
  3941. if (first == INVALID_SOCKET) { return; }
  3942. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3943. ::recv(first, buf, sizeof(buf), 0);
  3944. send_text(
  3945. first,
  3946. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3947. auto next = first;
  3948. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3949. reused = true;
  3950. } else {
  3951. detail::close_socket(first);
  3952. next = ::accept(srv, nullptr, nullptr);
  3953. if (next == INVALID_SOCKET) { return; }
  3954. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3955. ::recv(next, buf, sizeof(buf), 0);
  3956. }
  3957. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3958. "Connection: close\r\n\r\nok");
  3959. detail::close_socket(next);
  3960. });
  3961. Client cli("127.0.0.1", PORT + 2);
  3962. cli.set_follow_location(true);
  3963. cli.set_read_timeout(5, 0);
  3964. auto res = cli.Get("/1");
  3965. server_thread.join();
  3966. detail::close_socket(srv);
  3967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3968. EXPECT_EQ(StatusCode::OK_200, res->status);
  3969. EXPECT_EQ("ok", res->body);
  3970. EXPECT_FALSE(reused);
  3971. }
  3972. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3973. Server svr;
  3974. auto port_str = std::to_string(PORT);
  3975. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3976. auto expected_host = "[::1]:" + port_str;
  3977. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3978. res.set_content("___", "text/plain");
  3979. // res.set_redirect("/2");
  3980. res.set_redirect(redirect_url);
  3981. });
  3982. svr.Get("/2", [&](const Request &req, Response &res) {
  3983. auto host_header = req.headers.find("Host");
  3984. ASSERT_TRUE(host_header != req.headers.end());
  3985. EXPECT_EQ(expected_host, host_header->second);
  3986. res.set_content("Hello World!", "text/plain");
  3987. });
  3988. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3989. auto se = detail::scope_exit([&] {
  3990. svr.stop();
  3991. th.join();
  3992. ASSERT_FALSE(svr.is_running());
  3993. });
  3994. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3995. // actually starts anything, so the condition !svr.is_running() will
  3996. // always remain true, and the loop never stops.
  3997. // This basically counts how many milliseconds have passed since the
  3998. // call to svr.listen(), and if after 5 seconds nothing started yet
  3999. // aborts the test.
  4000. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4001. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4002. ASSERT_LT(milliseconds, 5000U);
  4003. }
  4004. {
  4005. Client cli("::1", PORT);
  4006. cli.set_follow_location(true);
  4007. std::string body;
  4008. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4009. body.append(data, data_length);
  4010. return true;
  4011. });
  4012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4013. EXPECT_EQ(StatusCode::OK_200, res->status);
  4014. EXPECT_EQ("Hello World!", body);
  4015. }
  4016. {
  4017. Client cli("::1", PORT);
  4018. std::string body;
  4019. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4020. body.append(data, data_length);
  4021. return true;
  4022. });
  4023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4024. EXPECT_EQ(StatusCode::Found_302, res->status);
  4025. EXPECT_EQ("___", body);
  4026. }
  4027. }
  4028. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4029. Server svr;
  4030. svr.Get("/foo", [](const Request &req, Response &res) {
  4031. auto a = req.params.find("a");
  4032. if (a != req.params.end()) {
  4033. res.set_content((*a).second, "text/plain");
  4034. res.status = StatusCode::OK_200;
  4035. } else {
  4036. res.status = StatusCode::BadRequest_400;
  4037. }
  4038. });
  4039. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. thread.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. {
  4047. Client cli(HOST, PORT);
  4048. cli.set_path_encode(false);
  4049. auto res = cli.Get("/foo?a=explicitly+encoded");
  4050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4051. EXPECT_EQ(StatusCode::OK_200, res->status);
  4052. // This expects it back with a space, as the `+` won't have been
  4053. // url-encoded, and server-side the params get decoded turning `+`
  4054. // into spaces.
  4055. EXPECT_EQ("explicitly encoded", res->body);
  4056. }
  4057. }
  4058. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4059. // When path encoding is disabled the client must transmit the supplied
  4060. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4061. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4062. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4063. // than a space (0x20). Assert on the raw wire target to catch this.
  4064. Server svr;
  4065. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4066. svr.Get("/foo", [&](const Request &req, Response &res) {
  4067. EXPECT_EQ(expected_target, req.target);
  4068. res.status = StatusCode::OK_200;
  4069. });
  4070. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4071. auto se = detail::scope_exit([&] {
  4072. svr.stop();
  4073. thread.join();
  4074. ASSERT_FALSE(svr.is_running());
  4075. });
  4076. svr.wait_until_ready();
  4077. {
  4078. Client cli(HOST, PORT);
  4079. cli.set_path_encode(false);
  4080. auto res = cli.Get(expected_target.c_str());
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. EXPECT_EQ(StatusCode::OK_200, res->status);
  4083. }
  4084. }
  4085. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4086. // `open_stream()` used to skip the path encoding that the buffered send
  4087. // path applies, so the same `path` produced different bytes in the request
  4088. // line depending on which API was used. Assert the two agree.
  4089. Server svr;
  4090. std::string target;
  4091. svr.Get(".*", [&](const Request &req, Response &res) {
  4092. target = req.target;
  4093. res.status = StatusCode::OK_200;
  4094. });
  4095. auto port = svr.bind_to_any_port(HOST);
  4096. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4097. auto se = detail::scope_exit([&] {
  4098. svr.stop();
  4099. thread.join();
  4100. ASSERT_FALSE(svr.is_running());
  4101. });
  4102. svr.wait_until_ready();
  4103. struct {
  4104. const char *path;
  4105. const char *expected;
  4106. } cases[] = {
  4107. {"/a b?x=1", "/a%20b?x=1"},
  4108. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4109. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4110. };
  4111. for (const auto &c : cases) {
  4112. Client cli(HOST, port);
  4113. target.clear();
  4114. auto res = cli.Get(c.path);
  4115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4116. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4117. auto buffered_target = target;
  4118. target.clear();
  4119. auto handle = cli.open_stream("GET", c.path);
  4120. EXPECT_TRUE(handle.is_valid())
  4121. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4122. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4123. }
  4124. }
  4125. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4126. // The `set_path_encode(false)` contract — transmit the supplied target
  4127. // verbatim — must hold for the streaming API too.
  4128. Server svr;
  4129. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4130. std::string target;
  4131. svr.Get("/foo", [&](const Request &req, Response &res) {
  4132. target = req.target;
  4133. res.status = StatusCode::OK_200;
  4134. });
  4135. auto port = svr.bind_to_any_port(HOST);
  4136. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4137. auto se = detail::scope_exit([&] {
  4138. svr.stop();
  4139. thread.join();
  4140. ASSERT_FALSE(svr.is_running());
  4141. });
  4142. svr.wait_until_ready();
  4143. {
  4144. Client cli(HOST, port);
  4145. cli.set_path_encode(false);
  4146. auto handle = cli.open_stream("GET", expected_target);
  4147. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4148. EXPECT_EQ(expected_target, target);
  4149. }
  4150. }
  4151. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4152. // With path encoding enabled a CR/LF in the target is percent-encoded
  4153. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4154. // write_request_line still backstops `set_path_encode(false)`, which is
  4155. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4156. Server svr;
  4157. // Captured before routing: the decoded path contains a newline, which a
  4158. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4159. std::string target;
  4160. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4161. target = req.target;
  4162. res.status = StatusCode::OK_200;
  4163. return Server::HandlerResponse::Handled;
  4164. });
  4165. auto port = svr.bind_to_any_port(HOST);
  4166. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4167. auto se = detail::scope_exit([&] {
  4168. svr.stop();
  4169. thread.join();
  4170. ASSERT_FALSE(svr.is_running());
  4171. });
  4172. svr.wait_until_ready();
  4173. {
  4174. Client cli(HOST, port);
  4175. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4176. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4177. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4178. }
  4179. }
  4180. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4181. // Every control character is percent-encoded, not just CR/LF, so the target
  4182. // passes the request-target check in write_request_line.
  4183. Server svr;
  4184. std::string target;
  4185. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4186. target = req.target;
  4187. res.status = StatusCode::OK_200;
  4188. return Server::HandlerResponse::Handled;
  4189. });
  4190. auto port = svr.bind_to_any_port(HOST);
  4191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4192. auto se = detail::scope_exit([&] {
  4193. svr.stop();
  4194. thread.join();
  4195. ASSERT_FALSE(svr.is_running());
  4196. });
  4197. svr.wait_until_ready();
  4198. {
  4199. Client cli(HOST, port);
  4200. auto res = cli.Get("/a\tb\x1b\x7f");
  4201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4202. EXPECT_EQ("/a%09b%1B%7F", target);
  4203. }
  4204. }
  4205. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4206. // Nothing may reach the wire: a raw CR/LF target would split the request
  4207. // line and inject headers.
  4208. Server svr;
  4209. // Pre-routing so that "not called" means nothing reached the server at all,
  4210. // rather than merely failing to match a handler pattern.
  4211. auto handler_called = false;
  4212. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4213. handler_called = true;
  4214. res.status = StatusCode::OK_200;
  4215. return Server::HandlerResponse::Handled;
  4216. });
  4217. auto port = svr.bind_to_any_port(HOST);
  4218. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4219. auto se = detail::scope_exit([&] {
  4220. svr.stop();
  4221. thread.join();
  4222. ASSERT_FALSE(svr.is_running());
  4223. });
  4224. svr.wait_until_ready();
  4225. {
  4226. Client cli(HOST, port);
  4227. cli.set_path_encode(false);
  4228. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4229. EXPECT_FALSE(handle.is_valid());
  4230. EXPECT_EQ(Error::Write, handle.error);
  4231. EXPECT_FALSE(handler_called);
  4232. }
  4233. }
  4234. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4235. // Which of the two branches runs is decided by whether the query component
  4236. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4237. // an empty query and must still fall back to building one from
  4238. // `req.params`, while a non-empty query must win over `req.params`.
  4239. Server svr;
  4240. std::string target;
  4241. svr.Get("/foo", [&](const Request &req, Response &res) {
  4242. target = req.target;
  4243. res.status = StatusCode::OK_200;
  4244. });
  4245. auto port = svr.bind_to_any_port(HOST);
  4246. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4247. auto se = detail::scope_exit([&] {
  4248. svr.stop();
  4249. thread.join();
  4250. ASSERT_FALSE(svr.is_running());
  4251. });
  4252. svr.wait_until_ready();
  4253. {
  4254. // Trailing `?` -> empty query component -> `req.params` is used.
  4255. Client cli(HOST, port);
  4256. Request req;
  4257. req.method = "GET";
  4258. req.path = "/foo?";
  4259. req.params.emplace("a", "1");
  4260. target.clear();
  4261. auto res = cli.send(req);
  4262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4263. EXPECT_EQ("/foo?a=1", target);
  4264. }
  4265. {
  4266. // Non-empty query in `req.path` -> `req.params` is not appended.
  4267. Client cli(HOST, port);
  4268. Request req;
  4269. req.method = "GET";
  4270. req.path = "/foo?b=2";
  4271. req.params.emplace("a", "1");
  4272. target.clear();
  4273. auto res = cli.send(req);
  4274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4275. EXPECT_EQ("/foo?b=2", target);
  4276. }
  4277. }
  4278. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4279. Server svr;
  4280. svr.Get("/", [](const Request &req, Response &) {
  4281. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4282. });
  4283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4284. auto se = detail::scope_exit([&] {
  4285. svr.stop();
  4286. thread.join();
  4287. ASSERT_FALSE(svr.is_running());
  4288. });
  4289. svr.wait_until_ready();
  4290. {
  4291. Client cli(HOST, PORT);
  4292. cli.set_path_encode(false);
  4293. auto res = cli.Get("/?something=%0A");
  4294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. }
  4297. }
  4298. TEST(BindServerTest, BindDualStack) {
  4299. Server svr;
  4300. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4301. res.set_content("Hello World!", "text/plain");
  4302. });
  4303. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4304. auto se = detail::scope_exit([&] {
  4305. svr.stop();
  4306. thread.join();
  4307. ASSERT_FALSE(svr.is_running());
  4308. });
  4309. svr.wait_until_ready();
  4310. {
  4311. Client cli("127.0.0.1", PORT);
  4312. auto res = cli.Get("/1");
  4313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4314. EXPECT_EQ(StatusCode::OK_200, res->status);
  4315. EXPECT_EQ("Hello World!", res->body);
  4316. }
  4317. {
  4318. Client cli("::1", PORT);
  4319. auto res = cli.Get("/1");
  4320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4321. EXPECT_EQ(StatusCode::OK_200, res->status);
  4322. EXPECT_EQ("Hello World!", res->body);
  4323. }
  4324. }
  4325. TEST(BindServerTest, BindAndListenSeparately) {
  4326. Server svr;
  4327. int port = svr.bind_to_any_port("0.0.0.0");
  4328. ASSERT_TRUE(svr.is_valid());
  4329. ASSERT_TRUE(port > 0);
  4330. svr.stop();
  4331. }
  4332. // Reports whether anything is still listening on a loopback port. A plain
  4333. // connect() is used instead of a Client request because a socket left bound by
  4334. // mistake accepts the connection into its backlog and never answers, which
  4335. // would hang the test instead of failing it.
  4336. static bool is_loopback_port_accepting(int port) {
  4337. sockaddr_in addr{};
  4338. addr.sin_family = AF_INET;
  4339. addr.sin_port = htons(static_cast<uint16_t>(port));
  4340. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4341. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4342. EXPECT_NE(sock, INVALID_SOCKET);
  4343. if (sock == INVALID_SOCKET) { return false; }
  4344. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4345. static_cast<socklen_t>(sizeof(addr)));
  4346. detail::close_socket(sock);
  4347. return ret == 0;
  4348. }
  4349. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4350. Server svr;
  4351. auto port = svr.bind_to_any_port("127.0.0.1");
  4352. ASSERT_TRUE(port > 0);
  4353. svr.stop();
  4354. // bind_to_any_port() already called listen(2), so until stop() closed the
  4355. // descriptor the port kept accepting connections into the backlog. ASSERT
  4356. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4357. // below blocks forever in the accept loop.
  4358. ASSERT_FALSE(is_loopback_port_accepting(port));
  4359. // Nothing is left to accept on, so listen_after_bind() must report failure
  4360. // instead of returning success without ever serving.
  4361. EXPECT_FALSE(svr.listen_after_bind());
  4362. // The failed listen marks the server decommissioned, so a waiter returns
  4363. // instead of spinning forever.
  4364. svr.wait_until_ready();
  4365. }
  4366. #ifdef CPPHTTPLIB_SSL_ENABLED
  4367. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4368. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4369. CLIENT_CA_CERT_DIR);
  4370. int port = svr.bind_to_any_port("0.0.0.0");
  4371. ASSERT_TRUE(svr.is_valid());
  4372. ASSERT_TRUE(port > 0);
  4373. svr.stop();
  4374. }
  4375. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4376. // or a rejected CustomRoute() registration would not stop the server binding.
  4377. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4378. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4379. CLIENT_CA_CERT_DIR);
  4380. ASSERT_TRUE(svr.is_valid());
  4381. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4382. EXPECT_FALSE(svr.is_valid());
  4383. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4384. }
  4385. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4386. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4387. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4388. int port = svr.bind_to_any_port("0.0.0.0");
  4389. ASSERT_TRUE(svr.is_valid());
  4390. ASSERT_TRUE(port > 0);
  4391. svr.stop();
  4392. }
  4393. TEST(BindServerTest, UpdateCertsPem) {
  4394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4395. int port = svr.bind_to_any_port("0.0.0.0");
  4396. ASSERT_TRUE(svr.is_valid());
  4397. ASSERT_TRUE(port > 0);
  4398. // Read PEM files
  4399. std::string cert_pem, key_pem, ca_pem;
  4400. read_file(SERVER_CERT_FILE, cert_pem);
  4401. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4402. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4403. // Update server certificates using PEM API
  4404. ASSERT_TRUE(
  4405. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4406. ASSERT_TRUE(svr.is_valid());
  4407. svr.stop();
  4408. }
  4409. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4410. // Start server with client CA (enables client auth)
  4411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4412. ASSERT_TRUE(svr.is_valid());
  4413. bool handler_called = false;
  4414. svr.Get("/test", [&](const Request &req, Response &res) {
  4415. handler_called = true;
  4416. // Verify client certificate is present
  4417. auto cert = req.peer_cert();
  4418. EXPECT_TRUE(static_cast<bool>(cert));
  4419. res.set_content("ok", "text/plain");
  4420. });
  4421. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4422. auto se = detail::scope_exit([&] {
  4423. svr.stop();
  4424. t.join();
  4425. ASSERT_FALSE(svr.is_running());
  4426. });
  4427. svr.wait_until_ready();
  4428. // Read PEM files
  4429. std::string cert_pem, key_pem, ca_pem;
  4430. read_file(SERVER_CERT_FILE, cert_pem);
  4431. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4432. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4433. // Update server certificates and client CA using PEM API while server running
  4434. ASSERT_TRUE(
  4435. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4436. // Connect with client certificate
  4437. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4438. cli.enable_server_certificate_verification(false);
  4439. cli.set_connection_timeout(30);
  4440. auto res = cli.Get("/test");
  4441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4442. ASSERT_EQ(StatusCode::OK_200, res->status);
  4443. ASSERT_TRUE(handler_called);
  4444. EXPECT_EQ("ok", res->body);
  4445. }
  4446. // Puts a CA that did not sign the client's certificate in the old one's place.
  4447. static bool replace_client_ca(SSLServer &svr) {
  4448. std::string cert_pem, key_pem, ca_pem;
  4449. read_file(SERVER_CERT_FILE, cert_pem);
  4450. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4451. read_file(SERVER_CERT2_FILE, ca_pem);
  4452. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4453. ca_pem.c_str());
  4454. }
  4455. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4456. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4457. ASSERT_TRUE(svr.is_valid());
  4458. svr.Get("/test", [](const Request &, Response &res) {
  4459. res.set_content("ok", "text/plain");
  4460. });
  4461. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4462. auto se = detail::scope_exit([&] {
  4463. svr.stop();
  4464. t.join();
  4465. ASSERT_FALSE(svr.is_running());
  4466. });
  4467. svr.wait_until_ready();
  4468. auto get = [] {
  4469. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4470. cli.enable_server_certificate_verification(false);
  4471. return cli.Get("/test");
  4472. };
  4473. ASSERT_TRUE(get());
  4474. ASSERT_TRUE(replace_client_ca(svr));
  4475. EXPECT_FALSE(get());
  4476. }
  4477. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4478. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4480. ASSERT_TRUE(svr.is_valid());
  4481. tls::set_verify_callback(svr.tls_context(),
  4482. [](const tls::VerifyContext &) -> bool {
  4483. throw std::runtime_error("verify");
  4484. });
  4485. svr.Get("/test", [](const Request &, Response &res) {
  4486. res.set_content("ok", "text/plain");
  4487. });
  4488. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4489. auto se = detail::scope_exit([&] {
  4490. svr.stop();
  4491. t.join();
  4492. ASSERT_FALSE(svr.is_running());
  4493. });
  4494. svr.wait_until_ready();
  4495. auto get = [] {
  4496. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4497. cli.enable_server_certificate_verification(false);
  4498. return cli.Get("/test");
  4499. };
  4500. EXPECT_FALSE(get());
  4501. // The handshake is over, so an update does not wait for it.
  4502. std::string cert_pem, key_pem;
  4503. read_file(SERVER_CERT_FILE, cert_pem);
  4504. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4505. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4506. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4507. return v.preverify_ok;
  4508. });
  4509. auto res = get();
  4510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4511. EXPECT_EQ("ok", res->body);
  4512. }
  4513. #endif
  4514. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4515. // Sends each request over a new connection with a client certificate,
  4516. // resuming the session of the one before when there is one.
  4517. class ResumingClient {
  4518. public:
  4519. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4520. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4521. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4522. SSL_FILETYPE_PEM);
  4523. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4524. // callback, not through SSL_get1_session().
  4525. SSL_CTX_set_app_data(ctx_, this);
  4526. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4527. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4528. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4529. auto self = static_cast<ResumingClient *>(
  4530. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4531. SSL_SESSION_free(self->session_);
  4532. self->session_ = session;
  4533. return 1; // Keeps the reference
  4534. });
  4535. }
  4536. ~ResumingClient() {
  4537. SSL_SESSION_free(session_);
  4538. SSL_CTX_free(ctx_);
  4539. }
  4540. // Tells whether the request was answered.
  4541. bool get() {
  4542. auto error = Error::Success;
  4543. auto sock = detail::create_client_socket(
  4544. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4545. /*connection_timeout_sec=*/5, 0,
  4546. /*read_timeout_sec=*/5, 0,
  4547. /*write_timeout_sec=*/5, 0, std::string(), error);
  4548. if (sock == INVALID_SOCKET) { return false; }
  4549. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4550. auto ssl = SSL_new(ctx_);
  4551. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4552. SSL_set_fd(ssl, static_cast<int>(sock));
  4553. if (session_) { SSL_set_session(ssl, session_); }
  4554. if (SSL_connect(ssl) != 1) { return false; }
  4555. reused_ = SSL_session_reused(ssl) == 1;
  4556. // Reading the response also takes in a TLS 1.3 session ticket.
  4557. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4558. "Connection: close\r\n\r\n";
  4559. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4560. std::string res;
  4561. char buf[256];
  4562. int n;
  4563. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4564. res.append(buf, static_cast<size_t>(n));
  4565. }
  4566. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4567. SSL_shutdown(ssl);
  4568. return res.find("200 OK") != std::string::npos;
  4569. }
  4570. // Whether the last connection resumed a session
  4571. bool reused() const { return reused_; }
  4572. private:
  4573. SSL_CTX *ctx_;
  4574. SSL_SESSION *session_ = nullptr;
  4575. bool reused_ = false;
  4576. };
  4577. // A client that resumes its session gets through, but not once the client CA
  4578. // has changed, as a resumed session does not show the certificate again.
  4579. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4581. ASSERT_TRUE(svr.is_valid());
  4582. svr.Get("/test", [](const Request &, Response &res) {
  4583. res.set_content("ok", "text/plain");
  4584. });
  4585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4586. auto se = detail::scope_exit([&] {
  4587. svr.stop();
  4588. t.join();
  4589. ASSERT_FALSE(svr.is_running());
  4590. });
  4591. svr.wait_until_ready();
  4592. ResumingClient cli;
  4593. ASSERT_TRUE(cli.get());
  4594. ASSERT_TRUE(cli.get());
  4595. EXPECT_TRUE(cli.reused());
  4596. ASSERT_TRUE(replace_client_ca(svr));
  4597. EXPECT_FALSE(cli.get());
  4598. }
  4599. // A resumed session does not show the certificate again, so the server does
  4600. // not resume one with a verify callback to run on it.
  4601. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4603. ASSERT_TRUE(svr.is_valid());
  4604. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4605. return v.preverify_ok;
  4606. });
  4607. svr.Get("/test", [](const Request &, Response &res) {
  4608. res.set_content("ok", "text/plain");
  4609. });
  4610. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4611. auto se = detail::scope_exit([&] {
  4612. svr.stop();
  4613. t.join();
  4614. ASSERT_FALSE(svr.is_running());
  4615. });
  4616. svr.wait_until_ready();
  4617. ResumingClient cli;
  4618. ASSERT_TRUE(cli.get());
  4619. ASSERT_TRUE(cli.get());
  4620. EXPECT_FALSE(cli.reused());
  4621. }
  4622. #endif
  4623. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4624. // wolfSSL shares its session cache between contexts, so a resumed session
  4625. // could carry a client certificate checked against another server's CA, or
  4626. // against a client CA since replaced.
  4627. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4629. ASSERT_TRUE(svr.is_valid());
  4630. // Trusts a CA that did not sign the client's certificate.
  4631. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4632. ASSERT_TRUE(other.is_valid());
  4633. for (auto s : {&svr, &other}) {
  4634. s->Get("/test", [](const Request &, Response &res) {
  4635. res.set_content("ok", "text/plain");
  4636. });
  4637. }
  4638. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4639. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4640. auto se = detail::scope_exit([&] {
  4641. other.stop();
  4642. svr.stop();
  4643. t2.join();
  4644. t.join();
  4645. });
  4646. svr.wait_until_ready();
  4647. other.wait_until_ready();
  4648. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4649. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4650. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4651. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4652. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4653. ASSERT_EQ(WOLFSSL_SUCCESS,
  4654. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4655. WOLFSSL_FILETYPE_PEM));
  4656. WOLFSSL_SESSION *session = nullptr;
  4657. auto session_se = detail::scope_exit([&] {
  4658. if (session) { wolfSSL_SESSION_free(session); }
  4659. });
  4660. // A request over a new connection, resuming `session` when there is one and
  4661. // keeping the connection's own in its place. Tells whether it was answered.
  4662. auto get = [&](int port) {
  4663. auto error = Error::Success;
  4664. auto sock = detail::create_client_socket(
  4665. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4666. /*connection_timeout_sec=*/5, 0,
  4667. /*read_timeout_sec=*/5, 0,
  4668. /*write_timeout_sec=*/5, 0, std::string(), error);
  4669. if (sock == INVALID_SOCKET) { return false; }
  4670. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4671. auto ssl = wolfSSL_new(ctx);
  4672. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4673. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4674. if (session) { wolfSSL_set_session(ssl, session); }
  4675. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4676. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4677. "Connection: close\r\n\r\n";
  4678. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4679. std::string res;
  4680. char buf[256];
  4681. int n;
  4682. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4683. res.append(buf, static_cast<size_t>(n));
  4684. }
  4685. wolfSSL_shutdown(ssl);
  4686. if (session) { wolfSSL_SESSION_free(session); }
  4687. session = wolfSSL_get1_session(ssl);
  4688. return res.find("200 OK") != std::string::npos;
  4689. };
  4690. ASSERT_TRUE(get(PORT));
  4691. EXPECT_FALSE(get(PORT + 1));
  4692. ASSERT_TRUE(get(PORT));
  4693. ASSERT_TRUE(replace_client_ca(svr));
  4694. EXPECT_FALSE(get(PORT));
  4695. }
  4696. #endif
  4697. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4698. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4699. ASSERT_TRUE(svr.is_valid());
  4700. svr.Get("/test", [](const Request &, Response &res) {
  4701. res.set_content("ok", "text/plain");
  4702. });
  4703. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4704. auto se = detail::scope_exit([&] {
  4705. svr.stop();
  4706. t.join();
  4707. ASSERT_FALSE(svr.is_running());
  4708. });
  4709. svr.wait_until_ready();
  4710. // A connection that sends no ClientHello keeps its handshake in progress,
  4711. // once the server has had a moment to start it.
  4712. auto error = Error::Success;
  4713. auto sock = detail::create_client_socket(
  4714. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4715. /*connection_timeout_sec=*/5, 0,
  4716. /*read_timeout_sec=*/5, 0,
  4717. /*write_timeout_sec=*/5, 0, std::string(), error);
  4718. ASSERT_NE(INVALID_SOCKET, sock);
  4719. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4720. std::string cert_pem, key_pem;
  4721. read_file(SERVER_CERT_FILE, cert_pem);
  4722. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4723. auto update = std::async(std::launch::async, [&]() {
  4724. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4725. });
  4726. EXPECT_EQ(std::future_status::timeout,
  4727. update.wait_for(std::chrono::milliseconds(200)));
  4728. detail::close_socket(sock);
  4729. EXPECT_TRUE(update.get());
  4730. SSLClient cli(HOST, PORT);
  4731. cli.enable_server_certificate_verification(false);
  4732. auto res = cli.Get("/test");
  4733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. }
  4736. #endif
  4737. TEST(ErrorHandlerTest, ContentLength) {
  4738. Server svr;
  4739. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4740. res.status = StatusCode::OK_200;
  4741. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4742. "text/html"); // <= Content-Length still 13
  4743. });
  4744. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4745. res.set_content("Hello World!\n", "text/plain");
  4746. res.status = 524;
  4747. });
  4748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4749. auto se = detail::scope_exit([&] {
  4750. svr.stop();
  4751. thread.join();
  4752. ASSERT_FALSE(svr.is_running());
  4753. });
  4754. svr.wait_until_ready();
  4755. {
  4756. Client cli(HOST, PORT);
  4757. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4759. EXPECT_EQ(StatusCode::OK_200, res->status);
  4760. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4761. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4762. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4763. }
  4764. }
  4765. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4766. TEST(ExceptionTest, WithoutExceptionHandler) {
  4767. Server svr;
  4768. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4769. throw std::runtime_error("exception...");
  4770. });
  4771. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4772. throw std::runtime_error("exception\r\n...");
  4773. });
  4774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4775. auto se = detail::scope_exit([&] {
  4776. svr.stop();
  4777. listen_thread.join();
  4778. ASSERT_FALSE(svr.is_running());
  4779. });
  4780. svr.wait_until_ready();
  4781. Client cli("localhost", PORT);
  4782. {
  4783. auto res = cli.Get("/exception");
  4784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4785. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4786. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4787. }
  4788. {
  4789. auto res = cli.Get("/unknown");
  4790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4791. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4792. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4793. }
  4794. }
  4795. TEST(ExceptionTest, WithExceptionHandler) {
  4796. Server svr;
  4797. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4798. std::exception_ptr ep) {
  4799. EXPECT_FALSE(ep == nullptr);
  4800. try {
  4801. std::rethrow_exception(ep);
  4802. } catch (std::exception &e) {
  4803. EXPECT_EQ("abc", std::string(e.what()));
  4804. } catch (...) {}
  4805. res.status = StatusCode::InternalServerError_500;
  4806. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4807. "text/html"); // <= Content-Length still 13 at this point
  4808. });
  4809. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4810. res.set_content("Hello World!\n", "text/plain");
  4811. throw std::runtime_error("abc");
  4812. });
  4813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4814. auto se = detail::scope_exit([&] {
  4815. svr.stop();
  4816. thread.join();
  4817. ASSERT_FALSE(svr.is_running());
  4818. });
  4819. svr.wait_until_ready();
  4820. for (size_t i = 0; i < 10; i++) {
  4821. Client cli(HOST, PORT);
  4822. for (size_t j = 0; j < 100; j++) {
  4823. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4826. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4827. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4828. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4829. }
  4830. cli.set_keep_alive(true);
  4831. for (size_t j = 0; j < 100; j++) {
  4832. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4834. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4835. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4836. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4837. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4838. }
  4839. }
  4840. }
  4841. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4842. Server svr;
  4843. svr.set_exception_handler(
  4844. [](const Request &, Response &res, std::exception_ptr) {
  4845. res.set_content("oops", "text/plain");
  4846. });
  4847. svr.Get("/throw", [](const Request &, Response &) {
  4848. throw std::runtime_error("throw");
  4849. });
  4850. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4851. res.status = StatusCode::Created_201;
  4852. throw std::runtime_error("created-then-throw");
  4853. });
  4854. auto port = svr.bind_to_any_port(HOST);
  4855. ASSERT_GT(port, 0);
  4856. thread t = thread([&] { svr.listen_after_bind(); });
  4857. auto se = detail::scope_exit([&] {
  4858. svr.stop();
  4859. t.join();
  4860. ASSERT_FALSE(svr.is_running());
  4861. });
  4862. svr.wait_until_ready();
  4863. Client cli(HOST, port);
  4864. for (auto path : {"/throw", "/created-then-throw"}) {
  4865. auto res = cli.Get(path);
  4866. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4867. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4868. }
  4869. }
  4870. TEST(ExceptionTest, AndErrorHandler) {
  4871. Server svr;
  4872. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4873. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4874. });
  4875. svr.set_exception_handler(
  4876. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4877. EXPECT_FALSE(ep == nullptr);
  4878. try {
  4879. std::rethrow_exception(ep);
  4880. } catch (std::exception &e) {
  4881. res.set_content(e.what(), "text/html");
  4882. } catch (...) {}
  4883. res.status = StatusCode::InternalServerError_500;
  4884. });
  4885. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4886. throw std::runtime_error("EXCEPTION");
  4887. });
  4888. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4889. res.set_content("ERROR", "text/html");
  4890. res.status = StatusCode::InternalServerError_500;
  4891. });
  4892. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4893. auto se = detail::scope_exit([&] {
  4894. svr.stop();
  4895. thread.join();
  4896. ASSERT_FALSE(svr.is_running());
  4897. });
  4898. svr.wait_until_ready();
  4899. Client cli(HOST, PORT);
  4900. {
  4901. auto res = cli.Get("/exception");
  4902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4903. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4904. EXPECT_EQ("EXCEPTION", res->body);
  4905. }
  4906. {
  4907. auto res = cli.Get("/error");
  4908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4909. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4910. EXPECT_EQ("ERROR", res->body);
  4911. }
  4912. {
  4913. auto res = cli.Get("/invalid");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4916. EXPECT_EQ("NOT_FOUND", res->body);
  4917. }
  4918. }
  4919. #endif
  4920. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4921. // An exception from a user callback outside process_request()'s try/catch
  4922. // used to unwind into the task queue - which does not catch - and terminate
  4923. // the process. Each test below runs the server on a single worker thread: a
  4924. // guard that catches the exception but still loses the thread would otherwise
  4925. // be hidden by a spare worker serving the follow-up request. Note that a
  4926. // regression here aborts the whole test binary rather than failing one test.
  4927. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4928. Server svr;
  4929. svr.new_task_queue = [] { return new ThreadPool(1); };
  4930. std::atomic<int> reported{0};
  4931. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4932. if (err == Error::UserCallbackException) { reported++; }
  4933. });
  4934. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4935. res.set_content_provider(
  4936. 1024, "text/plain",
  4937. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4938. sink.write("hello", 5);
  4939. throw std::runtime_error("from the content provider");
  4940. });
  4941. });
  4942. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4943. res.set_content("ok", "text/plain");
  4944. });
  4945. auto port = svr.bind_to_any_port(HOST);
  4946. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4947. auto se = detail::scope_exit([&] {
  4948. svr.stop();
  4949. listen_thread.join();
  4950. ASSERT_FALSE(svr.is_running());
  4951. });
  4952. svr.wait_until_ready();
  4953. {
  4954. Client cli(HOST, port);
  4955. cli.set_read_timeout(5, 0);
  4956. EXPECT_FALSE(cli.Get("/throw"));
  4957. }
  4958. EXPECT_TRUE(svr.is_running());
  4959. EXPECT_EQ(1, reported.load());
  4960. // A request on a fresh connection is still served.
  4961. {
  4962. Client cli(HOST, port);
  4963. auto res = cli.Get("/ok");
  4964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4965. EXPECT_EQ(StatusCode::OK_200, res->status);
  4966. EXPECT_EQ("ok", res->body);
  4967. }
  4968. }
  4969. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4970. Server svr;
  4971. svr.new_task_queue = [] { return new ThreadPool(1); };
  4972. std::atomic<bool> should_throw{true};
  4973. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4974. res.set_content("hi", "text/plain");
  4975. });
  4976. svr.set_post_routing_handler(
  4977. [&](const Request & /*req*/, Response & /*res*/) {
  4978. if (should_throw) {
  4979. throw std::runtime_error("from the post-routing handler");
  4980. }
  4981. });
  4982. auto port = svr.bind_to_any_port(HOST);
  4983. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4984. auto se = detail::scope_exit([&] {
  4985. svr.stop();
  4986. listen_thread.join();
  4987. ASSERT_FALSE(svr.is_running());
  4988. });
  4989. svr.wait_until_ready();
  4990. {
  4991. Client cli(HOST, port);
  4992. cli.set_read_timeout(5, 0);
  4993. EXPECT_FALSE(cli.Get("/hi"));
  4994. }
  4995. EXPECT_TRUE(svr.is_running());
  4996. should_throw = false;
  4997. {
  4998. Client cli(HOST, port);
  4999. auto res = cli.Get("/hi");
  5000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5001. EXPECT_EQ(StatusCode::OK_200, res->status);
  5002. EXPECT_EQ("hi", res->body);
  5003. }
  5004. }
  5005. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5006. // The guard reports the caught exception through the error logger, which is
  5007. // a user callback too. A logger that throws has to be contained as well, or
  5008. // the process would terminate from inside the catch.
  5009. Server svr;
  5010. svr.new_task_queue = [] { return new ThreadPool(1); };
  5011. std::atomic<int> reported{0};
  5012. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5013. if (err == Error::UserCallbackException) {
  5014. reported++;
  5015. throw std::runtime_error("from the error logger");
  5016. }
  5017. });
  5018. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5019. res.set_content_provider(
  5020. 1024, "text/plain",
  5021. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5022. sink.write("hello", 5);
  5023. throw std::runtime_error("from the content provider");
  5024. });
  5025. });
  5026. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5027. res.set_content("ok", "text/plain");
  5028. });
  5029. auto port = svr.bind_to_any_port(HOST);
  5030. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5031. auto se = detail::scope_exit([&] {
  5032. svr.stop();
  5033. listen_thread.join();
  5034. ASSERT_FALSE(svr.is_running());
  5035. });
  5036. svr.wait_until_ready();
  5037. {
  5038. Client cli(HOST, port);
  5039. cli.set_read_timeout(5, 0);
  5040. EXPECT_FALSE(cli.Get("/throw"));
  5041. }
  5042. EXPECT_TRUE(svr.is_running());
  5043. EXPECT_EQ(1, reported.load());
  5044. {
  5045. Client cli(HOST, port);
  5046. auto res = cli.Get("/ok");
  5047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5048. EXPECT_EQ(StatusCode::OK_200, res->status);
  5049. EXPECT_EQ("ok", res->body);
  5050. }
  5051. }
  5052. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5053. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5054. // so the exception unwinds through the ws::WebSocket object on its way to
  5055. // the guard. None of the HTTP cases above cross that.
  5056. Server svr;
  5057. svr.new_task_queue = [] { return new ThreadPool(1); };
  5058. std::atomic<int> reported{0};
  5059. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5060. if (err == Error::UserCallbackException) { reported++; }
  5061. });
  5062. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5063. throw std::runtime_error("from the WebSocket handler");
  5064. });
  5065. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5066. res.set_content("ok", "text/plain");
  5067. });
  5068. auto port = svr.bind_to_any_port(HOST);
  5069. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5070. auto se = detail::scope_exit([&] {
  5071. svr.stop();
  5072. listen_thread.join();
  5073. ASSERT_FALSE(svr.is_running());
  5074. });
  5075. svr.wait_until_ready();
  5076. {
  5077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5078. "/ws");
  5079. auto res = client.connect();
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. // The server dropped the connection instead of dying.
  5082. std::string msg;
  5083. EXPECT_FALSE(client.read(msg));
  5084. client.close();
  5085. }
  5086. EXPECT_TRUE(svr.is_running());
  5087. EXPECT_EQ(1, reported.load());
  5088. {
  5089. Client cli(HOST, port);
  5090. auto res = cli.Get("/ok");
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. EXPECT_EQ(StatusCode::OK_200, res->status);
  5093. EXPECT_EQ("ok", res->body);
  5094. }
  5095. }
  5096. #ifdef CPPHTTPLIB_SSL_ENABLED
  5097. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5098. // SSLServer::process_and_close_socket() is a separate overload with its own
  5099. // guard, so it is exercised on its own.
  5100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5101. ASSERT_TRUE(svr.is_valid());
  5102. svr.new_task_queue = [] { return new ThreadPool(1); };
  5103. std::atomic<int> reported{0};
  5104. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5105. if (err == Error::UserCallbackException) { reported++; }
  5106. });
  5107. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5108. res.set_content_provider(
  5109. 1024, "text/plain",
  5110. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5111. sink.write("hello", 5);
  5112. throw std::runtime_error("from the content provider");
  5113. });
  5114. });
  5115. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5116. res.set_content("ok", "text/plain");
  5117. });
  5118. auto port = svr.bind_to_any_port(HOST);
  5119. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5120. auto se = detail::scope_exit([&] {
  5121. svr.stop();
  5122. listen_thread.join();
  5123. ASSERT_FALSE(svr.is_running());
  5124. });
  5125. svr.wait_until_ready();
  5126. {
  5127. SSLClient cli(HOST, port);
  5128. cli.enable_server_certificate_verification(false);
  5129. cli.set_read_timeout(5, 0);
  5130. EXPECT_FALSE(cli.Get("/throw"));
  5131. }
  5132. EXPECT_TRUE(svr.is_running());
  5133. EXPECT_EQ(1, reported.load());
  5134. {
  5135. SSLClient cli(HOST, port);
  5136. cli.enable_server_certificate_verification(false);
  5137. auto res = cli.Get("/ok");
  5138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5139. EXPECT_EQ(StatusCode::OK_200, res->status);
  5140. EXPECT_EQ("ok", res->body);
  5141. }
  5142. }
  5143. #endif
  5144. #endif
  5145. TEST(NoContentTest, ContentLength) {
  5146. Server svr;
  5147. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5148. res.status = StatusCode::NoContent_204;
  5149. });
  5150. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5151. auto se = detail::scope_exit([&] {
  5152. svr.stop();
  5153. thread.join();
  5154. ASSERT_FALSE(svr.is_running());
  5155. });
  5156. svr.wait_until_ready();
  5157. {
  5158. Client cli(HOST, PORT);
  5159. auto res = cli.Get("/hi");
  5160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5161. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5162. // RFC 9110 8.6: none in a 204 response
  5163. EXPECT_FALSE(res->has_header("Content-Length"));
  5164. }
  5165. }
  5166. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5167. Server svr;
  5168. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5169. res.set_header("Content-Length", "5");
  5170. res.set_content("hello world", "text/plain");
  5171. });
  5172. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5173. // A body that reads as the last chunk, were it taken as chunked
  5174. res.set_header("Transfer-Encoding", "chunked");
  5175. res.set_content("0\r\n\r\n", "text/plain");
  5176. });
  5177. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5178. res.set_header("Content-Length", "2");
  5179. res.set_content_provider(5, "text/plain",
  5180. [](size_t offset, size_t length, DataSink &sink) {
  5181. sink.write(&"hello"[offset], length);
  5182. return true;
  5183. });
  5184. });
  5185. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5186. res.set_header("Content-Length", "1234");
  5187. });
  5188. thread t = thread([&] { svr.listen(HOST, PORT); });
  5189. auto se = detail::scope_exit([&] {
  5190. svr.stop();
  5191. t.join();
  5192. ASSERT_FALSE(svr.is_running());
  5193. });
  5194. svr.wait_until_ready();
  5195. Client cli(HOST, PORT);
  5196. cli.set_read_timeout(1, 0);
  5197. auto expect_body = [&](const Result &res, const std::string &body) {
  5198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5199. EXPECT_EQ(body, res->body);
  5200. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5201. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5202. };
  5203. Headers identity{{"Accept-Encoding", ""}};
  5204. expect_body(cli.Get("/body", identity), "hello world");
  5205. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5206. expect_body(cli.Get("/body",
  5207. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5208. "he");
  5209. expect_body(cli.Get("/provider", identity), "hello");
  5210. expect_body(cli.Get("/empty", identity), "");
  5211. // A HEAD response may give the length of the body a GET would get.
  5212. auto res = cli.Head("/empty");
  5213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5214. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5215. }
  5216. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5217. Server svr;
  5218. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5219. res.set_content("short", "text/plain");
  5220. });
  5221. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5222. res.body += " with a footer";
  5223. res.set_header("Transfer-Encoding", "chunked");
  5224. });
  5225. thread t = thread([&] { svr.listen(HOST, PORT); });
  5226. auto se = detail::scope_exit([&] {
  5227. svr.stop();
  5228. t.join();
  5229. ASSERT_FALSE(svr.is_running());
  5230. });
  5231. svr.wait_until_ready();
  5232. Client cli(HOST, PORT);
  5233. cli.set_read_timeout(1, 0);
  5234. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5236. EXPECT_EQ("short with a footer", res->body);
  5237. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5238. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5239. }
  5240. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5241. Server svr;
  5242. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5243. res.set_header("Content-Length", "3");
  5244. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5245. sink.write("abc", 3);
  5246. sink.done();
  5247. return true;
  5248. });
  5249. });
  5250. thread t = thread([&] { svr.listen(HOST, PORT); });
  5251. auto se = detail::scope_exit([&] {
  5252. svr.stop();
  5253. t.join();
  5254. ASSERT_FALSE(svr.is_running());
  5255. });
  5256. svr.wait_until_ready();
  5257. Client cli(HOST, PORT);
  5258. cli.set_keep_alive(true);
  5259. auto res = cli.Get("/");
  5260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5261. EXPECT_EQ("abc", res->body);
  5262. EXPECT_FALSE(res->has_header("Content-Length"));
  5263. EXPECT_EQ("close", res->get_header_value("Connection"));
  5264. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5265. // No body to delimit
  5266. auto head = cli.Head("/");
  5267. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5268. EXPECT_FALSE(head->has_header("Connection"));
  5269. }
  5270. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5271. #ifdef CPPHTTPLIB_SSL_ENABLED
  5272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5273. ASSERT_TRUE(svr.is_valid());
  5274. #else
  5275. Server svr;
  5276. #endif
  5277. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5278. if (req.path == "/routing_handler") {
  5279. res.set_header("PRE_ROUTING", "on");
  5280. res.set_content("Routing Handler", "text/plain");
  5281. return httplib::Server::HandlerResponse::Handled;
  5282. }
  5283. return httplib::Server::HandlerResponse::Unhandled;
  5284. });
  5285. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5286. res.set_content("Error", "text/html");
  5287. });
  5288. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5289. if (req.path == "/routing_handler") {
  5290. res.set_header("POST_ROUTING", "on");
  5291. }
  5292. });
  5293. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5294. res.set_content("Hello World!\n", "text/plain");
  5295. });
  5296. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5297. auto se = detail::scope_exit([&] {
  5298. svr.stop();
  5299. thread.join();
  5300. ASSERT_FALSE(svr.is_running());
  5301. });
  5302. svr.wait_until_ready();
  5303. {
  5304. #ifdef CPPHTTPLIB_SSL_ENABLED
  5305. SSLClient cli(HOST, PORT);
  5306. cli.enable_server_certificate_verification(false);
  5307. #else
  5308. Client cli(HOST, PORT);
  5309. #endif
  5310. auto res = cli.Get("/routing_handler");
  5311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. EXPECT_EQ("Routing Handler", res->body);
  5314. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5315. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5316. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5317. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5318. }
  5319. {
  5320. #ifdef CPPHTTPLIB_SSL_ENABLED
  5321. SSLClient cli(HOST, PORT);
  5322. cli.enable_server_certificate_verification(false);
  5323. #else
  5324. Client cli(HOST, PORT);
  5325. #endif
  5326. auto res = cli.Get("/hi");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. EXPECT_EQ(StatusCode::OK_200, res->status);
  5329. EXPECT_EQ("Hello World!\n", res->body);
  5330. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5331. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5332. }
  5333. {
  5334. #ifdef CPPHTTPLIB_SSL_ENABLED
  5335. SSLClient cli(HOST, PORT);
  5336. cli.enable_server_certificate_verification(false);
  5337. #else
  5338. Client cli(HOST, PORT);
  5339. #endif
  5340. auto res = cli.Get("/aaa");
  5341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5342. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5343. EXPECT_EQ("Error", res->body);
  5344. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5345. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5346. }
  5347. }
  5348. TEST(RequestHandlerTest, PreRequestHandler) {
  5349. auto route_path = "/user/:user";
  5350. Server svr;
  5351. svr.Get("/hi", [](const Request &, Response &res) {
  5352. res.set_content("hi", "text/plain");
  5353. });
  5354. svr.Get(route_path, [](const Request &req, Response &res) {
  5355. res.set_content(req.path_params.at("user"), "text/plain");
  5356. });
  5357. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5358. if (req.matched_route == route_path) {
  5359. auto user = req.path_params.at("user");
  5360. if (user != "john") {
  5361. res.status = StatusCode::Forbidden_403;
  5362. res.set_content("error", "text/html");
  5363. return Server::HandlerResponse::Handled;
  5364. }
  5365. }
  5366. return Server::HandlerResponse::Unhandled;
  5367. });
  5368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5369. auto se = detail::scope_exit([&] {
  5370. svr.stop();
  5371. thread.join();
  5372. ASSERT_FALSE(svr.is_running());
  5373. });
  5374. svr.wait_until_ready();
  5375. Client cli(HOST, PORT);
  5376. {
  5377. auto res = cli.Get("/hi");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. EXPECT_EQ(StatusCode::OK_200, res->status);
  5380. EXPECT_EQ("hi", res->body);
  5381. }
  5382. {
  5383. auto res = cli.Get("/user/john");
  5384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5385. EXPECT_EQ(StatusCode::OK_200, res->status);
  5386. EXPECT_EQ("john", res->body);
  5387. }
  5388. {
  5389. auto res = cli.Get("/user/invalid-user");
  5390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5391. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5392. EXPECT_EQ("error", res->body);
  5393. }
  5394. }
  5395. // The pre-request handler must run before the request body is read, so a
  5396. // rejected request never forces the server to buffer a (potentially large)
  5397. // body. Here the posted body is larger than the payload limit: if the body
  5398. // were read first the server would answer 413, but because the pre-request
  5399. // handler runs first it answers 403 and the body is never read.
  5400. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5401. Server svr;
  5402. svr.set_payload_max_length(8);
  5403. auto handler_ran = false;
  5404. svr.Post("/reject", [&](const Request &req, Response &res) {
  5405. handler_ran = true;
  5406. res.set_content(req.body, "text/plain");
  5407. });
  5408. svr.Post("/accept", [](const Request &req, Response &res) {
  5409. res.set_content(req.body, "text/plain");
  5410. });
  5411. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5412. if (req.matched_route == "/reject") {
  5413. res.status = StatusCode::Forbidden_403;
  5414. res.set_content("denied", "text/plain");
  5415. return Server::HandlerResponse::Handled;
  5416. }
  5417. return Server::HandlerResponse::Unhandled;
  5418. });
  5419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5420. auto se = detail::scope_exit([&] {
  5421. svr.stop();
  5422. thread.join();
  5423. ASSERT_FALSE(svr.is_running());
  5424. });
  5425. svr.wait_until_ready();
  5426. Client cli(HOST, PORT);
  5427. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5428. // rejects with 403 before the body is read, so 413 is never reached.
  5429. {
  5430. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5433. EXPECT_EQ("denied", res->body);
  5434. EXPECT_FALSE(handler_ran);
  5435. }
  5436. // An approved route still reads the body and enforces the payload limit.
  5437. {
  5438. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5441. }
  5442. }
  5443. TEST(UserDataTest, BasicOperations) {
  5444. httplib::UserData ud;
  5445. // Initially empty
  5446. EXPECT_FALSE(ud.has("key"));
  5447. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5448. // set and get
  5449. ud.set("key", 42);
  5450. EXPECT_TRUE(ud.has("key"));
  5451. auto *p = ud.get<int>("key");
  5452. ASSERT_NE(nullptr, p);
  5453. EXPECT_EQ(42, *p);
  5454. // Type mismatch → nullptr
  5455. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5456. // Overwrite with different type
  5457. ud.set("key", std::string("hello"));
  5458. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5459. auto *s = ud.get<std::string>("key");
  5460. ASSERT_NE(nullptr, s);
  5461. EXPECT_EQ("hello", *s);
  5462. // erase
  5463. ud.erase("key");
  5464. EXPECT_FALSE(ud.has("key"));
  5465. // clear
  5466. ud.set("a", 1);
  5467. ud.set("b", 2);
  5468. ud.clear();
  5469. EXPECT_FALSE(ud.has("a"));
  5470. EXPECT_FALSE(ud.has("b"));
  5471. }
  5472. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5473. struct AuthCtx {
  5474. std::string user_id;
  5475. };
  5476. Server svr;
  5477. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5478. res.user_data.set("auth", AuthCtx{"alice"});
  5479. return Server::HandlerResponse::Unhandled;
  5480. });
  5481. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5482. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5483. ASSERT_NE(nullptr, ctx);
  5484. res.set_content("Hello " + ctx->user_id, "text/plain");
  5485. });
  5486. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5487. auto se = detail::scope_exit([&] {
  5488. svr.stop();
  5489. thread.join();
  5490. ASSERT_FALSE(svr.is_running());
  5491. });
  5492. svr.wait_until_ready();
  5493. Client cli(HOST, PORT);
  5494. auto res = cli.Get("/me");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. EXPECT_EQ("Hello alice", res->body);
  5498. }
  5499. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5500. struct RoleCtx {
  5501. std::string role;
  5502. };
  5503. Server svr;
  5504. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5505. res.user_data.set("role", RoleCtx{"admin"});
  5506. return Server::HandlerResponse::Unhandled;
  5507. });
  5508. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5509. auto *ctx = res.user_data.get<RoleCtx>("role");
  5510. ASSERT_NE(nullptr, ctx);
  5511. res.set_content(ctx->role, "text/plain");
  5512. });
  5513. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5514. auto se = detail::scope_exit([&] {
  5515. svr.stop();
  5516. thread.join();
  5517. ASSERT_FALSE(svr.is_running());
  5518. });
  5519. svr.wait_until_ready();
  5520. Client cli(HOST, PORT);
  5521. auto res = cli.Get("/role");
  5522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. EXPECT_EQ("admin", res->body);
  5525. }
  5526. TEST(InvalidFormatTest, StatusCode) {
  5527. Server svr;
  5528. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5529. res.set_content("Hello World!\n", "text/plain");
  5530. res.status = 9999; // Status should be a three-digit code...
  5531. });
  5532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5533. auto se = detail::scope_exit([&] {
  5534. svr.stop();
  5535. thread.join();
  5536. ASSERT_FALSE(svr.is_running());
  5537. });
  5538. svr.wait_until_ready();
  5539. {
  5540. Client cli(HOST, PORT);
  5541. auto res = cli.Get("/hi");
  5542. ASSERT_FALSE(res);
  5543. }
  5544. }
  5545. TEST(URLFragmentTest, WithFragment) {
  5546. Server svr;
  5547. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5548. EXPECT_TRUE(req.target == "/hi");
  5549. });
  5550. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5551. auto se = detail::scope_exit([&] {
  5552. svr.stop();
  5553. thread.join();
  5554. ASSERT_FALSE(svr.is_running());
  5555. });
  5556. svr.wait_until_ready();
  5557. {
  5558. Client cli(HOST, PORT);
  5559. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5560. EXPECT_TRUE(res);
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. res = cli.Get("/hi%23key1=val1=key2=val2");
  5563. EXPECT_TRUE(res);
  5564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5565. }
  5566. }
  5567. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5568. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5569. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5570. Server svr;
  5571. std::vector<std::string> targets;
  5572. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5573. targets.push_back(req.target);
  5574. });
  5575. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5576. auto se = detail::scope_exit([&] {
  5577. svr.stop();
  5578. thread.join();
  5579. ASSERT_FALSE(svr.is_running());
  5580. });
  5581. svr.wait_until_ready();
  5582. Client cli(HOST, PORT);
  5583. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5584. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5585. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5586. // A '?' after the '#' belongs to the fragment, not to the query.
  5587. Request req;
  5588. req.method = "GET";
  5589. req.path = "/hi#f?x=1";
  5590. req.params.emplace("a", "1");
  5591. Response res;
  5592. auto error = Error::Success;
  5593. EXPECT_TRUE(cli.send(req, res, error));
  5594. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5595. "/hi?a=1"}),
  5596. targets);
  5597. }
  5598. TEST(HeaderWriter, SetHeaderWriter) {
  5599. Server svr;
  5600. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5601. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5602. return detail::write_headers(strm, hdrs);
  5603. });
  5604. svr.Get("/hi", [](const Request &req, Response &res) {
  5605. auto it = req.headers.find("CustomClientHeader");
  5606. EXPECT_TRUE(it != req.headers.end());
  5607. EXPECT_EQ(it->second, "CustomClientValue");
  5608. res.set_content("Hello World!\n", "text/plain");
  5609. });
  5610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5611. auto se = detail::scope_exit([&] {
  5612. svr.stop();
  5613. thread.join();
  5614. ASSERT_FALSE(svr.is_running());
  5615. });
  5616. svr.wait_until_ready();
  5617. {
  5618. Client cli(HOST, PORT);
  5619. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5620. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5621. return detail::write_headers(strm, hdrs);
  5622. });
  5623. auto res = cli.Get("/hi");
  5624. EXPECT_TRUE(res);
  5625. EXPECT_EQ(StatusCode::OK_200, res->status);
  5626. auto it = res->headers.find("CustomServerHeader");
  5627. EXPECT_TRUE(it != res->headers.end());
  5628. EXPECT_EQ(it->second, "CustomServerValue");
  5629. }
  5630. }
  5631. class ServerTest : public ::testing::Test {
  5632. protected:
  5633. ServerTest()
  5634. : cli_(HOST, PORT)
  5635. #ifdef CPPHTTPLIB_SSL_ENABLED
  5636. ,
  5637. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5638. #endif
  5639. {
  5640. #ifdef CPPHTTPLIB_SSL_ENABLED
  5641. cli_.enable_server_certificate_verification(false);
  5642. #endif
  5643. // Allow LARGE_DATA (100MB) responses
  5644. cli_.set_payload_max_length(200 * 1024 * 1024);
  5645. }
  5646. virtual void SetUp() {
  5647. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5648. svr_.set_payload_max_length(200 * 1024 * 1024);
  5649. svr_.set_mount_point("/", "./www");
  5650. svr_.set_mount_point("/mount", "./www2");
  5651. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5652. svr_.Get("/hi",
  5653. [&](const Request & /*req*/, Response &res) {
  5654. res.set_content("Hello World!", "text/plain");
  5655. })
  5656. .Get("/file_content",
  5657. [&](const Request & /*req*/, Response &res) {
  5658. res.set_file_content("./www/dir/test.html");
  5659. })
  5660. .Get("/file_content_with_content_type",
  5661. [&](const Request & /*req*/, Response &res) {
  5662. res.set_file_content("./www/file", "text/plain");
  5663. })
  5664. .Get("/invalid_file_content",
  5665. [&](const Request & /*req*/, Response &res) {
  5666. res.set_file_content("./www/dir/invalid_file_path");
  5667. })
  5668. .Get("/http_response_splitting",
  5669. [&](const Request & /*req*/, Response &res) {
  5670. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5671. EXPECT_EQ(0U, res.headers.size());
  5672. EXPECT_FALSE(res.has_header("a"));
  5673. res.set_header("a", "1\nSet-Cookie: a=1");
  5674. EXPECT_EQ(0U, res.headers.size());
  5675. EXPECT_FALSE(res.has_header("a"));
  5676. res.set_header("a", "1\rSet-Cookie: a=1");
  5677. EXPECT_EQ(0U, res.headers.size());
  5678. EXPECT_FALSE(res.has_header("a"));
  5679. res.set_header("a\r\nb", "0");
  5680. EXPECT_EQ(0U, res.headers.size());
  5681. EXPECT_FALSE(res.has_header("a"));
  5682. res.set_header("a\rb", "0");
  5683. EXPECT_EQ(0U, res.headers.size());
  5684. EXPECT_FALSE(res.has_header("a"));
  5685. res.set_header("a\nb", "0");
  5686. EXPECT_EQ(0U, res.headers.size());
  5687. EXPECT_FALSE(res.has_header("a"));
  5688. res.set_redirect("1\r\nSet-Cookie: a=1");
  5689. EXPECT_EQ(0U, res.headers.size());
  5690. EXPECT_FALSE(res.has_header("Location"));
  5691. })
  5692. .Get("/slow",
  5693. [&](const Request & /*req*/, Response &res) {
  5694. std::this_thread::sleep_for(std::chrono::seconds(4));
  5695. res.set_content("slow", "text/plain");
  5696. })
  5697. #if 0
  5698. .Post("/slowpost",
  5699. [&](const Request & /*req*/, Response &res) {
  5700. std::this_thread::sleep_for(std::chrono::seconds(2));
  5701. res.set_content("slow", "text/plain");
  5702. })
  5703. #endif
  5704. .Get("/remote_addr",
  5705. [&](const Request &req, Response &res) {
  5706. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5707. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5708. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5709. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5710. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5711. #endif
  5712. res.set_content(req.remote_addr, "text/plain");
  5713. })
  5714. .Get("/local_addr",
  5715. [&](const Request &req, Response &res) {
  5716. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5717. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5718. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5719. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5720. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5721. #endif
  5722. auto local_addr = req.local_addr;
  5723. auto local_port = std::to_string(req.local_port);
  5724. res.set_content(local_addr.append(":").append(local_port),
  5725. "text/plain");
  5726. })
  5727. .Get("/endwith%",
  5728. [&](const Request & /*req*/, Response &res) {
  5729. res.set_content("Hello World!", "text/plain");
  5730. })
  5731. .Get("/a\\+\\+b",
  5732. [&](const Request &req, Response &res) {
  5733. ASSERT_TRUE(req.has_param("a +b"));
  5734. auto val = req.get_param_value("a +b");
  5735. res.set_content(val, "text/plain");
  5736. })
  5737. .Get("/", [&](const Request & /*req*/,
  5738. Response &res) { res.set_redirect("/hi"); })
  5739. .Post("/1",
  5740. [](const Request & /*req*/, Response &res) {
  5741. res.set_redirect("/2", StatusCode::SeeOther_303);
  5742. })
  5743. .Get("/2",
  5744. [](const Request & /*req*/, Response &res) {
  5745. res.set_content("redirected.", "text/plain");
  5746. res.status = StatusCode::OK_200;
  5747. })
  5748. .Post("/person",
  5749. [&](const Request &req, Response &res) {
  5750. if (req.has_param("name") && req.has_param("note")) {
  5751. persons_[req.get_param_value("name")] =
  5752. req.get_param_value("note");
  5753. } else {
  5754. res.status = StatusCode::BadRequest_400;
  5755. }
  5756. })
  5757. .Put("/person",
  5758. [&](const Request &req, Response &res) {
  5759. if (req.has_param("name") && req.has_param("note")) {
  5760. persons_[req.get_param_value("name")] =
  5761. req.get_param_value("note");
  5762. } else {
  5763. res.status = StatusCode::BadRequest_400;
  5764. }
  5765. })
  5766. .Get("/person/(.*)",
  5767. [&](const Request &req, Response &res) {
  5768. string name = req.matches[1];
  5769. if (persons_.find(name) != persons_.end()) {
  5770. auto note = persons_[name];
  5771. res.set_content(note, "text/plain");
  5772. } else {
  5773. res.status = StatusCode::NotFound_404;
  5774. }
  5775. })
  5776. .Delete("/person",
  5777. [&](const Request &req, Response &res) {
  5778. if (req.has_param("name")) {
  5779. string name = req.get_param_value("name");
  5780. if (persons_.find(name) != persons_.end()) {
  5781. persons_.erase(name);
  5782. res.set_content("DELETED", "text/plain");
  5783. } else {
  5784. res.status = StatusCode::NotFound_404;
  5785. }
  5786. } else {
  5787. res.status = StatusCode::BadRequest_400;
  5788. }
  5789. })
  5790. .Post("/x-www-form-urlencoded-json",
  5791. [&](const Request &req, Response &res) {
  5792. auto json = req.get_param_value("json");
  5793. ASSERT_EQ(JSON_DATA, json);
  5794. res.set_content(json, "appliation/json");
  5795. res.status = StatusCode::OK_200;
  5796. })
  5797. .Get("/streamed-chunked",
  5798. [&](const Request & /*req*/, Response &res) {
  5799. res.set_chunked_content_provider(
  5800. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5801. sink.os << "123";
  5802. sink.os << "456";
  5803. sink.os << "789";
  5804. sink.done();
  5805. return true;
  5806. });
  5807. })
  5808. .Get("/streamed-chunked-with-prohibited-trailer",
  5809. [&](const Request & /*req*/, Response &res) {
  5810. auto i = new int(0);
  5811. // Declare both a prohibited trailer (Content-Length) and an
  5812. // allowed one
  5813. res.set_header("Trailer", "Content-Length, X-Allowed");
  5814. res.set_chunked_content_provider(
  5815. "text/plain",
  5816. [i](size_t /*offset*/, DataSink &sink) {
  5817. switch (*i) {
  5818. case 0: sink.os << "123"; break;
  5819. case 1: sink.os << "456"; break;
  5820. case 2: sink.os << "789"; break;
  5821. case 3: {
  5822. sink.done_with_trailer(
  5823. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5824. } break;
  5825. }
  5826. (*i)++;
  5827. return true;
  5828. },
  5829. [i](bool success) {
  5830. EXPECT_TRUE(success);
  5831. delete i;
  5832. });
  5833. })
  5834. .Get("/streamed-chunked2",
  5835. [&](const Request & /*req*/, Response &res) {
  5836. auto i = new int(0);
  5837. res.set_chunked_content_provider(
  5838. "text/plain",
  5839. [i](size_t /*offset*/, DataSink &sink) {
  5840. switch (*i) {
  5841. case 0: sink.os << "123"; break;
  5842. case 1: sink.os << "456"; break;
  5843. case 2: sink.os << "789"; break;
  5844. case 3: sink.done(); break;
  5845. }
  5846. (*i)++;
  5847. return true;
  5848. },
  5849. [i](bool success) {
  5850. EXPECT_TRUE(success);
  5851. delete i;
  5852. });
  5853. })
  5854. .Get("/streamed-chunked-with-trailer",
  5855. [&](const Request & /*req*/, Response &res) {
  5856. auto i = new int(0);
  5857. res.set_header("Trailer", "Dummy1, Dummy2");
  5858. res.set_chunked_content_provider(
  5859. "text/plain",
  5860. [i](size_t /*offset*/, DataSink &sink) {
  5861. switch (*i) {
  5862. case 0: sink.os << "123"; break;
  5863. case 1: sink.os << "456"; break;
  5864. case 2: sink.os << "789"; break;
  5865. case 3: {
  5866. sink.done_with_trailer(
  5867. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5868. } break;
  5869. }
  5870. (*i)++;
  5871. return true;
  5872. },
  5873. [i](bool success) {
  5874. EXPECT_TRUE(success);
  5875. delete i;
  5876. });
  5877. })
  5878. .Get("/streamed",
  5879. [&](const Request & /*req*/, Response &res) {
  5880. res.set_content_provider(
  5881. 6, "text/plain",
  5882. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5883. sink.os << (offset < 3 ? "a" : "b");
  5884. return true;
  5885. });
  5886. })
  5887. .Get("/streamed-without-length",
  5888. [&](const Request & /*req*/, Response &res) {
  5889. auto data = new std::string("abcdefg");
  5890. res.set_content_provider(
  5891. "text/plain",
  5892. [data](size_t offset, DataSink &sink) {
  5893. if (offset < data->size()) {
  5894. sink.os << data->substr(offset);
  5895. }
  5896. sink.done();
  5897. return true;
  5898. },
  5899. [data](bool success) {
  5900. EXPECT_TRUE(success);
  5901. delete data;
  5902. });
  5903. })
  5904. .Get("/streamed-with-range",
  5905. [&](const Request &req, Response &res) {
  5906. auto data = new std::string("abcdefg");
  5907. // An explicit status keeps the server from picking the 206 it
  5908. // would otherwise choose for a ranged request, so the response
  5909. // is not a partial representation.
  5910. auto status = req.get_param_value("status");
  5911. if (status == "200") {
  5912. res.status = StatusCode::OK_200;
  5913. } else if (status == "403") {
  5914. res.status = StatusCode::Forbidden_403;
  5915. }
  5916. res.set_content_provider(
  5917. data->size(), "text/plain",
  5918. [data](size_t offset, size_t length, DataSink &sink) {
  5919. size_t DATA_CHUNK_SIZE = 4;
  5920. const auto &d = *data;
  5921. auto out_len =
  5922. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5923. auto ret =
  5924. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5925. EXPECT_TRUE(ret);
  5926. return true;
  5927. },
  5928. [data, &req](bool success) {
  5929. EXPECT_EQ(success, !req.has_param("error"));
  5930. delete data;
  5931. });
  5932. })
  5933. .Get("/streamed-cancel",
  5934. [&](const Request & /*req*/, Response &res) {
  5935. res.set_content_provider(
  5936. size_t(-1), "text/plain",
  5937. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5938. sink.os << "data_chunk";
  5939. return true;
  5940. });
  5941. })
  5942. .Get("/regex-with-delimiter",
  5943. [&](const Request &req, Response & /*res*/) {
  5944. ASSERT_TRUE(req.has_param("key"));
  5945. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5946. })
  5947. .Get("/with-range",
  5948. [&](const Request & /*req*/, Response &res) {
  5949. res.set_content("abcdefg", "text/plain");
  5950. })
  5951. .Get("/test-start-time",
  5952. [&](const Request &req, Response & /*res*/) {
  5953. EXPECT_NE(req.start_time_,
  5954. std::chrono::steady_clock::time_point::min());
  5955. })
  5956. .Get("/with-range-customized-response",
  5957. [&](const Request & /*req*/, Response &res) {
  5958. res.status = StatusCode::BadRequest_400;
  5959. res.set_content(JSON_DATA, "application/json");
  5960. })
  5961. .Post("/chunked",
  5962. [&](const Request &req, Response & /*res*/) {
  5963. EXPECT_EQ(req.body, "dechunked post body");
  5964. })
  5965. .Post("/large-chunked",
  5966. [&](const Request &req, Response & /*res*/) {
  5967. std::string expected(6 * 30 * 1024u, 'a');
  5968. EXPECT_EQ(req.body, expected);
  5969. })
  5970. .Post("/multipart",
  5971. [&](const Request &req, Response & /*res*/) {
  5972. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5973. req.form.get_field_count("text2") +
  5974. req.form.get_field_count("file3") +
  5975. req.form.get_field_count("file4"));
  5976. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5977. req.form.get_file_count("file2"));
  5978. ASSERT_TRUE(!req.form.has_file("???"));
  5979. ASSERT_TRUE(!req.form.has_field("???"));
  5980. ASSERT_TRUE(req.body.empty());
  5981. {
  5982. const auto &text = req.form.get_field("text1");
  5983. EXPECT_EQ("text default", text);
  5984. }
  5985. {
  5986. const auto &text = req.form.get_field("text2");
  5987. EXPECT_EQ("aωb", text);
  5988. }
  5989. {
  5990. const auto &file = req.form.get_file("file1");
  5991. EXPECT_EQ("hello.txt", file.filename);
  5992. EXPECT_EQ("text/plain", file.content_type);
  5993. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5994. }
  5995. {
  5996. const auto &file = req.form.get_file("file2");
  5997. EXPECT_EQ("world.json", file.filename);
  5998. EXPECT_EQ("application/json", file.content_type);
  5999. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6000. }
  6001. {
  6002. const auto &text = req.form.get_field("file3");
  6003. EXPECT_EQ(0u, text.size());
  6004. }
  6005. {
  6006. const auto &text = req.form.get_field("file4");
  6007. EXPECT_EQ(0u, text.size());
  6008. }
  6009. })
  6010. .Post("/multipart/multi_file_values",
  6011. [&](const Request &req, Response & /*res*/) {
  6012. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6013. req.form.get_field_count("multi_text1"));
  6014. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6015. ASSERT_TRUE(!req.form.has_file("???"));
  6016. ASSERT_TRUE(!req.form.has_field("???"));
  6017. ASSERT_TRUE(req.body.empty());
  6018. {
  6019. const auto &text = req.form.get_field("text");
  6020. EXPECT_EQ("default text", text);
  6021. }
  6022. {
  6023. const auto &text1_values = req.form.get_fields("multi_text1");
  6024. EXPECT_EQ(2u, text1_values.size());
  6025. EXPECT_EQ("aaaaa", text1_values[0]);
  6026. EXPECT_EQ("bbbbb", text1_values[1]);
  6027. }
  6028. {
  6029. const auto &file1_values = req.form.get_files("multi_file1");
  6030. EXPECT_EQ(2u, file1_values.size());
  6031. auto file1 = file1_values[0];
  6032. EXPECT_EQ(file1.filename, "hello.txt");
  6033. EXPECT_EQ(file1.content_type, "text/plain");
  6034. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6035. auto file2 = file1_values[1];
  6036. EXPECT_EQ(file2.filename, "world.json");
  6037. EXPECT_EQ(file2.content_type, "application/json");
  6038. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6039. }
  6040. })
  6041. .Post("/empty",
  6042. [&](const Request &req, Response &res) {
  6043. EXPECT_EQ(req.body, "");
  6044. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6045. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6046. res.set_content("empty", "text/plain");
  6047. })
  6048. .Post("/empty-no-content-type",
  6049. [&](const Request &req, Response &res) {
  6050. EXPECT_EQ(req.body, "");
  6051. EXPECT_FALSE(req.has_header("Content-Type"));
  6052. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6053. res.set_content("empty-no-content-type", "text/plain");
  6054. })
  6055. .Post("/path-only",
  6056. [&](const Request &req, Response &res) {
  6057. EXPECT_EQ(req.body, "");
  6058. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6059. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6060. res.set_content("path-only", "text/plain");
  6061. })
  6062. .Post("/path-headers-only",
  6063. [&](const Request &req, Response &res) {
  6064. EXPECT_EQ(req.body, "");
  6065. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6066. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6067. EXPECT_EQ("world", req.get_header_value("hello"));
  6068. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6069. res.set_content("path-headers-only", "text/plain");
  6070. })
  6071. .Post("/post-large",
  6072. [&](const Request &req, Response &res) {
  6073. EXPECT_EQ(req.body, LARGE_DATA);
  6074. res.set_content(req.body, "text/plain");
  6075. })
  6076. .Post("/post-loopback",
  6077. [&](const Request &, Response &res,
  6078. ContentReader const &content_reader) {
  6079. std::string body;
  6080. content_reader([&](const char *data, size_t data_length) {
  6081. body.append(data, data_length);
  6082. return true;
  6083. });
  6084. res.set_content(body, "text/plain");
  6085. })
  6086. .Put("/put-loopback",
  6087. [&](const Request &, Response &res,
  6088. ContentReader const &content_reader) {
  6089. std::string body;
  6090. content_reader([&](const char *data, size_t data_length) {
  6091. body.append(data, data_length);
  6092. return true;
  6093. });
  6094. res.set_content(body, "text/plain");
  6095. })
  6096. .Patch("/patch-loopback",
  6097. [&](const Request &, Response &res,
  6098. ContentReader const &content_reader) {
  6099. std::string body;
  6100. content_reader([&](const char *data, size_t data_length) {
  6101. body.append(data, data_length);
  6102. return true;
  6103. });
  6104. res.set_content(body, "text/plain");
  6105. })
  6106. .Put("/empty-no-content-type",
  6107. [&](const Request &req, Response &res) {
  6108. EXPECT_EQ(req.body, "");
  6109. EXPECT_FALSE(req.has_header("Content-Type"));
  6110. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6111. res.set_content("empty-no-content-type", "text/plain");
  6112. })
  6113. .Put("/put",
  6114. [&](const Request &req, Response &res) {
  6115. EXPECT_EQ(req.body, "PUT");
  6116. res.set_content(req.body, "text/plain");
  6117. })
  6118. .Put("/put-large",
  6119. [&](const Request &req, Response &res) {
  6120. EXPECT_EQ(req.body, LARGE_DATA);
  6121. res.set_content(req.body, "text/plain");
  6122. })
  6123. .Patch("/patch",
  6124. [&](const Request &req, Response &res) {
  6125. EXPECT_EQ(req.body, "PATCH");
  6126. res.set_content(req.body, "text/plain");
  6127. })
  6128. .Delete("/delete",
  6129. [&](const Request & /*req*/, Response &res) {
  6130. res.set_content("DELETE", "text/plain");
  6131. })
  6132. .Delete("/delete-body",
  6133. [&](const Request &req, Response &res) {
  6134. EXPECT_EQ(req.body, "content");
  6135. res.set_content(req.body, "text/plain");
  6136. })
  6137. .Options(R"(\*)",
  6138. [&](const Request & /*req*/, Response &res) {
  6139. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6140. })
  6141. .CustomRoute("PROPFIND", "/dav/:id",
  6142. [&](const Request &req, Response &res) {
  6143. res.set_header("x-body-size",
  6144. std::to_string(req.body.size()));
  6145. res.set_header("x-matched-route", req.matched_route);
  6146. res.set_header("x-dav-id", req.path_params.at("id"));
  6147. res.status = StatusCode::MultiStatus_207;
  6148. res.set_content(req.body, "application/xml");
  6149. })
  6150. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6151. [&](const Request &req, Response &res) {
  6152. res.set_header("x-dav-match", req.matches[1]);
  6153. res.status = StatusCode::MultiStatus_207;
  6154. })
  6155. .CustomRoute("MKCOL", "/dav-mkcol",
  6156. [&](const Request &req, Response &res) {
  6157. EXPECT_TRUE(req.body.empty());
  6158. res.status = StatusCode::Created_201;
  6159. })
  6160. .CustomRoute(
  6161. "REPORT", "/dav-report",
  6162. [&](const Request & /*req*/, Response &res,
  6163. const ContentReader &content_reader) {
  6164. std::string body;
  6165. content_reader([&](const char *data, size_t data_length) {
  6166. body.append(data, data_length);
  6167. return true;
  6168. });
  6169. res.set_header("x-body-size", std::to_string(body.size()));
  6170. res.status = StatusCode::MultiStatus_207;
  6171. res.set_content(body, "application/xml");
  6172. })
  6173. .Get("/request-target",
  6174. [&](const Request &req, Response & /*res*/) {
  6175. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6176. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6177. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6178. })
  6179. .Get("/long-query-value",
  6180. [&](const Request &req, Response & /*res*/) {
  6181. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6182. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6183. })
  6184. .Get("/too-long-query-value",
  6185. [&](const Request &req, Response & /*res*/) {
  6186. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6187. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6188. })
  6189. .Get("/array-param",
  6190. [&](const Request &req, Response & /*res*/) {
  6191. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6192. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6193. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6194. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6195. })
  6196. .Get("/array-param-values",
  6197. [&](const Request &req, Response & /*res*/) {
  6198. auto values = req.get_param_values("array");
  6199. EXPECT_EQ(3u, values.size());
  6200. EXPECT_EQ("value1", values[0]);
  6201. EXPECT_EQ("value2", values[1]);
  6202. EXPECT_EQ("value3", values[2]);
  6203. auto empty = req.get_param_values("nonexistent");
  6204. EXPECT_TRUE(empty.empty());
  6205. })
  6206. .Post("/validate-no-multiple-headers",
  6207. [&](const Request &req, Response & /*res*/) {
  6208. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6209. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6210. })
  6211. .Post("/content_receiver",
  6212. [&](const Request &req, Response &res,
  6213. const ContentReader &content_reader) {
  6214. if (req.is_multipart_form_data()) {
  6215. std::vector<FormData> items;
  6216. content_reader(
  6217. [&](const FormData &file) {
  6218. items.push_back(file);
  6219. return true;
  6220. },
  6221. [&](const char *data, size_t data_length) {
  6222. items.back().content.append(data, data_length);
  6223. return true;
  6224. });
  6225. EXPECT_EQ(5u, items.size());
  6226. {
  6227. const auto &file = get_file_value(items, "text1");
  6228. EXPECT_TRUE(file.filename.empty());
  6229. EXPECT_EQ("text default", file.content);
  6230. }
  6231. {
  6232. const auto &file = get_file_value(items, "text2");
  6233. EXPECT_TRUE(file.filename.empty());
  6234. EXPECT_EQ("aωb", file.content);
  6235. }
  6236. {
  6237. const auto &file = get_file_value(items, "file1");
  6238. EXPECT_EQ("hello.txt", file.filename);
  6239. EXPECT_EQ("text/plain", file.content_type);
  6240. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6241. }
  6242. {
  6243. const auto &file = get_file_value(items, "file2");
  6244. EXPECT_EQ("world.json", file.filename);
  6245. EXPECT_EQ("application/json", file.content_type);
  6246. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6247. }
  6248. {
  6249. const auto &file = get_file_value(items, "file3");
  6250. EXPECT_TRUE(file.filename.empty());
  6251. EXPECT_EQ("application/octet-stream", file.content_type);
  6252. EXPECT_EQ(0u, file.content.size());
  6253. }
  6254. } else {
  6255. std::string body;
  6256. content_reader([&](const char *data, size_t data_length) {
  6257. EXPECT_EQ(7U, data_length);
  6258. body.append(data, data_length);
  6259. return true;
  6260. });
  6261. EXPECT_EQ(body, "content");
  6262. res.set_content(body, "text/plain");
  6263. }
  6264. })
  6265. .Put("/content_receiver",
  6266. [&](const Request & /*req*/, Response &res,
  6267. const ContentReader &content_reader) {
  6268. std::string body;
  6269. content_reader([&](const char *data, size_t data_length) {
  6270. body.append(data, data_length);
  6271. return true;
  6272. });
  6273. EXPECT_EQ(body, "content");
  6274. res.set_content(body, "text/plain");
  6275. })
  6276. .Patch("/content_receiver",
  6277. [&](const Request & /*req*/, Response &res,
  6278. const ContentReader &content_reader) {
  6279. std::string body;
  6280. content_reader([&](const char *data, size_t data_length) {
  6281. body.append(data, data_length);
  6282. return true;
  6283. });
  6284. EXPECT_EQ(body, "content");
  6285. res.set_content(body, "text/plain");
  6286. })
  6287. .Post("/query-string-and-body",
  6288. [&](const Request &req, Response & /*res*/) {
  6289. ASSERT_TRUE(req.has_param("key"));
  6290. EXPECT_EQ(req.get_param_value("key"), "value");
  6291. EXPECT_EQ(req.body, "content");
  6292. })
  6293. .Get("/last-request",
  6294. [&](const Request &req, Response & /*res*/) {
  6295. EXPECT_EQ("close", req.get_header_value("Connection"));
  6296. })
  6297. .Get(R"(/redirect/(\d+))",
  6298. [&](const Request &req, Response &res) {
  6299. auto num = std::stoi(req.matches[1]) + 1;
  6300. std::string url = "/redirect/" + std::to_string(num);
  6301. res.set_redirect(url);
  6302. })
  6303. .Post("/binary",
  6304. [&](const Request &req, Response &res) {
  6305. EXPECT_EQ(4U, req.body.size());
  6306. EXPECT_EQ("application/octet-stream",
  6307. req.get_header_value("Content-Type"));
  6308. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6309. res.set_content(req.body, "application/octet-stream");
  6310. })
  6311. .Put("/binary",
  6312. [&](const Request &req, Response &res) {
  6313. EXPECT_EQ(4U, req.body.size());
  6314. EXPECT_EQ("application/octet-stream",
  6315. req.get_header_value("Content-Type"));
  6316. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6317. res.set_content(req.body, "application/octet-stream");
  6318. })
  6319. .Patch("/binary",
  6320. [&](const Request &req, Response &res) {
  6321. EXPECT_EQ(4U, req.body.size());
  6322. EXPECT_EQ("application/octet-stream",
  6323. req.get_header_value("Content-Type"));
  6324. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6325. res.set_content(req.body, "application/octet-stream");
  6326. })
  6327. .Delete("/binary",
  6328. [&](const Request &req, Response &res) {
  6329. EXPECT_EQ(4U, req.body.size());
  6330. EXPECT_EQ("application/octet-stream",
  6331. req.get_header_value("Content-Type"));
  6332. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6333. res.set_content(req.body, "application/octet-stream");
  6334. })
  6335. .Get("/issue1772",
  6336. [&](const Request & /*req*/, Response &res) {
  6337. res.status = 401;
  6338. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6339. })
  6340. .Delete("/issue609",
  6341. [](const httplib::Request &, httplib::Response &res,
  6342. const httplib::ContentReader &) {
  6343. res.set_content("ok", "text/plain");
  6344. })
  6345. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6346. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6347. .Get("/compress",
  6348. [&](const Request & /*req*/, Response &res) {
  6349. res.set_content(
  6350. "12345678901234567890123456789012345678901234567890123456789"
  6351. "01234567890123456789012345678901234567890",
  6352. "text/plain");
  6353. })
  6354. .Get("/compress-with-charset",
  6355. [&](const Request & /*req*/, Response &res) {
  6356. res.set_content(
  6357. "12345678901234567890123456789012345678901234567890123456789"
  6358. "01234567890123456789012345678901234567890",
  6359. "application/json; charset=utf-8");
  6360. })
  6361. .Get("/nocompress",
  6362. [&](const Request & /*req*/, Response &res) {
  6363. res.set_content(
  6364. "12345678901234567890123456789012345678901234567890123456789"
  6365. "01234567890123456789012345678901234567890",
  6366. "application/octet-stream");
  6367. })
  6368. .Post("/compress-multipart",
  6369. [&](const Request &req, Response & /*res*/) {
  6370. EXPECT_EQ(2u, req.form.fields.size());
  6371. ASSERT_TRUE(!req.form.has_field("???"));
  6372. {
  6373. const auto &text = req.form.get_field("key1");
  6374. EXPECT_EQ("test", text);
  6375. }
  6376. {
  6377. const auto &text = req.form.get_field("key2");
  6378. EXPECT_EQ("--abcdefg123", text);
  6379. }
  6380. })
  6381. #endif
  6382. ;
  6383. persons_["john"] = "programmer";
  6384. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6385. svr_.wait_until_ready();
  6386. }
  6387. virtual void TearDown() {
  6388. svr_.stop();
  6389. if (!request_threads_.empty()) {
  6390. std::this_thread::sleep_for(std::chrono::seconds(1));
  6391. for (auto &t : request_threads_) {
  6392. t.join();
  6393. }
  6394. }
  6395. t_.join();
  6396. }
  6397. map<string, string> persons_;
  6398. #ifdef CPPHTTPLIB_SSL_ENABLED
  6399. SSLClient cli_;
  6400. SSLServer svr_;
  6401. #else
  6402. Client cli_;
  6403. Server svr_;
  6404. #endif
  6405. thread t_;
  6406. std::vector<thread> request_threads_;
  6407. };
  6408. TEST_F(ServerTest, GetMethod200) {
  6409. auto res = cli_.Get("/hi");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ("HTTP/1.1", res->version);
  6412. EXPECT_EQ(StatusCode::OK_200, res->status);
  6413. EXPECT_EQ("OK", res->reason);
  6414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6415. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6416. EXPECT_EQ("Hello World!", res->body);
  6417. }
  6418. TEST_F(ServerTest, GetEmptyFile) {
  6419. auto res = cli_.Get("/empty_file");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. EXPECT_EQ(StatusCode::OK_200, res->status);
  6422. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6423. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6424. EXPECT_EQ("", res->body);
  6425. }
  6426. TEST_F(ServerTest, GetFileContent) {
  6427. auto res = cli_.Get("/file_content");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::OK_200, res->status);
  6430. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6431. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6432. EXPECT_EQ("test.html", res->body);
  6433. }
  6434. TEST_F(ServerTest, GetFileContentWithRange) {
  6435. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6438. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6439. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6440. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6441. EXPECT_EQ("est", res->body);
  6442. }
  6443. TEST_F(ServerTest, GetFileContentWithContentType) {
  6444. auto res = cli_.Get("/file_content_with_content_type");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::OK_200, res->status);
  6447. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6448. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6449. EXPECT_EQ("file\n", res->body);
  6450. }
  6451. TEST_F(ServerTest, GetInvalidFileContent) {
  6452. auto res = cli_.Get("/invalid_file_content");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6455. }
  6456. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6457. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. EXPECT_EQ("HTTP/1.1", res->version);
  6460. EXPECT_EQ(StatusCode::OK_200, res->status);
  6461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6462. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6463. EXPECT_EQ("Hello World!", res->body);
  6464. }
  6465. TEST_F(ServerTest, GetMethod302) {
  6466. auto res = cli_.Get("/");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::Found_302, res->status);
  6469. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6470. }
  6471. TEST_F(ServerTest, GetMethod302Redirect) {
  6472. cli_.set_follow_location(true);
  6473. auto res = cli_.Get("/");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. EXPECT_EQ(StatusCode::OK_200, res->status);
  6476. EXPECT_EQ("Hello World!", res->body);
  6477. EXPECT_EQ("/hi", res->location);
  6478. }
  6479. TEST_F(ServerTest, GetMethod404) {
  6480. auto res = cli_.Get("/invalid");
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6483. }
  6484. TEST_F(ServerTest, HeadMethod200) {
  6485. auto res = cli_.Head("/hi");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. EXPECT_EQ(StatusCode::OK_200, res->status);
  6488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6489. EXPECT_TRUE(res->body.empty());
  6490. }
  6491. TEST_F(ServerTest, HeadMethod200Static) {
  6492. auto res = cli_.Head("/mount/dir/index.html");
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::OK_200, res->status);
  6495. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6496. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6497. EXPECT_TRUE(res->body.empty());
  6498. }
  6499. TEST_F(ServerTest, HeadMethod404) {
  6500. auto res = cli_.Head("/invalid");
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6503. EXPECT_TRUE(res->body.empty());
  6504. }
  6505. TEST_F(ServerTest, GetMethodPersonJohn) {
  6506. auto res = cli_.Get("/person/john");
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::OK_200, res->status);
  6509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6510. EXPECT_EQ("programmer", res->body);
  6511. }
  6512. TEST_F(ServerTest, PostMethod1) {
  6513. auto res = cli_.Get("/person/john1");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6516. res = cli_.Post("/person", "name=john1&note=coder",
  6517. "application/x-www-form-urlencoded");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. ASSERT_EQ(StatusCode::OK_200, res->status);
  6520. res = cli_.Get("/person/john1");
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. ASSERT_EQ(StatusCode::OK_200, res->status);
  6523. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6524. ASSERT_EQ("coder", res->body);
  6525. }
  6526. TEST_F(ServerTest, PostMethod2) {
  6527. auto res = cli_.Get("/person/john2");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6530. Params params;
  6531. params.emplace("name", "john2");
  6532. params.emplace("note", "coder");
  6533. res = cli_.Post("/person", params);
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. ASSERT_EQ(StatusCode::OK_200, res->status);
  6536. res = cli_.Get("/person/john2");
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. ASSERT_EQ(StatusCode::OK_200, res->status);
  6539. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6540. ASSERT_EQ("coder", res->body);
  6541. }
  6542. TEST_F(ServerTest, PutMethod3) {
  6543. auto res = cli_.Get("/person/john3");
  6544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6545. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6546. Params params;
  6547. params.emplace("name", "john3");
  6548. params.emplace("note", "coder");
  6549. res = cli_.Put("/person", params);
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. ASSERT_EQ(StatusCode::OK_200, res->status);
  6552. res = cli_.Get("/person/john3");
  6553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6554. ASSERT_EQ(StatusCode::OK_200, res->status);
  6555. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6556. ASSERT_EQ("coder", res->body);
  6557. }
  6558. TEST_F(ServerTest, DeleteMethod1) {
  6559. auto res = cli_.Get("/person/john4");
  6560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6561. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6562. Params params;
  6563. params.emplace("name", "john4");
  6564. params.emplace("note", "coder");
  6565. res = cli_.Post("/person", params);
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. ASSERT_EQ(StatusCode::OK_200, res->status);
  6568. res = cli_.Get("/person/john4");
  6569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6570. ASSERT_EQ(StatusCode::OK_200, res->status);
  6571. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6572. ASSERT_EQ("coder", res->body);
  6573. Params delete_params;
  6574. delete_params.emplace("name", "john4");
  6575. res = cli_.Delete("/person", delete_params);
  6576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6577. ASSERT_EQ(StatusCode::OK_200, res->status);
  6578. ASSERT_EQ("DELETED", res->body);
  6579. res = cli_.Get("/person/john4");
  6580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6581. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6582. }
  6583. TEST_F(ServerTest, DeleteMethod2) {
  6584. auto res = cli_.Get("/person/john5");
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6587. Params params;
  6588. params.emplace("name", "john5");
  6589. params.emplace("note", "developer");
  6590. res = cli_.Post("/person", params);
  6591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6592. ASSERT_EQ(StatusCode::OK_200, res->status);
  6593. res = cli_.Get("/person/john5");
  6594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6595. ASSERT_EQ(StatusCode::OK_200, res->status);
  6596. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6597. ASSERT_EQ("developer", res->body);
  6598. Params delete_params;
  6599. delete_params.emplace("name", "john5");
  6600. Headers headers;
  6601. headers.emplace("Custom-Header", "test-value");
  6602. res = cli_.Delete("/person", headers, delete_params);
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. ASSERT_EQ(StatusCode::OK_200, res->status);
  6605. ASSERT_EQ("DELETED", res->body);
  6606. res = cli_.Get("/person/john5");
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6609. }
  6610. TEST_F(ServerTest, DeleteMethod3) {
  6611. auto res = cli_.Get("/person/john6");
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6614. Params params;
  6615. params.emplace("name", "john6");
  6616. params.emplace("note", "tester");
  6617. res = cli_.Post("/person", params);
  6618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6619. ASSERT_EQ(StatusCode::OK_200, res->status);
  6620. res = cli_.Get("/person/john6");
  6621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6622. ASSERT_EQ(StatusCode::OK_200, res->status);
  6623. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6624. ASSERT_EQ("tester", res->body);
  6625. Params delete_params;
  6626. delete_params.emplace("name", "john6");
  6627. Headers headers;
  6628. headers.emplace("Custom-Header", "test-value");
  6629. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6631. ASSERT_EQ(StatusCode::OK_200, res->status);
  6632. ASSERT_EQ("DELETED", res->body);
  6633. res = cli_.Get("/person/john6");
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6636. }
  6637. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6638. Params params;
  6639. params.emplace("json", JSON_DATA);
  6640. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. ASSERT_EQ(StatusCode::OK_200, res->status);
  6643. ASSERT_EQ(JSON_DATA, res->body);
  6644. }
  6645. TEST_F(ServerTest, PostEmptyContent) {
  6646. auto res = cli_.Post("/empty", "", "text/plain");
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. ASSERT_EQ(StatusCode::OK_200, res->status);
  6649. ASSERT_EQ("empty", res->body);
  6650. }
  6651. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6652. auto res = cli_.Post("/empty-no-content-type");
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. ASSERT_EQ(StatusCode::OK_200, res->status);
  6655. ASSERT_EQ("empty-no-content-type", res->body);
  6656. }
  6657. TEST_F(ServerTest, PostPathOnly) {
  6658. auto res = cli_.Post("/path-only");
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. ASSERT_EQ(StatusCode::OK_200, res->status);
  6661. ASSERT_EQ("path-only", res->body);
  6662. }
  6663. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6664. auto res = cli_.Post("/path-headers-only",
  6665. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. ASSERT_EQ(StatusCode::OK_200, res->status);
  6668. ASSERT_EQ("path-headers-only", res->body);
  6669. }
  6670. TEST_F(ServerTest, PostLarge) {
  6671. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. ASSERT_EQ(StatusCode::OK_200, res->status);
  6674. EXPECT_EQ(LARGE_DATA, res->body);
  6675. }
  6676. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6677. auto res = cli_.Put("/empty-no-content-type");
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. ASSERT_EQ(StatusCode::OK_200, res->status);
  6680. ASSERT_EQ("empty-no-content-type", res->body);
  6681. }
  6682. TEST_F(ServerTest, GetMethodDir) {
  6683. auto res = cli_.Get("/dir/");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6687. auto body = R"(<html>
  6688. <head>
  6689. </head>
  6690. <body>
  6691. <a href="/dir/test.html">Test</a>
  6692. <a href="/hi">hi</a>
  6693. </body>
  6694. </html>
  6695. )";
  6696. EXPECT_EQ(body, res->body);
  6697. }
  6698. TEST_F(ServerTest, GetMethodDirTest) {
  6699. auto res = cli_.Get("/dir/test.html");
  6700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6701. EXPECT_EQ(StatusCode::OK_200, res->status);
  6702. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6703. EXPECT_EQ("test.html", res->body);
  6704. }
  6705. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6706. auto res = cli_.Get("/dir/../dir/test.html");
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6709. }
  6710. TEST_F(ServerTest, GetMethodInvalidPath) {
  6711. auto res = cli_.Get("/dir/../test.html");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6714. }
  6715. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6716. auto res = cli_.Get("/../www/dir/test.html");
  6717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6719. }
  6720. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6721. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6724. }
  6725. TEST_F(ServerTest, GetMethodDirMountTest) {
  6726. auto res = cli_.Get("/mount/dir/test.html");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ("test.html", res->body);
  6731. }
  6732. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6733. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6736. }
  6737. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6738. auto res = cli_.Get("/mount/dir/../test.html");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6741. }
  6742. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6743. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6746. }
  6747. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6748. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6751. }
  6752. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6753. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6756. }
  6757. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6758. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6761. }
  6762. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6763. auto res = cli_.Get("/mount/dir");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6766. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6767. }
  6768. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6769. auto res = cli_.Get("//dir");
  6770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6772. EXPECT_FALSE(res->has_header("Location"));
  6773. }
  6774. TEST_F(ServerTest, PostMethod303) {
  6775. auto res = cli_.Post("/1", "body", "text/plain");
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6778. EXPECT_EQ("/2", res->get_header_value("Location"));
  6779. }
  6780. TEST_F(ServerTest, PostMethod303Redirect) {
  6781. cli_.set_follow_location(true);
  6782. auto res = cli_.Post("/1", "body", "text/plain");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ("redirected.", res->body);
  6786. EXPECT_EQ("/2", res->location);
  6787. }
  6788. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6789. auto res = cli_.Get("/dir/test.abcde");
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(StatusCode::OK_200, res->status);
  6792. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6793. EXPECT_EQ("abcde", res->body);
  6794. }
  6795. TEST_F(ServerTest, StaticFileRange) {
  6796. auto res =
  6797. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6800. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6801. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6802. EXPECT_EQ(true, res->has_header("Content-Range"));
  6803. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6804. EXPECT_EQ(std::string("cd"), res->body);
  6805. }
  6806. TEST_F(ServerTest, StaticFileRanges) {
  6807. auto res = cli_.Get("/dir/test.abcde",
  6808. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6811. EXPECT_TRUE(
  6812. res->get_header_value("Content-Type")
  6813. .find(
  6814. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6815. 0);
  6816. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6817. }
  6818. TEST_F(ServerTest, StaticFileRangeHead) {
  6819. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6822. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6823. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6824. EXPECT_EQ(true, res->has_header("Content-Range"));
  6825. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6826. }
  6827. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6828. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6831. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6832. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6833. EXPECT_EQ(true, res->has_header("Content-Range"));
  6834. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6835. res->get_header_value("Content-Range"));
  6836. EXPECT_EQ("LAST\n", res->body);
  6837. }
  6838. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6839. auto res =
  6840. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6844. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6845. EXPECT_EQ(true, res->has_header("Content-Range"));
  6846. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6847. }
  6848. TEST_F(ServerTest, StaticFileBigFile) {
  6849. auto res = cli_.Get("/dir/1MB.txt");
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6853. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6854. }
  6855. TEST_F(ServerTest, InvalidBaseDirMount) {
  6856. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6857. }
  6858. TEST_F(ServerTest, Binary) {
  6859. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6860. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6861. "application/octet-stream");
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. ASSERT_EQ(StatusCode::OK_200, res->status);
  6864. ASSERT_EQ(4U, res->body.size());
  6865. res = cli_.Put("/binary", binary.data(), binary.size(),
  6866. "application/octet-stream");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. ASSERT_EQ(StatusCode::OK_200, res->status);
  6869. ASSERT_EQ(4U, res->body.size());
  6870. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6871. "application/octet-stream");
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. ASSERT_EQ(StatusCode::OK_200, res->status);
  6874. ASSERT_EQ(4U, res->body.size());
  6875. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6876. "application/octet-stream");
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. ASSERT_EQ(StatusCode::OK_200, res->status);
  6879. ASSERT_EQ(4U, res->body.size());
  6880. }
  6881. TEST_F(ServerTest, BinaryString) {
  6882. auto binary = std::string("\x00\x01\x02\x03", 4);
  6883. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. ASSERT_EQ(StatusCode::OK_200, res->status);
  6886. ASSERT_EQ(4U, res->body.size());
  6887. res = cli_.Put("/binary", binary, "application/octet-stream");
  6888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6889. ASSERT_EQ(StatusCode::OK_200, res->status);
  6890. ASSERT_EQ(4U, res->body.size());
  6891. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. ASSERT_EQ(StatusCode::OK_200, res->status);
  6894. ASSERT_EQ(4U, res->body.size());
  6895. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. ASSERT_EQ(StatusCode::OK_200, res->status);
  6898. ASSERT_EQ(4U, res->body.size());
  6899. }
  6900. TEST_F(ServerTest, EmptyRequest) {
  6901. auto res = cli_.Get("");
  6902. ASSERT_TRUE(!res);
  6903. EXPECT_EQ(Error::Connection, res.error());
  6904. }
  6905. TEST_F(ServerTest, LongRequest) {
  6906. std::string request;
  6907. for (size_t i = 0; i < 545; i++) {
  6908. request += "/TooLongRequest";
  6909. }
  6910. request += "OK";
  6911. auto res = cli_.Get(request.c_str());
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6914. }
  6915. TEST_F(ServerTest, TooLongRequest) {
  6916. std::string request;
  6917. for (size_t i = 0; i < 546; i++) {
  6918. request += "/TooLongRequest";
  6919. }
  6920. request += "_NG";
  6921. auto start = std::chrono::high_resolution_clock::now();
  6922. cli_.set_keep_alive(true);
  6923. auto res = cli_.Get(request.c_str());
  6924. auto end = std::chrono::high_resolution_clock::now();
  6925. auto elapsed =
  6926. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6927. .count();
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6930. EXPECT_LE(elapsed, 1000);
  6931. EXPECT_EQ("close", res->get_header_value("Connection"));
  6932. EXPECT_FALSE(cli_.is_socket_open());
  6933. }
  6934. TEST_F(ServerTest, AlmostTooLongRequest) {
  6935. // test for #2046 - URI length check shouldn't include other content on req
  6936. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6937. // leading /, space, HTTP/1.1)
  6938. std::string request =
  6939. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6940. auto res = cli_.Get(request.c_str());
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6943. }
  6944. TEST_F(ServerTest, LongHeader) {
  6945. Request req;
  6946. req.method = "GET";
  6947. req.path = "/hi";
  6948. std::string host_and_port;
  6949. host_and_port += HOST;
  6950. host_and_port += ":";
  6951. host_and_port += std::to_string(PORT);
  6952. req.headers.emplace("Host", host_and_port.c_str());
  6953. req.headers.emplace("Accept", "*/*");
  6954. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6955. req.headers.emplace(
  6956. "Header-Name",
  6957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6985. "@@@@@@@@@@@@@@@@");
  6986. auto res = std::make_shared<Response>();
  6987. auto error = Error::Success;
  6988. auto ret = cli_.send(req, *res, error);
  6989. ASSERT_TRUE(ret);
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. }
  6992. TEST_F(ServerTest, LongQueryValue) {
  6993. auto start = std::chrono::high_resolution_clock::now();
  6994. cli_.set_keep_alive(true);
  6995. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6996. auto end = std::chrono::high_resolution_clock::now();
  6997. auto elapsed =
  6998. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6999. .count();
  7000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7001. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7002. EXPECT_LE(elapsed, 1000);
  7003. EXPECT_EQ("close", res->get_header_value("Connection"));
  7004. EXPECT_FALSE(cli_.is_socket_open());
  7005. }
  7006. TEST_F(ServerTest, TooLongQueryValue) {
  7007. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7008. ASSERT_FALSE(res);
  7009. EXPECT_EQ(Error::Read, res.error());
  7010. }
  7011. TEST_F(ServerTest, TooLongHeader) {
  7012. Request req;
  7013. req.method = "GET";
  7014. req.path = "/hi";
  7015. std::string host_and_port;
  7016. host_and_port += HOST;
  7017. host_and_port += ":";
  7018. host_and_port += std::to_string(PORT);
  7019. req.headers.emplace("Host", host_and_port.c_str());
  7020. req.headers.emplace("Accept", "*/*");
  7021. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7022. req.headers.emplace(
  7023. "Header-Name",
  7024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7052. "@@@@@@@@@@@@@@@@@");
  7053. auto res = std::make_shared<Response>();
  7054. auto error = Error::Success;
  7055. auto ret = cli_.send(req, *res, error);
  7056. ASSERT_TRUE(ret);
  7057. EXPECT_EQ(StatusCode::OK_200, res->status);
  7058. }
  7059. TEST_F(ServerTest, HeaderCountAtLimit) {
  7060. // Test with headers just under the 100 limit
  7061. httplib::Headers headers;
  7062. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7063. // This should keep us just under the 100 header limit
  7064. for (int i = 0; i < 95; i++) {
  7065. std::string name = "X-Test-Header-" + std::to_string(i);
  7066. std::string value = "value" + std::to_string(i);
  7067. headers.emplace(name, value);
  7068. }
  7069. // This should work fine as we're under the limit
  7070. auto res = cli_.Get("/hi", headers);
  7071. EXPECT_TRUE(res);
  7072. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7073. }
  7074. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7075. // Test with many headers to exceed the 100 limit
  7076. httplib::Headers headers;
  7077. // Add 150 headers to definitely exceed the 100 limit
  7078. for (int i = 0; i < 150; i++) {
  7079. std::string name = "X-Test-Header-" + std::to_string(i);
  7080. std::string value = "value" + std::to_string(i);
  7081. headers.emplace(name, value);
  7082. }
  7083. // This should fail due to exceeding header count limit
  7084. cli_.set_keep_alive(true);
  7085. auto res = cli_.Get("/hi", headers);
  7086. // The server should respond with 400 Bad Request
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7089. EXPECT_EQ("close", res->get_header_value("Connection"));
  7090. EXPECT_FALSE(cli_.is_socket_open());
  7091. }
  7092. TEST_F(ServerTest, PercentEncoding) {
  7093. auto res = cli_.Get("/e%6edwith%");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. }
  7097. TEST_F(ServerTest, PercentEncodingUnicode) {
  7098. auto res = cli_.Get("/e%u006edwith%");
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::OK_200, res->status);
  7101. }
  7102. TEST_F(ServerTest, InvalidPercentEncoding) {
  7103. auto res = cli_.Get("/%endwith%");
  7104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7105. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7106. }
  7107. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7108. auto res = cli_.Get("/%uendwith%");
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7111. }
  7112. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7113. auto res = cli_.Get("/hello?aaa=bbb%");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7116. }
  7117. TEST_F(ServerTest, PlusSignEncoding) {
  7118. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::OK_200, res->status);
  7121. EXPECT_EQ("a +b", res->body);
  7122. }
  7123. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7124. // This test simulates a potential DoS attack using many headers
  7125. // to verify our security fix prevents memory exhaustion
  7126. httplib::Headers attack_headers;
  7127. // Attempt to add many headers like an attacker would (200 headers to far
  7128. // exceed limit)
  7129. for (int i = 0; i < 200; i++) {
  7130. std::string name = "X-Attack-Header-" + std::to_string(i);
  7131. std::string value = "attack_payload_" + std::to_string(i);
  7132. attack_headers.emplace(name, value);
  7133. }
  7134. // Try to POST with excessive headers
  7135. cli_.set_keep_alive(true);
  7136. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7137. // Should either fail or return 400 Bad Request due to security limit
  7138. if (res) {
  7139. // If we get a response, it should be 400 Bad Request
  7140. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7141. EXPECT_EQ("close", res->get_header_value("Connection"));
  7142. }
  7143. EXPECT_FALSE(cli_.is_socket_open());
  7144. }
  7145. TEST_F(ServerTest, MultipartFormData) {
  7146. UploadFormDataItems items = {
  7147. {"text1", "text default", "", ""},
  7148. {"text2", "aωb", "", ""},
  7149. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7150. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7151. {"file3", "", "", "application/octet-stream"},
  7152. {"file4", "", "", " application/json tmp-string "}};
  7153. auto res = cli_.Post("/multipart", items);
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::OK_200, res->status);
  7156. }
  7157. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7158. UploadFormDataItems items = {
  7159. {"text", "default text", "", ""},
  7160. {"multi_text1", "aaaaa", "", ""},
  7161. {"multi_text1", "bbbbb", "", ""},
  7162. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7163. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7164. "application/json"},
  7165. };
  7166. auto res = cli_.Post("/multipart/multi_file_values", items);
  7167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7168. EXPECT_EQ(StatusCode::OK_200, res->status);
  7169. }
  7170. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7171. auto res = cli_.Get("/hi");
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::OK_200, res->status);
  7174. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7175. EXPECT_EQ("Hello World!", res->body);
  7176. }
  7177. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7178. Request req;
  7179. req.method = "POST";
  7180. req.path = "/chunked";
  7181. std::string host_and_port;
  7182. host_and_port += HOST;
  7183. host_and_port += ":";
  7184. host_and_port += std::to_string(PORT);
  7185. req.headers.emplace("Host", host_and_port.c_str());
  7186. req.headers.emplace("Accept", "*/*");
  7187. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7188. req.headers.emplace("Content-Type", "text/plain");
  7189. req.headers.emplace("Content-Length", "0");
  7190. req.headers.emplace(
  7191. "Transfer-Encoding",
  7192. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7193. // Client does not chunk, so make a chunked body manually.
  7194. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7195. auto res = std::make_shared<Response>();
  7196. auto error = Error::Success;
  7197. auto ret = cli_.send(req, *res, error);
  7198. ASSERT_TRUE(ret);
  7199. EXPECT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. template <typename ClientT>
  7202. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7203. int expected_status) {
  7204. Request req;
  7205. req.method = "POST";
  7206. req.path = "/chunked";
  7207. std::string host_and_port;
  7208. host_and_port += HOST;
  7209. host_and_port += ":";
  7210. host_and_port += std::to_string(PORT);
  7211. req.headers.emplace("Host", host_and_port.c_str());
  7212. req.headers.emplace("Content-Length", "0");
  7213. req.headers.emplace("Transfer-Encoding", "chunked");
  7214. req.body = body;
  7215. auto res = std::make_shared<Response>();
  7216. auto error = Error::Success;
  7217. ASSERT_TRUE(cli.send(req, *res, error));
  7218. EXPECT_EQ(expected_status, res->status);
  7219. }
  7220. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7221. // rather than treat them as valid lengths.
  7222. template <typename ClientT>
  7223. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7224. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7225. }
  7226. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7227. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7228. }
  7229. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7230. expect_chunked_body_rejected(
  7231. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7232. }
  7233. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7234. // chunk-size line carries no CR, LF or other control character ahead of its
  7235. // terminator. Such a line must be refused rather than read as extension text.
  7236. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7237. expect_chunked_body_rejected(
  7238. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7239. }
  7240. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7241. expect_chunked_body_rejected(
  7242. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7243. }
  7244. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7245. expect_chunked_body_rejected(
  7246. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7247. }
  7248. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7249. // The literal stays split: a hex escape consumes every hex digit that
  7250. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7251. expect_chunked_body_rejected(
  7252. cli_, "4;a\x01"
  7253. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7254. }
  7255. // The bytes around chunk data are no payload, so they cannot ride on the
  7256. // payload limit
  7257. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7258. // Small enough that the whole request is sent before the server turns it
  7259. // down, yet past the limit by the last chunks
  7260. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7261. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7262. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7263. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7264. SCOPED_TRACE(size_line.substr(0, 2));
  7265. std::string body;
  7266. for (auto c : std::string("dechunked post body")) {
  7267. body += size_line + "\r\n" + c + "\r\n";
  7268. }
  7269. body += "0\r\n\r\n";
  7270. expect_chunked_body_rejected(cli_, body.c_str());
  7271. }
  7272. }
  7273. TEST_F(ServerTest, AcceptsChunkExtension) {
  7274. expect_chunked_body_status(cli_,
  7275. "4;name=value\r\ndech\r\n"
  7276. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7277. "0;last\r\n\r\n",
  7278. StatusCode::OK_200);
  7279. }
  7280. TEST_F(ServerTest, GetStreamed2) {
  7281. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7283. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7284. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7285. EXPECT_EQ(true, res->has_header("Content-Range"));
  7286. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7287. EXPECT_EQ(std::string("ab"), res->body);
  7288. }
  7289. TEST_F(ServerTest, GetStreamed) {
  7290. auto res = cli_.Get("/streamed");
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::OK_200, res->status);
  7293. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7294. EXPECT_EQ(std::string("aaabbb"), res->body);
  7295. }
  7296. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7297. auto res = cli_.Get("/streamed-without-length",
  7298. Headers{make_range_header({{0, -1}})});
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. EXPECT_EQ(false, res->has_header("Content-Length"));
  7302. EXPECT_EQ(false, res->has_header("Content-Range"));
  7303. EXPECT_EQ(std::string("abcdefg"), res->body);
  7304. }
  7305. TEST_F(ServerTest, GetStreamedWithRange1) {
  7306. auto res =
  7307. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7310. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7311. EXPECT_EQ(true, res->has_header("Content-Range"));
  7312. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7313. EXPECT_EQ(std::string("def"), res->body);
  7314. }
  7315. TEST_F(ServerTest, GetStreamedWithRange2) {
  7316. auto res =
  7317. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7320. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7321. EXPECT_EQ(true, res->has_header("Content-Range"));
  7322. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7323. EXPECT_EQ(std::string("bcdefg"), res->body);
  7324. }
  7325. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7326. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7329. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7330. EXPECT_EQ(true, res->has_header("Content-Range"));
  7331. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7332. EXPECT_EQ(std::string("efg"), res->body);
  7333. }
  7334. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7335. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7336. // the entire representation.
  7337. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7338. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7341. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7342. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7343. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7344. }
  7345. }
  7346. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7347. auto res =
  7348. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7351. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7352. EXPECT_EQ(false, res->has_header("Content-Range"));
  7353. EXPECT_EQ(0U, res->body.size());
  7354. }
  7355. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7356. // Only a 206 is served as a partial representation. Under any other status
  7357. // `apply_ranges()` reported the full content length, so the body must match
  7358. // that header, and the content provider must never be asked for an offset
  7359. // outside the representation.
  7360. auto check = [&](int status, const char *range) {
  7361. auto path =
  7362. std::string("/streamed-with-range?status=") + std::to_string(status);
  7363. auto ctx = path + " Range: " + range;
  7364. auto res = cli_.Get(path, Headers{{"Range", range}});
  7365. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7366. EXPECT_EQ(status, res->status) << ctx;
  7367. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7369. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7370. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7371. };
  7372. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7373. check(403, "bytes=3-5");
  7374. // The offset is far past the representation.
  7375. check(403, "bytes=100000-100200");
  7376. // `first_pos` is still -1 here, and the bounds asserts in
  7377. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7378. check(403, "bytes=-3");
  7379. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7380. // multipart branch would have written one that is empty.
  7381. check(403, "bytes=1-2, 4-5");
  7382. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7383. // covers the whole representation.
  7384. check(200, "bytes=3-5");
  7385. check(200, "bytes=1-2, 4-5");
  7386. }
  7387. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7388. auto res =
  7389. cli_.Get("/streamed-with-range",
  7390. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7391. "92233720368547758079223372036854775807"}});
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7394. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7395. EXPECT_EQ(false, res->has_header("Content-Range"));
  7396. EXPECT_EQ(0U, res->body.size());
  7397. }
  7398. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7399. auto res = cli_.Get(
  7400. "/with-range",
  7401. Headers{{"Range",
  7402. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7403. {"Accept-Encoding", ""}});
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7406. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7407. EXPECT_EQ(true, res->has_header("Content-Range"));
  7408. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7409. EXPECT_EQ(std::string("abcdefg"), res->body);
  7410. }
  7411. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7412. auto res = cli_.Get("/with-range", Headers{
  7413. {"Range", "bytes=0-"},
  7414. {"Accept-Encoding", ""},
  7415. });
  7416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7418. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7419. EXPECT_EQ(true, res->has_header("Content-Range"));
  7420. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7421. EXPECT_EQ(std::string("abcdefg"), res->body);
  7422. }
  7423. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7424. auto res = cli_.Get("/streamed-with-range",
  7425. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7427. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7428. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7429. EXPECT_EQ(false, res->has_header("Content-Range"));
  7430. EXPECT_EQ(267U, res->body.size());
  7431. // Check that both range contents are present
  7432. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7433. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7434. // Check that Content-Range headers are present for both ranges
  7435. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7436. std::string::npos);
  7437. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7438. std::string::npos);
  7439. }
  7440. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7441. Ranges ranges;
  7442. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7443. ranges.emplace_back(0, -1);
  7444. }
  7445. auto res = cli_.Get("/streamed-with-range?error",
  7446. Headers{{make_range_header(ranges)}});
  7447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7448. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7449. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7450. EXPECT_EQ(false, res->has_header("Content-Range"));
  7451. EXPECT_EQ(0U, res->body.size());
  7452. }
  7453. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7454. auto res = cli_.Get("/streamed-with-range",
  7455. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7457. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7458. EXPECT_EQ(5U, res->body.size());
  7459. // Check that overlapping ranges are coalesced into a single range
  7460. EXPECT_EQ("bcdef", res->body);
  7461. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7462. // Should be single range, not multipart
  7463. EXPECT_TRUE(res->has_header("Content-Range"));
  7464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7465. }
  7466. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7467. auto res = cli_.Get("/streamed-with-range",
  7468. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7471. EXPECT_EQ(268U, res->body.size());
  7472. // Check that both range contents are present
  7473. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7474. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7475. // Check that Content-Range headers are present for both ranges
  7476. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7477. std::string::npos);
  7478. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7479. std::string::npos);
  7480. }
  7481. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7482. auto res = cli_.Get("/streamed-with-range",
  7483. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7485. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7486. EXPECT_EQ(269U, res->body.size());
  7487. // Check that both duplicate range contents are present
  7488. size_t first_abc = res->body.find("abc\r\n");
  7489. EXPECT_TRUE(first_abc != std::string::npos);
  7490. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7491. EXPECT_TRUE(second_abc != std::string::npos);
  7492. // Check that Content-Range headers are present for both ranges
  7493. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7494. EXPECT_TRUE(first_range != std::string::npos);
  7495. size_t second_range =
  7496. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7497. EXPECT_TRUE(second_range != std::string::npos);
  7498. }
  7499. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7500. auto res =
  7501. cli_.Get("/streamed-with-range?error",
  7502. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7505. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7506. EXPECT_EQ(false, res->has_header("Content-Range"));
  7507. EXPECT_EQ(0U, res->body.size());
  7508. }
  7509. TEST_F(ServerTest, GetStreamedEndless) {
  7510. uint64_t offset = 0;
  7511. auto res = cli_.Get("/streamed-cancel",
  7512. [&](const char * /*data*/, uint64_t data_length) {
  7513. if (offset < 100) {
  7514. offset += data_length;
  7515. return true;
  7516. }
  7517. return false;
  7518. });
  7519. ASSERT_TRUE(!res);
  7520. EXPECT_EQ(Error::Canceled, res.error());
  7521. }
  7522. TEST_F(ServerTest, ClientStop) {
  7523. std::atomic_size_t count{4};
  7524. std::vector<std::thread> threads;
  7525. for (auto i = count.load(); i != 0; --i) {
  7526. threads.emplace_back([&]() {
  7527. auto res = cli_.Get("/streamed-cancel",
  7528. [&](const char *, uint64_t) { return true; });
  7529. --count;
  7530. ASSERT_TRUE(!res);
  7531. EXPECT_TRUE(res.error() == Error::Canceled ||
  7532. res.error() == Error::Read || res.error() == Error::Write);
  7533. });
  7534. }
  7535. std::this_thread::sleep_for(std::chrono::seconds(2));
  7536. while (count != 0) {
  7537. cli_.stop();
  7538. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7539. }
  7540. for (auto &t : threads) {
  7541. t.join();
  7542. }
  7543. }
  7544. TEST_F(ServerTest, GetWithRange1) {
  7545. auto res = cli_.Get("/with-range", Headers{
  7546. make_range_header({{3, 5}}),
  7547. {"Accept-Encoding", ""},
  7548. });
  7549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7550. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7551. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7552. EXPECT_EQ(true, res->has_header("Content-Range"));
  7553. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7554. EXPECT_EQ(std::string("def"), res->body);
  7555. }
  7556. TEST_F(ServerTest, GetWithRange2) {
  7557. auto res = cli_.Get("/with-range", Headers{
  7558. make_range_header({{1, -1}}),
  7559. {"Accept-Encoding", ""},
  7560. });
  7561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7562. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7563. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7564. EXPECT_EQ(true, res->has_header("Content-Range"));
  7565. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7566. EXPECT_EQ(std::string("bcdefg"), res->body);
  7567. }
  7568. TEST_F(ServerTest, GetWithRange3) {
  7569. auto res = cli_.Get("/with-range", Headers{
  7570. make_range_header({{0, 0}}),
  7571. {"Accept-Encoding", ""},
  7572. });
  7573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7574. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7575. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7576. EXPECT_EQ(true, res->has_header("Content-Range"));
  7577. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7578. EXPECT_EQ(std::string("a"), res->body);
  7579. }
  7580. TEST_F(ServerTest, GetWithRange4) {
  7581. auto res = cli_.Get("/with-range", Headers{
  7582. make_range_header({{-1, 2}}),
  7583. {"Accept-Encoding", ""},
  7584. });
  7585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7587. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7588. EXPECT_EQ(true, res->has_header("Content-Range"));
  7589. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7590. EXPECT_EQ(std::string("fg"), res->body);
  7591. }
  7592. TEST_F(ServerTest, GetWithRange5) {
  7593. auto res = cli_.Get("/with-range", Headers{
  7594. make_range_header({{0, 5}}),
  7595. {"Accept-Encoding", ""},
  7596. });
  7597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7599. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7600. EXPECT_EQ(true, res->has_header("Content-Range"));
  7601. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7602. EXPECT_EQ(std::string("abcdef"), res->body);
  7603. }
  7604. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7605. auto res =
  7606. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7608. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7609. }
  7610. TEST_F(ServerTest, GetWithRangeMultipart) {
  7611. auto res =
  7612. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7614. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7615. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7616. EXPECT_EQ(false, res->has_header("Content-Range"));
  7617. EXPECT_EQ(267U, res->body.size());
  7618. }
  7619. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7620. auto res = cli_.Get("/with-range",
  7621. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7623. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7624. }
  7625. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7626. auto res = cli_.Get("/with-range-customized-response",
  7627. Headers{{make_range_header({{1, 2}})}});
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7630. EXPECT_EQ(true, res->has_header("Content-Length"));
  7631. EXPECT_EQ(false, res->has_header("Content-Range"));
  7632. EXPECT_EQ(JSON_DATA, res->body);
  7633. }
  7634. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7635. auto res = cli_.Get("/with-range-customized-response",
  7636. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7638. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7639. EXPECT_EQ(true, res->has_header("Content-Length"));
  7640. EXPECT_EQ(false, res->has_header("Content-Range"));
  7641. EXPECT_EQ(JSON_DATA, res->body);
  7642. }
  7643. TEST_F(ServerTest, Issue1772) {
  7644. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7646. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7647. }
  7648. TEST_F(ServerTest, Issue609) {
  7649. auto res = cli_.Delete("/issue609");
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ(StatusCode::OK_200, res->status);
  7652. EXPECT_EQ(std::string("ok"), res->body);
  7653. }
  7654. TEST_F(ServerTest, GetStreamedChunked) {
  7655. auto res = cli_.Get("/streamed-chunked");
  7656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7657. EXPECT_EQ(StatusCode::OK_200, res->status);
  7658. EXPECT_EQ(std::string("123456789"), res->body);
  7659. }
  7660. TEST_F(ServerTest, GetStreamedChunked2) {
  7661. auto res = cli_.Get("/streamed-chunked2");
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(StatusCode::OK_200, res->status);
  7664. EXPECT_EQ(std::string("123456789"), res->body);
  7665. }
  7666. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7667. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7669. EXPECT_EQ(StatusCode::OK_200, res->status);
  7670. EXPECT_EQ(std::string("123456789"), res->body);
  7671. EXPECT_TRUE(res->has_header("Trailer"));
  7672. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7673. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7674. // Trailers are now stored separately from headers (security fix)
  7675. EXPECT_EQ(2U, res->trailers.size());
  7676. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7677. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7678. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7679. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7680. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7681. // Verify trailers are NOT in headers (security verification)
  7682. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7683. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7684. }
  7685. TEST_F(ServerTest, LargeChunkedPost) {
  7686. Request req;
  7687. req.method = "POST";
  7688. req.path = "/large-chunked";
  7689. std::string host_and_port;
  7690. host_and_port += HOST;
  7691. host_and_port += ":";
  7692. host_and_port += std::to_string(PORT);
  7693. req.headers.emplace("Host", host_and_port.c_str());
  7694. req.headers.emplace("Accept", "*/*");
  7695. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7696. req.headers.emplace("Content-Type", "text/plain");
  7697. req.headers.emplace("Content-Length", "0");
  7698. req.headers.emplace("Transfer-Encoding", "chunked");
  7699. std::string long_string(30 * 1024u, 'a');
  7700. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7701. // Attempt to make a large enough post to exceed OS buffers, to test that
  7702. // the server handles short reads if the full chunk data isn't available.
  7703. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7704. auto res = std::make_shared<Response>();
  7705. auto error = Error::Success;
  7706. auto ret = cli_.send(req, *res, error);
  7707. ASSERT_TRUE(ret);
  7708. EXPECT_EQ(StatusCode::OK_200, res->status);
  7709. }
  7710. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7711. auto res = cli_.Get("/remote_addr");
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7715. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7716. }
  7717. TEST_F(ServerTest, GetMethodLocalAddr) {
  7718. auto res = cli_.Get("/local_addr");
  7719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7722. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7723. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7724. }
  7725. TEST_F(ServerTest, HTTPResponseSplitting) {
  7726. auto res = cli_.Get("/http_response_splitting");
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. }
  7730. TEST_F(ServerTest, SlowRequest) {
  7731. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7732. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7733. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7734. }
  7735. #if 0
  7736. TEST_F(ServerTest, SlowPost) {
  7737. char buffer[64 * 1024];
  7738. memset(buffer, 0x42, sizeof(buffer));
  7739. auto res = cli_.Post(
  7740. "/slowpost", 64 * 1024 * 1024,
  7741. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7742. auto ret = sink.write(buffer, sizeof(buffer));
  7743. EXPECT_TRUE(ret);
  7744. return true;
  7745. },
  7746. "text/plain");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST_F(ServerTest, SlowPostFail) {
  7751. char buffer[64 * 1024];
  7752. memset(buffer, 0x42, sizeof(buffer));
  7753. cli_.set_write_timeout(std::chrono::seconds(0));
  7754. auto res = cli_.Post(
  7755. "/slowpost", 64 * 1024 * 1024,
  7756. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7757. sink.write(buffer, sizeof(buffer));
  7758. return true;
  7759. },
  7760. "text/plain");
  7761. ASSERT_TRUE(!res);
  7762. EXPECT_EQ(Error::Write, res.error());
  7763. }
  7764. #endif
  7765. TEST_F(ServerTest, Put) {
  7766. auto res = cli_.Put("/put", "PUT", "text/plain");
  7767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7768. EXPECT_EQ(StatusCode::OK_200, res->status);
  7769. EXPECT_EQ("PUT", res->body);
  7770. }
  7771. TEST_F(ServerTest, PutWithContentProvider) {
  7772. auto res = cli_.Put(
  7773. "/put", 3,
  7774. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7775. sink.os << "PUT";
  7776. return true;
  7777. },
  7778. "text/plain");
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. EXPECT_EQ("PUT", res->body);
  7782. }
  7783. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7784. auto res = cli_.Post(
  7785. "/post", 42,
  7786. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7787. return false;
  7788. },
  7789. "text/plain");
  7790. ASSERT_TRUE(!res);
  7791. EXPECT_EQ(Error::Canceled, res.error());
  7792. }
  7793. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7794. auto res = cli_.Put(
  7795. "/put",
  7796. [](size_t /*offset*/, DataSink &sink) {
  7797. sink.os << "PUT";
  7798. sink.done();
  7799. return true;
  7800. },
  7801. "text/plain");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. EXPECT_EQ("PUT", res->body);
  7805. }
  7806. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7807. auto res = cli_.Post(
  7808. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7809. "text/plain");
  7810. ASSERT_TRUE(!res);
  7811. EXPECT_EQ(Error::Canceled, res.error());
  7812. }
  7813. TEST_F(ServerTest, PostLoopBack) {
  7814. std::string body;
  7815. auto res = cli_.Post(
  7816. "/post-loopback", 9,
  7817. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7818. EXPECT_EQ(9u, length);
  7819. sink.write("123", 3);
  7820. sink.write("456", 3);
  7821. sink.write("789", 3);
  7822. return true;
  7823. },
  7824. "text/plain",
  7825. [&body](const char *data, size_t data_length) {
  7826. body.append(data, data_length);
  7827. return true;
  7828. });
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::OK_200, res->status);
  7831. EXPECT_EQ("123456789", body);
  7832. }
  7833. TEST_F(ServerTest, PutLoopBack) {
  7834. std::string body;
  7835. auto res = cli_.Put(
  7836. "/put-loopback", 9,
  7837. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7838. EXPECT_EQ(9u, length);
  7839. sink.write("123", 3);
  7840. sink.write("456", 3);
  7841. sink.write("789", 3);
  7842. return true;
  7843. },
  7844. "text/plain",
  7845. [&body](const char *data, size_t data_length) {
  7846. body.append(data, data_length);
  7847. return true;
  7848. });
  7849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. EXPECT_EQ("123456789", body);
  7852. }
  7853. TEST_F(ServerTest, PatchLoopBack) {
  7854. std::string body;
  7855. auto res = cli_.Patch(
  7856. "/patch-loopback", 9,
  7857. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7858. EXPECT_EQ(9u, length);
  7859. sink.write("123", 3);
  7860. sink.write("456", 3);
  7861. sink.write("789", 3);
  7862. return true;
  7863. },
  7864. "text/plain",
  7865. [&body](const char *data, size_t data_length) {
  7866. body.append(data, data_length);
  7867. return true;
  7868. });
  7869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7870. EXPECT_EQ(StatusCode::OK_200, res->status);
  7871. EXPECT_EQ("123456789", body);
  7872. }
  7873. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7874. std::string body;
  7875. auto res = cli_.Post(
  7876. "/post-loopback",
  7877. [](size_t /*offset*/, DataSink &sink) {
  7878. sink.write("123", 3);
  7879. sink.write("456", 3);
  7880. sink.write("789", 3);
  7881. sink.done();
  7882. return true;
  7883. },
  7884. "text/plain",
  7885. [&body](const char *data, size_t data_length) {
  7886. body.append(data, data_length);
  7887. return true;
  7888. });
  7889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7890. EXPECT_EQ(StatusCode::OK_200, res->status);
  7891. EXPECT_EQ("123456789", body);
  7892. }
  7893. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7894. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7895. cli_.set_compress(true);
  7896. auto res = cli_.Put(
  7897. "/put", 3,
  7898. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7899. sink.os << "PUT";
  7900. return true;
  7901. },
  7902. "text/plain");
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ(StatusCode::OK_200, res->status);
  7905. EXPECT_EQ("PUT", res->body);
  7906. }
  7907. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7908. cli_.set_compress(true);
  7909. auto res = cli_.Post(
  7910. "/post", 42,
  7911. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7912. return false;
  7913. },
  7914. "text/plain");
  7915. ASSERT_TRUE(!res);
  7916. EXPECT_EQ(Error::Canceled, res.error());
  7917. }
  7918. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7919. cli_.set_compress(true);
  7920. auto res = cli_.Put(
  7921. "/put",
  7922. [](size_t /*offset*/, DataSink &sink) {
  7923. sink.os << "PUT";
  7924. sink.done();
  7925. return true;
  7926. },
  7927. "text/plain");
  7928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7929. EXPECT_EQ(StatusCode::OK_200, res->status);
  7930. EXPECT_EQ("PUT", res->body);
  7931. }
  7932. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7933. cli_.set_compress(true);
  7934. auto res = cli_.Post(
  7935. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7936. "text/plain");
  7937. ASSERT_TRUE(!res);
  7938. EXPECT_EQ(Error::Canceled, res.error());
  7939. }
  7940. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7941. cli_.set_compress(true);
  7942. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(StatusCode::OK_200, res->status);
  7945. EXPECT_EQ(LARGE_DATA, res->body);
  7946. }
  7947. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7948. #ifdef CPPHTTPLIB_SSL_ENABLED
  7949. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7950. Client cli(s.c_str());
  7951. cli.enable_server_certificate_verification(false);
  7952. #else
  7953. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7954. Client cli(s.c_str());
  7955. #endif
  7956. cli.set_compress(true);
  7957. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::OK_200, res->status);
  7960. EXPECT_EQ(LARGE_DATA, res->body);
  7961. // The compressed size should be less than a 10th of the original. May vary
  7962. // depending on the zlib library.
  7963. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7964. static_cast<uint64_t>(10 * 1024 * 1024));
  7965. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7966. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7967. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7968. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7969. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7970. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7971. #endif
  7972. }
  7973. TEST_F(ServerTest, PutContentWithDeflate) {
  7974. cli_.set_compress(false);
  7975. Headers headers;
  7976. headers.emplace("Content-Encoding", "deflate");
  7977. // PUT in deflate format:
  7978. auto res = cli_.Put("/put", headers,
  7979. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. EXPECT_EQ("PUT", res->body);
  7983. }
  7984. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7985. Headers headers;
  7986. headers.emplace("Accept-Encoding", "gzip, deflate");
  7987. auto res = cli_.Get("/streamed-chunked", headers);
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(StatusCode::OK_200, res->status);
  7990. EXPECT_EQ(std::string("123456789"), res->body);
  7991. }
  7992. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7993. Headers headers;
  7994. headers.emplace("Accept-Encoding", "gzip, deflate");
  7995. auto res = cli_.Get("/streamed-chunked2", headers);
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ(std::string("123456789"), res->body);
  7999. }
  8000. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8001. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. }
  8005. TEST(GzipDecompressor, ChunkedDecompression) {
  8006. std::string data;
  8007. for (size_t i = 0; i < 32 * 1024; ++i) {
  8008. data.push_back(static_cast<char>('a' + i % 26));
  8009. }
  8010. std::string compressed_data;
  8011. {
  8012. httplib::detail::gzip_compressor compressor;
  8013. bool result = compressor.compress(
  8014. data.data(), data.size(),
  8015. /*last=*/true,
  8016. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8017. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8018. compressed_data_size);
  8019. return true;
  8020. });
  8021. ASSERT_TRUE(result);
  8022. }
  8023. std::string decompressed_data;
  8024. {
  8025. httplib::detail::gzip_decompressor decompressor;
  8026. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8027. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8028. size_t chunk_size = 130;
  8029. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8030. chunk_begin += chunk_size) {
  8031. size_t current_chunk_size =
  8032. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8033. bool result = decompressor.decompress(
  8034. compressed_data.data() + chunk_begin, current_chunk_size,
  8035. [&](const char *decompressed_data_chunk,
  8036. size_t decompressed_data_chunk_size) {
  8037. decompressed_data.insert(decompressed_data.size(),
  8038. decompressed_data_chunk,
  8039. decompressed_data_chunk_size);
  8040. return true;
  8041. });
  8042. ASSERT_TRUE(result);
  8043. }
  8044. }
  8045. ASSERT_EQ(data, decompressed_data);
  8046. }
  8047. TEST(GzipDecompressor, DeflateDecompression) {
  8048. std::string original_text = "Raw deflate without gzip";
  8049. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8050. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8051. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8052. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8053. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8054. std::string decompressed_data;
  8055. {
  8056. httplib::detail::gzip_decompressor decompressor;
  8057. bool result = decompressor.decompress(
  8058. compressed_data.data(), compressed_data.size(),
  8059. [&](const char *decompressed_data_chunk,
  8060. size_t decompressed_data_chunk_size) {
  8061. decompressed_data.insert(decompressed_data.size(),
  8062. decompressed_data_chunk,
  8063. decompressed_data_chunk_size);
  8064. return true;
  8065. });
  8066. ASSERT_TRUE(result);
  8067. }
  8068. ASSERT_EQ(original_text, decompressed_data);
  8069. }
  8070. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8071. std::string original_text = "Raw deflate without gzip";
  8072. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8073. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8074. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8075. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8076. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8077. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8078. std::string decompressed_data;
  8079. {
  8080. httplib::detail::gzip_decompressor decompressor;
  8081. bool result = decompressor.decompress(
  8082. compressed_data.data(), compressed_data.size(),
  8083. [&](const char *decompressed_data_chunk,
  8084. size_t decompressed_data_chunk_size) {
  8085. decompressed_data.insert(decompressed_data.size(),
  8086. decompressed_data_chunk,
  8087. decompressed_data_chunk_size);
  8088. return true;
  8089. });
  8090. ASSERT_TRUE(result);
  8091. }
  8092. ASSERT_EQ(original_text, decompressed_data);
  8093. }
  8094. #endif
  8095. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8096. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8097. Headers headers;
  8098. headers.emplace("Accept-Encoding", "br");
  8099. auto res = cli_.Get("/streamed-chunked", headers);
  8100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8101. EXPECT_EQ(StatusCode::OK_200, res->status);
  8102. EXPECT_EQ(std::string("123456789"), res->body);
  8103. }
  8104. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8105. Headers headers;
  8106. headers.emplace("Accept-Encoding", "br");
  8107. auto res = cli_.Get("/streamed-chunked2", headers);
  8108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8109. EXPECT_EQ(StatusCode::OK_200, res->status);
  8110. EXPECT_EQ(std::string("123456789"), res->body);
  8111. }
  8112. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8113. cli_.set_compress(true);
  8114. auto res = cli_.Put(
  8115. "/put", 3,
  8116. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8117. sink.os << "PUT";
  8118. return true;
  8119. },
  8120. "text/plain");
  8121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8122. EXPECT_EQ(StatusCode::OK_200, res->status);
  8123. EXPECT_EQ("PUT", res->body);
  8124. }
  8125. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8126. cli_.set_compress(true);
  8127. auto res = cli_.Put(
  8128. "/put",
  8129. [](size_t /*offset*/, DataSink &sink) {
  8130. sink.os << "PUT";
  8131. sink.done();
  8132. return true;
  8133. },
  8134. "text/plain");
  8135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8136. EXPECT_EQ(StatusCode::OK_200, res->status);
  8137. EXPECT_EQ("PUT", res->body);
  8138. }
  8139. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8140. cli_.set_compress(true);
  8141. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8143. EXPECT_EQ(StatusCode::OK_200, res->status);
  8144. EXPECT_EQ(LARGE_DATA, res->body);
  8145. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8146. }
  8147. #endif
  8148. TEST_F(ServerTest, Patch) {
  8149. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. EXPECT_EQ("PATCH", res->body);
  8153. }
  8154. TEST_F(ServerTest, Delete) {
  8155. auto res = cli_.Delete("/delete");
  8156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8157. EXPECT_EQ(StatusCode::OK_200, res->status);
  8158. EXPECT_EQ("DELETE", res->body);
  8159. }
  8160. TEST_F(ServerTest, DeleteContentReceiver) {
  8161. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ(StatusCode::OK_200, res->status);
  8164. EXPECT_EQ("content", res->body);
  8165. }
  8166. TEST_F(ServerTest, Options) {
  8167. auto res = cli_.Options("*");
  8168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8171. EXPECT_TRUE(res->body.empty());
  8172. }
  8173. TEST_F(ServerTest, URL) {
  8174. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(StatusCode::OK_200, res->status);
  8177. }
  8178. TEST_F(ServerTest, ArrayParam) {
  8179. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::OK_200, res->status);
  8182. }
  8183. TEST_F(ServerTest, ArrayParamValues) {
  8184. auto res =
  8185. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8187. EXPECT_EQ(StatusCode::OK_200, res->status);
  8188. }
  8189. TEST_F(ServerTest, NoMultipleHeaders) {
  8190. Headers headers = {{"Content-Length", "5"}};
  8191. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8192. "text/plain");
  8193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8194. EXPECT_EQ(StatusCode::OK_200, res->status);
  8195. }
  8196. TEST_F(ServerTest, PostContentReceiver) {
  8197. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. ASSERT_EQ(StatusCode::OK_200, res->status);
  8200. ASSERT_EQ("content", res->body);
  8201. }
  8202. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8203. UploadFormDataItems items = {
  8204. {"text1", "text default", "", ""},
  8205. {"text2", "aωb", "", ""},
  8206. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8207. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8208. {"file3", "", "", "application/octet-stream"},
  8209. };
  8210. auto res = cli_.Post("/content_receiver", items);
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. }
  8214. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8215. UploadFormDataItems items = {
  8216. {"text1", "text default", "", ""},
  8217. {"text2", "aωb", "", ""},
  8218. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8219. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8220. {"file3", "", "", "application/octet-stream"},
  8221. };
  8222. auto boundary = std::string("+++++");
  8223. std::string body;
  8224. for (const auto &item : items) {
  8225. body += "--" + boundary + "\r\n";
  8226. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8227. if (!item.filename.empty()) {
  8228. body += "; filename=\"" + item.filename + "\"";
  8229. }
  8230. body += "\r\n";
  8231. if (!item.content_type.empty()) {
  8232. body += "Content-Type: " + item.content_type + "\r\n";
  8233. }
  8234. body += "\r\n";
  8235. body += item.content + "\r\n";
  8236. }
  8237. body += "--" + boundary + "--\r\n";
  8238. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8239. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8241. EXPECT_EQ(StatusCode::OK_200, res->status);
  8242. }
  8243. TEST(MultipartFormDataTest, FieldEscaping) {
  8244. Server svr;
  8245. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8246. const ContentReader &content_reader) {
  8247. ASSERT_TRUE(req.is_multipart_form_data());
  8248. std::vector<FormData> received;
  8249. content_reader(
  8250. [&](const FormData &file) {
  8251. received.push_back(file);
  8252. return true;
  8253. },
  8254. [&](const char *data, size_t data_length) {
  8255. received.back().content.append(data, data_length);
  8256. return true;
  8257. });
  8258. // '"', CR and LF in names and filenames are escaped following the
  8259. // WHATWG HTML standard, so each part still parses as a single part
  8260. // with no injected headers. Content types get CR/LF escaped too,
  8261. // while '"' (legal there, e.g. quoted charset) is preserved.
  8262. ASSERT_EQ(4U, received.size());
  8263. EXPECT_EQ("na%22me", received[0].name);
  8264. EXPECT_EQ("quoted name", received[0].content);
  8265. EXPECT_EQ("file", received[1].name);
  8266. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8267. received[1].filename);
  8268. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8269. EXPECT_EQ("injected", received[1].content);
  8270. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8271. EXPECT_EQ("my%22file.txt", received[2].filename);
  8272. EXPECT_EQ("cr lf name", received[2].content);
  8273. EXPECT_EQ("typed", received[3].name);
  8274. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8275. received[3].content_type);
  8276. EXPECT_EQ("typed content", received[3].content);
  8277. });
  8278. auto port = svr.bind_to_any_port("localhost");
  8279. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8280. auto se = detail::scope_exit([&] {
  8281. svr.stop();
  8282. t.join();
  8283. ASSERT_FALSE(svr.is_running());
  8284. });
  8285. svr.wait_until_ready();
  8286. Client cli("localhost", port);
  8287. UploadFormDataItems items = {
  8288. {"na\"me", "quoted name", "", ""},
  8289. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8290. "application/octet-stream"},
  8291. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8292. {"typed", "typed content", "",
  8293. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8294. };
  8295. auto res = cli.Post("/post", items);
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::OK_200, res->status);
  8298. }
  8299. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8300. const UploadFormDataItems items = {
  8301. {"name1", "Content 1", "", ""},
  8302. {"name2", "Content 2", "file2.txt", "text/plain"},
  8303. };
  8304. Server svr;
  8305. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8306. const ContentReader &content_reader) {
  8307. ASSERT_TRUE(req.is_multipart_form_data());
  8308. std::vector<FormData> received;
  8309. content_reader(
  8310. [&](const FormData &file) {
  8311. received.push_back(file);
  8312. return true;
  8313. },
  8314. [&](const char *data, size_t data_length) {
  8315. received.back().content.append(data, data_length);
  8316. return true;
  8317. });
  8318. ASSERT_EQ(2U, received.size());
  8319. EXPECT_EQ("name1", received[0].name);
  8320. EXPECT_EQ("Content 1", received[0].content);
  8321. EXPECT_EQ("name2", received[1].name);
  8322. EXPECT_EQ("Content 2", received[1].content);
  8323. EXPECT_EQ("file2.txt", received[1].filename);
  8324. EXPECT_EQ("text/plain", received[1].content_type);
  8325. });
  8326. auto port = svr.bind_to_any_port("localhost");
  8327. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8328. auto se = detail::scope_exit([&] {
  8329. svr.stop();
  8330. t.join();
  8331. ASSERT_FALSE(svr.is_running());
  8332. });
  8333. svr.wait_until_ready();
  8334. Client cli("localhost", port);
  8335. // Whole-body serialization with a generated boundary
  8336. {
  8337. MultipartFormDataWriter writer;
  8338. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8339. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8340. writer.content_type());
  8341. auto body = writer.serialize(items);
  8342. EXPECT_EQ(body.size(), writer.content_length(items));
  8343. auto res = cli.Post("/post", body, writer.content_type());
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::OK_200, res->status);
  8346. }
  8347. // Per-part framing with a custom boundary via a content provider
  8348. {
  8349. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8350. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8351. MultipartFormDataWriter writer("custom-boundary_123");
  8352. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8353. std::string body;
  8354. for (const auto &item : items) {
  8355. body += writer.item_begin(item);
  8356. body += item.content;
  8357. body += MultipartFormDataWriter::item_end();
  8358. }
  8359. body += writer.finish();
  8360. EXPECT_EQ(body.size(), writer.content_length(items));
  8361. auto res = cli.Post(
  8362. "/post", body.size(),
  8363. [&](size_t offset, size_t length, DataSink &sink) {
  8364. sink.write(body.data() + offset, length);
  8365. return true;
  8366. },
  8367. writer.content_type());
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. }
  8371. }
  8372. TEST_F(ServerTest, PostContentReceiverGzip) {
  8373. cli_.set_compress(true);
  8374. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8376. ASSERT_EQ(StatusCode::OK_200, res->status);
  8377. ASSERT_EQ("content", res->body);
  8378. }
  8379. TEST_F(ServerTest, PutContentReceiver) {
  8380. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8382. ASSERT_EQ(StatusCode::OK_200, res->status);
  8383. ASSERT_EQ("content", res->body);
  8384. }
  8385. TEST_F(ServerTest, PatchContentReceiver) {
  8386. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8388. ASSERT_EQ(StatusCode::OK_200, res->status);
  8389. ASSERT_EQ("content", res->body);
  8390. }
  8391. template <typename ClientType>
  8392. void TestWithHeadersAndContentReceiver(
  8393. ClientType &cli,
  8394. std::function<Result(ClientType &, const std::string &, const Headers &,
  8395. const std::string &, const std::string &,
  8396. ContentReceiver, DownloadProgress)>
  8397. request_func) {
  8398. Headers headers;
  8399. headers.emplace("X-Custom-Header", "test-value");
  8400. std::string received_body;
  8401. auto res = request_func(
  8402. cli, "/content_receiver", headers, "content", "application/json",
  8403. [&](const char *data, size_t data_length) {
  8404. received_body.append(data, data_length);
  8405. return true;
  8406. },
  8407. nullptr);
  8408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. EXPECT_EQ("content", received_body);
  8411. }
  8412. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8413. #ifdef CPPHTTPLIB_SSL_ENABLED
  8414. using ClientT = SSLClient;
  8415. #else
  8416. using ClientT = Client;
  8417. #endif
  8418. TestWithHeadersAndContentReceiver<ClientT>(
  8419. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8420. const std::string &body, const std::string &content_type,
  8421. ContentReceiver receiver, DownloadProgress progress) {
  8422. return cli.Post(path, headers, body, content_type, receiver, progress);
  8423. });
  8424. }
  8425. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8426. #ifdef CPPHTTPLIB_SSL_ENABLED
  8427. using ClientT = SSLClient;
  8428. #else
  8429. using ClientT = Client;
  8430. #endif
  8431. TestWithHeadersAndContentReceiver<ClientT>(
  8432. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8433. const std::string &body, const std::string &content_type,
  8434. ContentReceiver receiver, DownloadProgress progress) {
  8435. return cli.Put(path, headers, body, content_type, receiver, progress);
  8436. });
  8437. }
  8438. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8439. #ifdef CPPHTTPLIB_SSL_ENABLED
  8440. using ClientT = SSLClient;
  8441. #else
  8442. using ClientT = Client;
  8443. #endif
  8444. TestWithHeadersAndContentReceiver<ClientT>(
  8445. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8446. const std::string &body, const std::string &content_type,
  8447. ContentReceiver receiver, DownloadProgress progress) {
  8448. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8449. });
  8450. }
  8451. template <typename ClientType>
  8452. void TestWithHeadersAndContentReceiverWithProgress(
  8453. ClientType &cli,
  8454. std::function<Result(ClientType &, const std::string &, const Headers &,
  8455. const std::string &, const std::string &,
  8456. ContentReceiver, DownloadProgress)>
  8457. request_func) {
  8458. Headers headers;
  8459. headers.emplace("X-Test-Header", "progress-test");
  8460. std::string received_body;
  8461. auto progress_called = false;
  8462. auto res = request_func(
  8463. cli, "/content_receiver", headers, "content", "text/plain",
  8464. [&](const char *data, size_t data_length) {
  8465. received_body.append(data, data_length);
  8466. return true;
  8467. },
  8468. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8469. progress_called = true;
  8470. return true;
  8471. });
  8472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. EXPECT_EQ("content", received_body);
  8475. EXPECT_TRUE(progress_called);
  8476. }
  8477. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8478. #ifdef CPPHTTPLIB_SSL_ENABLED
  8479. using ClientT = SSLClient;
  8480. #else
  8481. using ClientT = Client;
  8482. #endif
  8483. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8484. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8485. const std::string &body, const std::string &content_type,
  8486. ContentReceiver receiver, DownloadProgress progress) {
  8487. return cli.Post(path, headers, body, content_type, receiver, progress);
  8488. });
  8489. }
  8490. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8491. #ifdef CPPHTTPLIB_SSL_ENABLED
  8492. using ClientT = SSLClient;
  8493. #else
  8494. using ClientT = Client;
  8495. #endif
  8496. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8497. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8498. const std::string &body, const std::string &content_type,
  8499. ContentReceiver receiver, DownloadProgress progress) {
  8500. return cli.Put(path, headers, body, content_type, receiver, progress);
  8501. });
  8502. }
  8503. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8504. #ifdef CPPHTTPLIB_SSL_ENABLED
  8505. using ClientT = SSLClient;
  8506. #else
  8507. using ClientT = Client;
  8508. #endif
  8509. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8510. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8511. const std::string &body, const std::string &content_type,
  8512. ContentReceiver receiver, DownloadProgress progress) {
  8513. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8514. });
  8515. }
  8516. template <typename ClientType>
  8517. void TestWithHeadersAndContentReceiverError(
  8518. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8519. const Headers &, const std::string &,
  8520. const std::string &, ContentReceiver)>
  8521. request_func) {
  8522. Headers headers;
  8523. headers.emplace("X-Error-Test", "true");
  8524. std::string received_body;
  8525. auto receiver_failed = false;
  8526. auto res =
  8527. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8528. [&](const char *data, size_t data_length) {
  8529. received_body.append(data, data_length);
  8530. receiver_failed = true;
  8531. return false;
  8532. });
  8533. ASSERT_FALSE(res);
  8534. EXPECT_TRUE(receiver_failed);
  8535. }
  8536. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8537. #ifdef CPPHTTPLIB_SSL_ENABLED
  8538. using ClientT = SSLClient;
  8539. #else
  8540. using ClientT = Client;
  8541. #endif
  8542. TestWithHeadersAndContentReceiverError<ClientT>(
  8543. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8544. const std::string &body, const std::string &content_type,
  8545. ContentReceiver receiver) {
  8546. return cli.Post(path, headers, body, content_type, receiver);
  8547. });
  8548. }
  8549. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8550. #ifdef CPPHTTPLIB_SSL_ENABLED
  8551. using ClientT = SSLClient;
  8552. #else
  8553. using ClientT = Client;
  8554. #endif
  8555. TestWithHeadersAndContentReceiverError<ClientT>(
  8556. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8557. const std::string &body, const std::string &content_type,
  8558. ContentReceiver receiver) {
  8559. return cli.Put(path, headers, body, content_type, receiver);
  8560. });
  8561. }
  8562. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8563. #ifdef CPPHTTPLIB_SSL_ENABLED
  8564. using ClientT = SSLClient;
  8565. #else
  8566. using ClientT = Client;
  8567. #endif
  8568. TestWithHeadersAndContentReceiverError<ClientT>(
  8569. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8570. const std::string &body, const std::string &content_type,
  8571. ContentReceiver receiver) {
  8572. return cli.Patch(path, headers, body, content_type, receiver);
  8573. });
  8574. }
  8575. TEST_F(ServerTest, PostQueryStringAndBody) {
  8576. auto res =
  8577. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8579. ASSERT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST_F(ServerTest, HTTP2Magic) {
  8582. Request req;
  8583. req.method = "PRI";
  8584. req.path = "*";
  8585. req.body = "SM";
  8586. auto res = std::make_shared<Response>();
  8587. auto error = Error::Success;
  8588. auto ret = cli_.send(req, *res, error);
  8589. ASSERT_TRUE(ret);
  8590. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8591. }
  8592. TEST_F(ServerTest, KeepAlive) {
  8593. auto res = cli_.Get("/hi");
  8594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8595. EXPECT_EQ(StatusCode::OK_200, res->status);
  8596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8597. EXPECT_EQ("Hello World!", res->body);
  8598. res = cli_.Get("/hi");
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::OK_200, res->status);
  8601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8602. EXPECT_EQ("Hello World!", res->body);
  8603. res = cli_.Get("/hi");
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(StatusCode::OK_200, res->status);
  8606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("Hello World!", res->body);
  8608. res = cli_.Get("/not-exist");
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8611. res = cli_.Post("/empty", "", "text/plain");
  8612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8613. EXPECT_EQ(StatusCode::OK_200, res->status);
  8614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8615. EXPECT_EQ("empty", res->body);
  8616. EXPECT_EQ("close", res->get_header_value("Connection"));
  8617. res = cli_.Post(
  8618. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8619. "text/plain");
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8623. EXPECT_EQ("empty", res->body);
  8624. cli_.set_keep_alive(false);
  8625. res = cli_.Get("/last-request");
  8626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8627. EXPECT_EQ(StatusCode::OK_200, res->status);
  8628. EXPECT_EQ("close", res->get_header_value("Connection"));
  8629. }
  8630. TEST_F(ServerTest, TooManyRedirect) {
  8631. cli_.set_follow_location(true);
  8632. auto res = cli_.Get("/redirect/0");
  8633. ASSERT_TRUE(!res);
  8634. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8635. }
  8636. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8637. Request req;
  8638. req.method = "FOOBAR";
  8639. req.path = "/hi";
  8640. cli_.set_keep_alive(true);
  8641. auto res = cli_.send(req);
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8644. EXPECT_EQ("close", res->get_header_value("Connection"));
  8645. EXPECT_FALSE(cli_.is_socket_open());
  8646. }
  8647. TEST_F(ServerTest, CustomRouteReadsBody) {
  8648. const std::string xml =
  8649. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8650. Request req;
  8651. req.method = "PROPFIND";
  8652. req.path = "/dav/dir";
  8653. req.set_header("Depth", "1");
  8654. req.body = xml;
  8655. auto res = cli_.send(req);
  8656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8657. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8658. EXPECT_EQ(xml, res->body);
  8659. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8660. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8661. }
  8662. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8663. Request req;
  8664. req.method = "PROPFIND";
  8665. req.path = "/dav/42";
  8666. auto res = cli_.send(req);
  8667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8668. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8669. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8670. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8671. }
  8672. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8673. Request req;
  8674. req.method = "PROPFIND";
  8675. req.path = "/dav-re/123";
  8676. auto res = cli_.send(req);
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8679. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8680. }
  8681. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8682. Request req;
  8683. req.method = "MKCOL";
  8684. req.path = "/dav-mkcol";
  8685. auto res = cli_.send(req);
  8686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8687. EXPECT_EQ(StatusCode::Created_201, res->status);
  8688. }
  8689. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8690. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8691. Request req;
  8692. req.method = "REPORT";
  8693. req.path = "/dav-report";
  8694. req.body = xml;
  8695. auto res = cli_.send(req);
  8696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8697. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8698. EXPECT_EQ(xml, res->body);
  8699. }
  8700. // A content reader route must fire even when the request carries no body,
  8701. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8702. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8703. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8704. Request req;
  8705. req.method = "REPORT";
  8706. req.path = "/dav-report";
  8707. auto res = cli_.send(req);
  8708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8709. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8710. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8711. }
  8712. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8713. Request req;
  8714. req.method = "PROPFIND";
  8715. req.path = "/not-dav";
  8716. auto res = cli_.send(req);
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8719. }
  8720. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8721. Request req;
  8722. req.method = "UNLOCK";
  8723. req.path = "/dav/dir";
  8724. cli_.set_keep_alive(true);
  8725. auto res = cli_.send(req);
  8726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8727. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8728. EXPECT_EQ("close", res->get_header_value("Connection"));
  8729. EXPECT_FALSE(cli_.is_socket_open());
  8730. }
  8731. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8732. // The mount point serves this path, but only for GET and HEAD.
  8733. auto get_res = cli_.Get("/dir/index.html");
  8734. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8735. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8736. Request req;
  8737. req.method = "PROPFIND";
  8738. req.path = "/dir/index.html";
  8739. auto res = cli_.send(req);
  8740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8741. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8742. }
  8743. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8744. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8745. cli_.set_keep_alive(true);
  8746. for (auto i = 0; i < 2; i++) {
  8747. Request req;
  8748. req.method = "PROPFIND";
  8749. req.path = "/dav/dir";
  8750. req.body = xml;
  8751. auto res = cli_.send(req);
  8752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8753. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8754. EXPECT_EQ(xml, res->body);
  8755. EXPECT_TRUE(cli_.is_socket_open());
  8756. }
  8757. // A built-in method must still be served on the same connection.
  8758. cli_.set_keep_alive(false);
  8759. auto res = cli_.Get("/hi");
  8760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8761. EXPECT_EQ(StatusCode::OK_200, res->status);
  8762. EXPECT_EQ("close", res->get_header_value("Connection"));
  8763. }
  8764. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8765. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8766. Request req;
  8767. req.method = "PROPFIND";
  8768. req.path = "/dav/dir";
  8769. req.set_header("Expect", "100-continue");
  8770. req.body = xml;
  8771. auto res = cli_.send(req);
  8772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8773. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8774. EXPECT_EQ(xml, res->body);
  8775. }
  8776. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8777. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8778. TEST_F(ServerTest, Gzip) {
  8779. Headers headers;
  8780. headers.emplace("Accept-Encoding", "gzip, deflate");
  8781. auto res = cli_.Get("/compress", headers);
  8782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8783. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8785. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8786. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8787. "7890123456789012345678901234567890",
  8788. res->body);
  8789. EXPECT_EQ(StatusCode::OK_200, res->status);
  8790. }
  8791. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8792. Headers headers;
  8793. headers.emplace("Accept-Encoding", "gzip, deflate");
  8794. auto res = cli_.Get("/compress-with-charset", headers);
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8797. EXPECT_EQ("application/json; charset=utf-8",
  8798. res->get_header_value("Content-Type"));
  8799. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8800. "7890123456789012345678901234567890",
  8801. res->body);
  8802. EXPECT_EQ(StatusCode::OK_200, res->status);
  8803. }
  8804. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8805. Headers headers;
  8806. headers.emplace("Accept-Encoding", "");
  8807. auto res = cli_.Get("/compress", headers);
  8808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8809. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8811. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8812. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8813. "7890123456789012345678901234567890",
  8814. res->body);
  8815. EXPECT_EQ(StatusCode::OK_200, res->status);
  8816. }
  8817. TEST_F(ServerTest, GzipWithContentReceiver) {
  8818. Headers headers;
  8819. headers.emplace("Accept-Encoding", "gzip, deflate");
  8820. std::string body;
  8821. auto res =
  8822. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8823. EXPECT_EQ(100U, data_length);
  8824. body.append(data, data_length);
  8825. return true;
  8826. });
  8827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8828. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8829. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8830. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8831. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8832. "7890123456789012345678901234567890",
  8833. body);
  8834. EXPECT_EQ(StatusCode::OK_200, res->status);
  8835. }
  8836. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8837. Headers headers;
  8838. headers.emplace("Accept-Encoding", "gzip, deflate");
  8839. cli_.set_decompress(false);
  8840. auto res = cli_.Get("/compress", headers);
  8841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8842. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8844. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8845. EXPECT_EQ(33U, res->body.size());
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8849. Headers headers;
  8850. headers.emplace("Accept-Encoding", "");
  8851. std::string body;
  8852. auto res =
  8853. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8854. EXPECT_EQ(100U, data_length);
  8855. body.append(data, data_length);
  8856. return true;
  8857. });
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8860. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8861. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8862. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8863. "7890123456789012345678901234567890",
  8864. body);
  8865. EXPECT_EQ(StatusCode::OK_200, res->status);
  8866. }
  8867. TEST_F(ServerTest, NoGzip) {
  8868. Headers headers;
  8869. headers.emplace("Accept-Encoding", "gzip, deflate");
  8870. auto res = cli_.Get("/nocompress", headers);
  8871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8872. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8873. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8874. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8875. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8876. "7890123456789012345678901234567890",
  8877. res->body);
  8878. EXPECT_EQ(StatusCode::OK_200, res->status);
  8879. }
  8880. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8881. Headers headers;
  8882. headers.emplace("Accept-Encoding", "gzip, deflate");
  8883. std::string body;
  8884. auto res = cli_.Get("/nocompress", headers,
  8885. [&](const char *data, size_t data_length) {
  8886. EXPECT_EQ(100U, data_length);
  8887. body.append(data, data_length);
  8888. return true;
  8889. });
  8890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8891. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8892. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8893. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8894. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8895. "7890123456789012345678901234567890",
  8896. body);
  8897. EXPECT_EQ(StatusCode::OK_200, res->status);
  8898. }
  8899. TEST_F(ServerTest, MultipartFormDataGzip) {
  8900. UploadFormDataItems items = {
  8901. {"key1", "test", "", ""},
  8902. {"key2", "--abcdefg123", "", ""},
  8903. };
  8904. cli_.set_compress(true);
  8905. auto res = cli_.Post("/compress-multipart", items);
  8906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8907. EXPECT_EQ(StatusCode::OK_200, res->status);
  8908. }
  8909. #endif
  8910. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8911. // Static file compression is opt-in, so these run their own server rather than
  8912. // flipping it on for the shared ServerTest fixture, which would silently
  8913. // rewrite what every other static file test is asserting.
  8914. class StaticFileCompressionTest : public ::testing::Test {
  8915. protected:
  8916. void TearDown() override {
  8917. if (t_.joinable()) {
  8918. svr_.stop();
  8919. t_.join();
  8920. }
  8921. }
  8922. int start(const std::function<void(Server &)> &configure = nullptr) {
  8923. // Serves the same tree as a directory of build-time compressed assets
  8924. // would be served: the mount point names the coding the files are already
  8925. // stored in. Registered before "/" so it is the one that matches.
  8926. svr_.set_mount_point("/pre-encoded", "./www",
  8927. {{"Content-Encoding", "gzip"}});
  8928. svr_.set_mount_point("/", "./www");
  8929. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8930. res.set_file_content("./www/dir/index.html", "text/html");
  8931. });
  8932. svr_.Get("/pre-encoded-file-content",
  8933. [](const Request & /*req*/, Response &res) {
  8934. res.set_header("Content-Encoding", "gzip");
  8935. res.set_file_content("./www/dir/index.html", "text/html");
  8936. });
  8937. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8938. res.set_content_provider(
  8939. 6, "text/plain",
  8940. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8941. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8942. return true;
  8943. });
  8944. });
  8945. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8946. res.set_content_provider(
  8947. 1000, "text/plain",
  8948. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8949. if (offset < 100) {
  8950. std::string data(100, 'A');
  8951. sink.write(data.data(), data.size());
  8952. return true;
  8953. }
  8954. std::this_thread::sleep_for(std::chrono::seconds(2));
  8955. std::string data(900, 'B');
  8956. sink.write(data.data(), data.size());
  8957. return true;
  8958. });
  8959. });
  8960. if (configure) { configure(svr_); }
  8961. auto port = svr_.bind_to_any_port(HOST);
  8962. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8963. svr_.wait_until_ready();
  8964. return port;
  8965. }
  8966. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8967. // Every file under ./www except 1MB.txt is smaller than the default
  8968. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8969. // it out of the way.
  8970. static void enable_without_floor(Server &svr) {
  8971. svr.set_static_file_compression(true);
  8972. svr.set_static_file_compression_min_length(0);
  8973. }
  8974. Server svr_;
  8975. std::thread t_;
  8976. };
  8977. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8978. auto port = start();
  8979. Client cli(HOST, port);
  8980. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8982. EXPECT_EQ(StatusCode::OK_200, res->status);
  8983. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8984. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8985. EXPECT_EQ(1048576U, res->body.size());
  8986. }
  8987. TEST_F(StaticFileCompressionTest, MountPoint) {
  8988. auto port = start(enable);
  8989. Client cli(HOST, port);
  8990. cli.set_decompress(false);
  8991. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8993. EXPECT_EQ(StatusCode::OK_200, res->status);
  8994. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8995. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8996. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8997. // The response stays self-delimiting: a length, not a chunked body.
  8998. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8999. EXPECT_EQ(std::to_string(res->body.size()),
  9000. res->get_header_value("Content-Length"));
  9001. EXPECT_LT(res->body.size(), 1048576U);
  9002. EXPECT_FALSE(res->body.empty());
  9003. }
  9004. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9005. auto port = start(enable);
  9006. Client cli(HOST, port);
  9007. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9009. EXPECT_EQ(StatusCode::OK_200, res->status);
  9010. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9011. EXPECT_EQ(1048576U, res->body.size());
  9012. }
  9013. TEST_F(StaticFileCompressionTest, FileContent) {
  9014. auto port = start(enable_without_floor);
  9015. Client cli(HOST, port);
  9016. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9018. EXPECT_EQ(StatusCode::OK_200, res->status);
  9019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9020. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9021. EXPECT_EQ(104U, res->body.size());
  9022. }
  9023. // A handler that serves an already-encoded file names the coding itself. The
  9024. // file-backed path decided its coding from Accept-Encoding and the content
  9025. // type alone, so it compressed the stored bytes a second time and appended a
  9026. // second Content-Encoding field line.
  9027. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9028. auto port = start(enable_without_floor);
  9029. Client cli(HOST, port);
  9030. cli.set_decompress(false);
  9031. auto res = cli.Get("/pre-encoded-file-content",
  9032. Headers{{"Accept-Encoding", "gzip"}});
  9033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9034. EXPECT_EQ(StatusCode::OK_200, res->status);
  9035. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9036. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9037. // Vary belongs to a coding the server chose, and it chose none here.
  9038. EXPECT_FALSE(res->has_header("Vary"));
  9039. // The file travels exactly as it is stored on disk.
  9040. EXPECT_EQ(104U, res->body.size());
  9041. }
  9042. // The 1MB file clears the default floor, so this one runs the configuration a
  9043. // deployment would actually have.
  9044. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9045. auto port = start(enable);
  9046. Client cli(HOST, port);
  9047. cli.set_decompress(false);
  9048. auto res =
  9049. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::OK_200, res->status);
  9052. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9053. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9054. EXPECT_FALSE(res->has_header("Vary"));
  9055. EXPECT_EQ(1048576U, res->body.size());
  9056. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9057. }
  9058. TEST_F(StaticFileCompressionTest, Head) {
  9059. auto port = start(enable);
  9060. Client cli(HOST, port);
  9061. cli.set_decompress(false);
  9062. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9063. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9064. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9066. EXPECT_EQ(StatusCode::OK_200, res->status);
  9067. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9068. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9069. // HEAD still reports the size a GET would return.
  9070. EXPECT_EQ(get->get_header_value("Content-Length"),
  9071. res->get_header_value("Content-Length"));
  9072. EXPECT_TRUE(res->body.empty());
  9073. }
  9074. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9075. auto port = start(enable);
  9076. Client cli(HOST, port);
  9077. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9078. {"Accept-Encoding", "gzip"}});
  9079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9080. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9081. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9082. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9083. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9084. EXPECT_EQ("cd", res->body);
  9085. }
  9086. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9087. auto port = start(enable);
  9088. Client cli(HOST, port);
  9089. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9091. EXPECT_EQ(StatusCode::OK_200, res->status);
  9092. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9093. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9094. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9095. }
  9096. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9097. auto port = start(enable);
  9098. Client cli(HOST, port);
  9099. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9101. EXPECT_EQ(StatusCode::OK_200, res->status);
  9102. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9103. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9104. EXPECT_TRUE(res->body.empty());
  9105. }
  9106. TEST_F(StaticFileCompressionTest, MinLength) {
  9107. auto port = start(enable);
  9108. Client cli(HOST, port);
  9109. // 104 bytes, well under the default floor. Compressing it would add the
  9110. // gzip header and trailer to a body that already fits in one packet.
  9111. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9113. EXPECT_EQ(StatusCode::OK_200, res->status);
  9114. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9115. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9116. }
  9117. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9118. auto port = start([](Server &svr) {
  9119. svr.set_static_file_compression(true);
  9120. svr.set_static_file_compression_min_length(1);
  9121. });
  9122. Client cli(HOST, port);
  9123. cli.set_decompress(false);
  9124. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9126. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9127. // A 9-byte file comes back larger than it went in, because gzip's header and
  9128. // trailer outweigh anything deflate can save. That is the end of the range
  9129. // the floor exists to keep out.
  9130. EXPECT_GT(res->body.size(), 9U);
  9131. }
  9132. TEST_F(StaticFileCompressionTest, MaxLength) {
  9133. auto port = start([](Server &svr) {
  9134. svr.set_static_file_compression(true);
  9135. svr.set_static_file_compression_min_length(0);
  9136. svr.set_static_file_compression_max_length(1024);
  9137. });
  9138. Client cli(HOST, port);
  9139. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9140. // defines `small` as a macro on Windows.
  9141. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9142. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9143. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9144. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9145. // Under it: compressed.
  9146. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9147. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9148. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9149. }
  9150. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9151. auto port = start(enable_without_floor);
  9152. Client cli(HOST, port);
  9153. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9154. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9155. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9156. auto identity_etag = identity->get_header_value("ETag");
  9157. ASSERT_FALSE(identity_etag.empty());
  9158. auto gzipped =
  9159. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9160. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9161. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9162. auto gzip_etag = gzipped->get_header_value("ETag");
  9163. ASSERT_FALSE(gzip_etag.empty());
  9164. // Two representations, two validators.
  9165. EXPECT_NE(identity_etag, gzip_etag);
  9166. // Each one revalidates against the request that would produce it...
  9167. auto fresh =
  9168. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9169. {"If-None-Match", gzip_etag}});
  9170. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9171. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9172. auto fresh_identity =
  9173. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9174. {"If-None-Match", identity_etag}});
  9175. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9176. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9177. // ...and not against the other representation.
  9178. auto crossed =
  9179. cli.Get("/dir/index.html",
  9180. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9181. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9182. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9183. }
  9184. // The opt-in covers responses the server reads off disk itself. A caller's own
  9185. // known-length provider keeps its Content-Length and, more importantly, keeps
  9186. // delivering incrementally: routing it through a compressor would hold every
  9187. // write back until zlib's window filled.
  9188. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9189. auto port = start(enable);
  9190. Client cli(HOST, port);
  9191. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9193. EXPECT_EQ(StatusCode::OK_200, res->status);
  9194. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9195. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9196. EXPECT_EQ("aaabbb", res->body);
  9197. }
  9198. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9199. auto port = start(enable);
  9200. Client cli(HOST, port);
  9201. cli.set_read_timeout(1, 0);
  9202. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9203. Headers{{"Accept-Encoding", "gzip"}});
  9204. ASSERT_TRUE(handle.is_valid());
  9205. // The provider writes 100 bytes and then stalls for longer than the read
  9206. // timeout. Those first bytes have to arrive anyway: run the response through
  9207. // a compressor and zlib holds them until its window fills, so the read would
  9208. // come back empty instead.
  9209. char buf[256];
  9210. auto n = handle.read(buf, sizeof(buf));
  9211. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9212. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9213. }
  9214. #endif
  9215. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9216. TEST_F(ServerTest, Brotli) {
  9217. Headers headers;
  9218. headers.emplace("Accept-Encoding", "br");
  9219. auto res = cli_.Get("/compress", headers);
  9220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9221. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9223. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9224. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9225. "7890123456789012345678901234567890",
  9226. res->body);
  9227. EXPECT_EQ(StatusCode::OK_200, res->status);
  9228. }
  9229. #endif
  9230. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9231. TEST_F(ServerTest, Zstd) {
  9232. Headers headers;
  9233. headers.emplace("Accept-Encoding", "zstd");
  9234. auto res = cli_.Get("/compress", headers);
  9235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9236. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9237. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9238. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9239. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9240. "7890123456789012345678901234567890",
  9241. res->body);
  9242. EXPECT_EQ(StatusCode::OK_200, res->status);
  9243. }
  9244. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9245. Headers headers;
  9246. headers.emplace("Accept-Encoding", "");
  9247. auto res = cli_.Get("/compress", headers);
  9248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9249. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9250. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9251. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9252. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9253. "7890123456789012345678901234567890",
  9254. res->body);
  9255. EXPECT_EQ(StatusCode::OK_200, res->status);
  9256. }
  9257. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9258. Headers headers;
  9259. headers.emplace("Accept-Encoding", "zstd");
  9260. std::string body;
  9261. auto res =
  9262. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9263. EXPECT_EQ(100U, data_length);
  9264. body.append(data, data_length);
  9265. return true;
  9266. });
  9267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9268. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9269. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9270. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9271. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9272. "7890123456789012345678901234567890",
  9273. body);
  9274. EXPECT_EQ(StatusCode::OK_200, res->status);
  9275. }
  9276. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9277. Headers headers;
  9278. headers.emplace("Accept-Encoding", "zstd");
  9279. cli_.set_decompress(false);
  9280. auto res = cli_.Get("/compress", headers);
  9281. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9282. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9283. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9284. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9286. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9287. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9288. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9289. EXPECT_EQ(StatusCode::OK_200, res->status);
  9290. ASSERT_EQ(26U, res->body.size());
  9291. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9292. 0);
  9293. }
  9294. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9295. Headers headers;
  9296. headers.emplace("Accept-Encoding", "");
  9297. std::string body;
  9298. auto res =
  9299. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9300. EXPECT_EQ(100U, data_length);
  9301. body.append(data, data_length);
  9302. return true;
  9303. });
  9304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9305. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9306. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9307. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9308. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9309. "7890123456789012345678901234567890",
  9310. body);
  9311. EXPECT_EQ(StatusCode::OK_200, res->status);
  9312. }
  9313. TEST_F(ServerTest, NoZstd) {
  9314. Headers headers;
  9315. headers.emplace("Accept-Encoding", "zstd");
  9316. auto res = cli_.Get("/nocompress", headers);
  9317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9318. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9319. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9320. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9321. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9322. "7890123456789012345678901234567890",
  9323. res->body);
  9324. EXPECT_EQ(StatusCode::OK_200, res->status);
  9325. }
  9326. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9327. Headers headers;
  9328. headers.emplace("Accept-Encoding", "zstd");
  9329. std::string body;
  9330. auto res = cli_.Get("/nocompress", headers,
  9331. [&](const char *data, size_t data_length) {
  9332. EXPECT_EQ(100U, data_length);
  9333. body.append(data, data_length);
  9334. return true;
  9335. });
  9336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9337. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9338. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9339. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9340. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9341. "7890123456789012345678901234567890",
  9342. body);
  9343. EXPECT_EQ(StatusCode::OK_200, res->status);
  9344. }
  9345. // TODO: How to enable zstd ??
  9346. TEST_F(ServerTest, MultipartFormDataZstd) {
  9347. UploadFormDataItems items = {
  9348. {"key1", "test", "", ""},
  9349. {"key2", "--abcdefg123", "", ""},
  9350. };
  9351. Headers headers;
  9352. headers.emplace("Accept-Encoding", "zstd");
  9353. cli_.set_compress(true);
  9354. auto res = cli_.Post("/compress-multipart", headers, items);
  9355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9356. EXPECT_EQ(StatusCode::OK_200, res->status);
  9357. }
  9358. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9359. Headers headers;
  9360. headers.emplace("Accept-Encoding", "zstd");
  9361. cli_.set_compress(true);
  9362. auto res = cli_.Put(
  9363. "/put", headers, 3,
  9364. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9365. sink.os << "PUT";
  9366. return true;
  9367. },
  9368. "text/plain");
  9369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9370. EXPECT_EQ(StatusCode::OK_200, res->status);
  9371. EXPECT_EQ("PUT", res->body);
  9372. }
  9373. // Pre-compression logging tests
  9374. TEST_F(ServerTest, PreCompressionLogging) {
  9375. // Test data for compression (matches the actual /compress endpoint content)
  9376. const std::string test_content =
  9377. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9378. "3456789012345678901234567890";
  9379. // Variables to capture logging data
  9380. std::string pre_compression_body;
  9381. std::string pre_compression_content_type;
  9382. std::string pre_compression_content_encoding;
  9383. std::string post_compression_body;
  9384. std::string post_compression_content_type;
  9385. std::string post_compression_content_encoding;
  9386. // Set up pre-compression logger
  9387. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9388. const Response &res) {
  9389. pre_compression_body = res.body;
  9390. pre_compression_content_type = res.get_header_value("Content-Type");
  9391. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9392. });
  9393. // Set up post-compression logger
  9394. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9395. post_compression_body = res.body;
  9396. post_compression_content_type = res.get_header_value("Content-Type");
  9397. post_compression_content_encoding =
  9398. res.get_header_value("Content-Encoding");
  9399. });
  9400. // Test with gzip compression
  9401. Headers headers;
  9402. headers.emplace("Accept-Encoding", "gzip");
  9403. auto res = cli_.Get("/compress", headers);
  9404. // Verify response was compressed
  9405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9406. EXPECT_EQ(StatusCode::OK_200, res->status);
  9407. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9408. // Verify pre-compression logger captured uncompressed content
  9409. EXPECT_EQ(test_content, pre_compression_body);
  9410. EXPECT_EQ("text/plain", pre_compression_content_type);
  9411. EXPECT_TRUE(pre_compression_content_encoding
  9412. .empty()); // No encoding header before compression
  9413. // Verify post-compression logger captured compressed content
  9414. EXPECT_NE(test_content,
  9415. post_compression_body); // Should be different after compression
  9416. EXPECT_EQ("text/plain", post_compression_content_type);
  9417. EXPECT_EQ("gzip", post_compression_content_encoding);
  9418. // Verify compressed content is smaller
  9419. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9420. }
  9421. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9422. const std::string test_content =
  9423. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9424. "3456789012345678901234567890";
  9425. std::string pre_compression_body;
  9426. std::string post_compression_body;
  9427. svr_.set_pre_compression_logger(
  9428. [&](const Request & /*req*/, const Response &res) {
  9429. pre_compression_body = res.body;
  9430. });
  9431. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9432. post_compression_body = res.body;
  9433. });
  9434. Headers headers;
  9435. headers.emplace("Accept-Encoding", "br");
  9436. auto res = cli_.Get("/compress", headers);
  9437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9438. EXPECT_EQ(StatusCode::OK_200, res->status);
  9439. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9440. // Verify pre-compression content is uncompressed
  9441. EXPECT_EQ(test_content, pre_compression_body);
  9442. // Verify post-compression content is compressed
  9443. EXPECT_NE(test_content, post_compression_body);
  9444. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9445. }
  9446. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9447. const std::string test_content =
  9448. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9449. "3456789012345678901234567890";
  9450. std::string pre_compression_body;
  9451. std::string post_compression_body;
  9452. svr_.set_pre_compression_logger(
  9453. [&](const Request & /*req*/, const Response &res) {
  9454. pre_compression_body = res.body;
  9455. });
  9456. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9457. post_compression_body = res.body;
  9458. });
  9459. // Request without compression (use /nocompress endpoint)
  9460. Headers headers;
  9461. auto res = cli_.Get("/nocompress", headers);
  9462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9463. EXPECT_EQ(StatusCode::OK_200, res->status);
  9464. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9465. // Pre-compression logger should not be called when no compression is applied
  9466. EXPECT_TRUE(
  9467. pre_compression_body.empty()); // Pre-compression logger not called
  9468. EXPECT_EQ(
  9469. test_content,
  9470. post_compression_body); // Post-compression logger captures final content
  9471. }
  9472. TEST_F(ServerTest, LoggerSeesContentLength) {
  9473. size_t logged_content_length = 0;
  9474. std::string logged_content_length_header;
  9475. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9476. logged_content_length = res.content_length_;
  9477. logged_content_length_header = res.get_header_value("Content-Length");
  9478. });
  9479. auto res = cli_.Get("/nocompress");
  9480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9481. EXPECT_EQ(StatusCode::OK_200, res->status);
  9482. EXPECT_EQ(res->body.size(), logged_content_length);
  9483. EXPECT_EQ(std::to_string(logged_content_length),
  9484. logged_content_length_header);
  9485. }
  9486. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9487. const std::string test_content =
  9488. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9489. "3456789012345678901234567890";
  9490. std::string pre_compression_body;
  9491. bool pre_logger_called = false;
  9492. // Set only pre-compression logger
  9493. svr_.set_pre_compression_logger(
  9494. [&](const Request & /*req*/, const Response &res) {
  9495. pre_compression_body = res.body;
  9496. pre_logger_called = true;
  9497. });
  9498. Headers headers;
  9499. headers.emplace("Accept-Encoding", "gzip");
  9500. auto res = cli_.Get("/compress", headers);
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9504. // Verify pre-compression logger was called
  9505. EXPECT_TRUE(pre_logger_called);
  9506. EXPECT_EQ(test_content, pre_compression_body);
  9507. }
  9508. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9509. {
  9510. // Test with Expect: 100-continue header - success case
  9511. // Server returns 100 Continue, client sends body, server returns 200 OK
  9512. Request req;
  9513. req.method = "POST";
  9514. req.path = "/post-large";
  9515. req.set_header("Expect", "100-continue");
  9516. req.body = LARGE_DATA;
  9517. Response res;
  9518. auto error = Error::Success;
  9519. cli_.set_keep_alive(true);
  9520. auto ret = cli_.send(req, res, error);
  9521. EXPECT_TRUE(ret);
  9522. EXPECT_EQ(StatusCode::OK_200, res.status);
  9523. EXPECT_EQ(LARGE_DATA, res.body);
  9524. }
  9525. {
  9526. // Test with Expect: 100-continue header - error case
  9527. // Client should not send the body when server returns an error
  9528. Request req;
  9529. req.method = "POST";
  9530. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9531. req.set_header("Expect", "100-continue");
  9532. req.body = LARGE_DATA;
  9533. Response res;
  9534. auto error = Error::Success;
  9535. auto start = std::chrono::high_resolution_clock::now();
  9536. cli_.set_keep_alive(true);
  9537. auto ret = cli_.send(req, res, error);
  9538. auto end = std::chrono::high_resolution_clock::now();
  9539. auto elapsed =
  9540. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9541. .count();
  9542. // With Expect: 100-continue, request completes successfully but with error
  9543. EXPECT_TRUE(ret);
  9544. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9545. EXPECT_EQ("close", res.get_header_value("Connection"));
  9546. EXPECT_FALSE(cli_.is_socket_open());
  9547. EXPECT_LE(elapsed, 2000);
  9548. }
  9549. {
  9550. // Send an extra GET request to ensure error recovery without hanging
  9551. Request req;
  9552. req.method = "GET";
  9553. req.path = "/hi";
  9554. auto start = std::chrono::high_resolution_clock::now();
  9555. auto res = cli_.send(req);
  9556. auto end = std::chrono::high_resolution_clock::now();
  9557. auto elapsed =
  9558. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9559. .count();
  9560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9561. EXPECT_EQ(StatusCode::OK_200, res->status);
  9562. EXPECT_EQ("Hello World!", res->body);
  9563. EXPECT_LE(elapsed, 500);
  9564. }
  9565. }
  9566. TEST(ZstdDecompressor, ChunkedDecompression) {
  9567. std::string data;
  9568. for (size_t i = 0; i < 32 * 1024; ++i) {
  9569. data.push_back(static_cast<char>('a' + i % 26));
  9570. }
  9571. std::string compressed_data;
  9572. {
  9573. httplib::detail::zstd_compressor compressor;
  9574. bool result = compressor.compress(
  9575. data.data(), data.size(),
  9576. /*last=*/true,
  9577. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9578. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9579. compressed_data_size);
  9580. return true;
  9581. });
  9582. ASSERT_TRUE(result);
  9583. }
  9584. std::string decompressed_data;
  9585. {
  9586. httplib::detail::zstd_decompressor decompressor;
  9587. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9588. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9589. size_t chunk_size = 130;
  9590. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9591. chunk_begin += chunk_size) {
  9592. size_t current_chunk_size =
  9593. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9594. bool result = decompressor.decompress(
  9595. compressed_data.data() + chunk_begin, current_chunk_size,
  9596. [&](const char *decompressed_data_chunk,
  9597. size_t decompressed_data_chunk_size) {
  9598. decompressed_data.insert(decompressed_data.size(),
  9599. decompressed_data_chunk,
  9600. decompressed_data_chunk_size);
  9601. return true;
  9602. });
  9603. ASSERT_TRUE(result);
  9604. }
  9605. }
  9606. ASSERT_EQ(data, decompressed_data);
  9607. }
  9608. TEST(ZstdDecompressor, Decompress) {
  9609. std::string original_text = "Compressed with ZSTD";
  9610. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9611. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9612. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9613. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9614. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9615. std::string decompressed_data;
  9616. {
  9617. httplib::detail::zstd_decompressor decompressor;
  9618. bool result = decompressor.decompress(
  9619. compressed_data.data(), compressed_data.size(),
  9620. [&](const char *decompressed_data_chunk,
  9621. size_t decompressed_data_chunk_size) {
  9622. decompressed_data.insert(decompressed_data.size(),
  9623. decompressed_data_chunk,
  9624. decompressed_data_chunk_size);
  9625. return true;
  9626. });
  9627. ASSERT_TRUE(result);
  9628. }
  9629. ASSERT_EQ(original_text, decompressed_data);
  9630. }
  9631. #endif
  9632. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9633. // separate chunks so that the server sees each part in its own read(). Used to
  9634. // place a read boundary at a specific offset of a request body.
  9635. static bool send_request_in_parts(time_t read_timeout_sec,
  9636. const std::vector<std::string> &parts,
  9637. std::string *resp = nullptr,
  9638. int port = PORT) {
  9639. auto error = Error::Success;
  9640. auto client_sock = detail::create_client_socket(
  9641. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9642. /*connection_timeout_sec=*/5, 0,
  9643. /*read_timeout_sec=*/5, 0,
  9644. /*write_timeout_sec=*/5, 0, std::string(), error);
  9645. if (client_sock == INVALID_SOCKET) { return false; }
  9646. auto ret = detail::process_client_socket(
  9647. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9648. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9649. for (size_t i = 0; i < parts.size(); i++) {
  9650. const auto &part = parts[i];
  9651. if (part.size() !=
  9652. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9653. return false;
  9654. }
  9655. if (i + 1 < parts.size()) {
  9656. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9657. }
  9658. }
  9659. char buf[512];
  9660. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9661. while (line_reader.getline()) {
  9662. if (resp) { *resp += line_reader.ptr(); }
  9663. }
  9664. return true;
  9665. });
  9666. detail::close_socket(client_sock);
  9667. return ret;
  9668. }
  9669. // Sends a raw request to a server listening at HOST:PORT.
  9670. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9671. std::string *resp = nullptr, int port = PORT) {
  9672. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9673. }
  9674. #ifdef CPPHTTPLIB_SSL_ENABLED
  9675. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9677. ASSERT_TRUE(svr.is_valid());
  9678. svr.set_read_timeout(1, 0);
  9679. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9680. auto se = detail::scope_exit([&] {
  9681. svr.stop();
  9682. t.join();
  9683. ASSERT_FALSE(svr.is_running());
  9684. });
  9685. svr.wait_until_ready();
  9686. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9687. // keeps each wait well within the read timeout. The server gives up a
  9688. // second in, so the bytes sent after that fail.
  9689. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9690. parts.resize(26, std::string(1, '\0'));
  9691. EXPECT_FALSE(send_request_in_parts(5, parts));
  9692. }
  9693. #endif
  9694. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9695. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9696. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9697. const std::vector<std::string> &parts,
  9698. std::string *resp = nullptr,
  9699. int port = PORT) {
  9700. auto error = Error::Success;
  9701. auto sock = detail::create_client_socket(
  9702. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9703. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9704. /*write_timeout_sec=*/5, 0, std::string(), error);
  9705. if (sock == INVALID_SOCKET) { return false; }
  9706. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9707. auto ctx = SSL_CTX_new(TLS_client_method());
  9708. auto ssl = SSL_new(ctx);
  9709. auto ssl_se = detail::scope_exit([&] {
  9710. SSL_free(ssl);
  9711. SSL_CTX_free(ctx);
  9712. });
  9713. SSL_set_fd(ssl, static_cast<int>(sock));
  9714. if (SSL_connect(ssl) != 1) { return false; }
  9715. for (size_t i = 0; i < parts.size(); i++) {
  9716. const auto &part = parts[i];
  9717. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9718. static_cast<int>(part.size())) {
  9719. return false;
  9720. }
  9721. if (i + 1 < parts.size()) {
  9722. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9723. }
  9724. }
  9725. char buf[512];
  9726. int n;
  9727. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9728. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9729. }
  9730. return true;
  9731. }
  9732. #endif
  9733. // The request line, then a header value a byte at a time.
  9734. static std::vector<std::string> slow_request_head_parts() {
  9735. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9736. parts.resize(26, "a");
  9737. parts.emplace_back("\r\n\r\n");
  9738. return parts;
  9739. }
  9740. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9741. // within the one-second read timeout. The server gives up a second in, before
  9742. // the head is complete.
  9743. static void
  9744. expect_slow_request_head_dropped(Server &svr,
  9745. const std::function<std::string()> &send) {
  9746. std::atomic<bool> handled(false);
  9747. svr.Get("/", [&](const Request &, Response &res) {
  9748. handled = true;
  9749. res.set_content("ok", "text/plain");
  9750. });
  9751. svr.set_read_timeout(1, 0);
  9752. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9753. auto se = detail::scope_exit([&] {
  9754. svr.stop();
  9755. t.join();
  9756. ASSERT_FALSE(svr.is_running());
  9757. });
  9758. svr.wait_until_ready();
  9759. auto resp = send();
  9760. EXPECT_FALSE(handled);
  9761. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9762. }
  9763. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9764. Server svr;
  9765. expect_slow_request_head_dropped(svr, [] {
  9766. std::string resp;
  9767. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9768. return resp;
  9769. });
  9770. }
  9771. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9772. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9774. ASSERT_TRUE(svr.is_valid());
  9775. expect_slow_request_head_dropped(svr, [] {
  9776. std::string resp;
  9777. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9778. return resp;
  9779. });
  9780. }
  9781. #endif
  9782. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9783. Server svr;
  9784. std::string header_value;
  9785. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9786. header_value = req.get_header_value("foo");
  9787. res.set_content("ok", "text/plain");
  9788. });
  9789. thread t = thread([&] { svr.listen(HOST, PORT); });
  9790. auto se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. t.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. });
  9795. svr.wait_until_ready();
  9796. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9797. // like characters are not treated the same - use vertical tab and escape.
  9798. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9799. "foo: \t \v bar \x1B\t \r\n"
  9800. "Connection: close\r\n"
  9801. "\r\n";
  9802. std::string res;
  9803. ASSERT_TRUE(send_request(5, req, &res));
  9804. EXPECT_EQ(header_value, "");
  9805. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9806. }
  9807. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9808. Server svr;
  9809. std::string received;
  9810. svr.Get("/order", [&](const Request &req, Response &res) {
  9811. received = entries_to_string(req.headers);
  9812. res.set_content("ok", "text/plain");
  9813. });
  9814. auto port = svr.bind_to_any_port(HOST);
  9815. thread t = thread([&] { svr.listen_after_bind(); });
  9816. auto se = detail::scope_exit([&] {
  9817. svr.stop();
  9818. t.join();
  9819. ASSERT_FALSE(svr.is_running());
  9820. });
  9821. svr.wait_until_ready();
  9822. const std::string req = "GET /order HTTP/1.1\r\n"
  9823. "Host: localhost\r\n"
  9824. "X-First: 1\r\n"
  9825. "X-Dup: a\r\n"
  9826. "X-Second: 2\r\n"
  9827. "X-Dup: b\r\n"
  9828. "Connection: close\r\n"
  9829. "\r\n";
  9830. std::string res;
  9831. ASSERT_TRUE(send_request(5, req, &res, port));
  9832. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9833. EXPECT_EQ(
  9834. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9835. received);
  9836. }
  9837. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9838. Server svr;
  9839. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9840. res.set_header("Set-Cookie", "first=1");
  9841. res.set_header("X-Between", "y");
  9842. res.set_header("Set-Cookie", "second=2");
  9843. res.set_content("ok", "text/plain");
  9844. });
  9845. auto port = svr.bind_to_any_port(HOST);
  9846. thread t = thread([&] { svr.listen_after_bind(); });
  9847. auto se = detail::scope_exit([&] {
  9848. svr.stop();
  9849. t.join();
  9850. ASSERT_FALSE(svr.is_running());
  9851. });
  9852. svr.wait_until_ready();
  9853. Client cli(HOST, port);
  9854. auto res = cli.Get("/cookies");
  9855. ASSERT_TRUE(res);
  9856. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9857. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9858. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9859. }
  9860. // A stream may send a byte at a time with a small extension on each chunk,
  9861. // however long it runs
  9862. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9863. Server svr;
  9864. svr.Post("/count", [](const Request &req, Response &res) {
  9865. res.set_content(std::to_string(req.body.size()), "text/plain");
  9866. });
  9867. auto port = svr.bind_to_any_port(HOST);
  9868. ASSERT_LT(0, port);
  9869. thread t = thread([&] { svr.listen_after_bind(); });
  9870. auto se = detail::scope_exit([&] {
  9871. svr.stop();
  9872. t.join();
  9873. ASSERT_FALSE(svr.is_running());
  9874. });
  9875. svr.wait_until_ready();
  9876. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9877. "\r\nTransfer-Encoding: chunked\r\n"
  9878. "Connection: close\r\n\r\n";
  9879. for (auto i = 0; i < 4096; i++) {
  9880. req += "1;a=b\r\nx\r\n";
  9881. }
  9882. req += "0\r\n\r\n";
  9883. std::string res;
  9884. ASSERT_TRUE(send_request(5, req, &res, port));
  9885. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9886. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9887. }
  9888. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9889. Server svr;
  9890. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9891. auto i = new int(0);
  9892. res.set_header("Trailer", "X-Safe, X-Reflected");
  9893. res.set_chunked_content_provider(
  9894. "text/plain",
  9895. [i](size_t /*offset*/, DataSink &sink) {
  9896. if (*i == 0) {
  9897. sink.os << "body";
  9898. } else {
  9899. Headers trailer;
  9900. // A valid trailer that must survive.
  9901. trailer.emplace("X-Safe", "safe");
  9902. // Attacker-controlled value carrying CR/LF (response splitting).
  9903. trailer.emplace("X-Reflected",
  9904. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9905. // Attacker-controlled name carrying CR/LF.
  9906. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9907. sink.done_with_trailer(trailer);
  9908. }
  9909. (*i)++;
  9910. return true;
  9911. },
  9912. [i](bool /*success*/) { delete i; });
  9913. });
  9914. thread t = thread([&] { svr.listen(HOST, PORT); });
  9915. auto se = detail::scope_exit([&] {
  9916. svr.stop();
  9917. t.join();
  9918. ASSERT_FALSE(svr.is_running());
  9919. });
  9920. svr.wait_until_ready();
  9921. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9922. "Host: " + HOST +
  9923. "\r\n"
  9924. "Connection: close\r\n"
  9925. "\r\n";
  9926. std::string res;
  9927. ASSERT_TRUE(send_request(5, req, &res));
  9928. // The injected fields must not appear anywhere in the raw response.
  9929. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9930. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9931. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9932. // Invalid trailers are dropped entirely, matching set_header().
  9933. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9934. // The valid trailer still passes through.
  9935. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9936. }
  9937. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9938. // A custom header writer gets only the fields the default one writes
  9939. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9940. std::string s;
  9941. for (const auto &h : hdrs) {
  9942. s += h.first + ": " + h.second + "\r\n";
  9943. }
  9944. s += "\r\n";
  9945. return strm.write(s.data(), s.size());
  9946. };
  9947. for (auto custom_writer : {false, true}) {
  9948. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9949. Server svr;
  9950. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9951. svr.set_post_routing_handler([](const Request &, Response &res) {
  9952. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9953. });
  9954. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9955. // res.headers is a public field an application can populate directly,
  9956. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9957. // A valid header that must survive.
  9958. res.headers.emplace("X-Safe", "safe");
  9959. // Attacker-controlled value carrying CR/LF (response splitting).
  9960. res.headers.emplace("X-Reflected",
  9961. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9962. // Attacker-controlled name carrying CR/LF.
  9963. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9964. res.set_content("body", "text/plain");
  9965. });
  9966. thread t = thread([&] { svr.listen(HOST, PORT); });
  9967. auto se = detail::scope_exit([&] {
  9968. svr.stop();
  9969. t.join();
  9970. ASSERT_FALSE(svr.is_running());
  9971. });
  9972. svr.wait_until_ready();
  9973. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9974. "Host: " + HOST +
  9975. "\r\n"
  9976. "Connection: close\r\n"
  9977. "\r\n";
  9978. std::string res;
  9979. ASSERT_TRUE(send_request(5, req, &res));
  9980. // The injected fields must not appear anywhere in the raw response.
  9981. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9982. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9983. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9984. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9985. // Invalid headers are dropped entirely, matching set_header().
  9986. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9987. // The valid header still passes through.
  9988. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9989. }
  9990. }
  9991. // Forward declaration: in split builds split.py strips `inline` and moves the
  9992. // definition into httplib.cc, so detail::write_request_line is not visible from
  9993. // the public httplib.h. Re-declaring it here lets the tests link against the
  9994. // symbol in both header-only and split builds.
  9995. namespace httplib {
  9996. namespace detail {
  9997. ssize_t write_request_line(Stream &strm, const std::string &method,
  9998. const std::string &path);
  9999. } // namespace detail
  10000. } // namespace httplib
  10001. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10002. // A well-formed target is written verbatim.
  10003. {
  10004. detail::BufferStream strm;
  10005. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10006. EXPECT_GT(n, 0);
  10007. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10008. }
  10009. // A target carrying CR/LF, SP or other control octets must be rejected
  10010. // before anything reaches the wire, otherwise it splits the request line and
  10011. // injects a header or a whole request.
  10012. const std::string evil_targets[] = {
  10013. "/a\r\nInjected: pwned",
  10014. "/a\rInjected",
  10015. "/a\nInjected",
  10016. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10017. "/a b",
  10018. "/a\tb",
  10019. "/a\x7f",
  10020. };
  10021. for (const auto &evil : evil_targets) {
  10022. detail::BufferStream strm;
  10023. auto n = detail::write_request_line(strm, "GET", evil);
  10024. EXPECT_LT(n, 0);
  10025. EXPECT_TRUE(strm.get_buffer().empty());
  10026. }
  10027. }
  10028. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10029. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10030. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10031. // target reaches write_request. The client must fail cleanly with
  10032. // Error::Write instead of putting a request-line-less, header-injecting
  10033. // request on the wire.
  10034. Server svr;
  10035. svr.Get("/a", [](const Request &, Response &res) {
  10036. res.set_content("ok", "text/plain");
  10037. });
  10038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10039. auto se = detail::scope_exit([&] {
  10040. svr.stop();
  10041. thread.join();
  10042. ASSERT_FALSE(svr.is_running());
  10043. });
  10044. svr.wait_until_ready();
  10045. {
  10046. Client cli(HOST, PORT);
  10047. cli.set_path_encode(false);
  10048. // The request is rejected before anything is written, so the connection
  10049. // stays silent and the subsequent response read would otherwise block for
  10050. // the full default read timeout. Shorten it -- the assertion is on the
  10051. // error, not the timeout.
  10052. cli.set_read_timeout(1, 0);
  10053. auto res = cli.Get("/a\r\nInjected: pwned");
  10054. EXPECT_FALSE(res);
  10055. EXPECT_EQ(Error::Write, res.error());
  10056. }
  10057. }
  10058. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10059. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10060. // including extension methods.
  10061. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10062. for (const auto &method : good_methods) {
  10063. detail::BufferStream strm;
  10064. auto n = detail::write_request_line(strm, method, "/");
  10065. EXPECT_GT(n, 0);
  10066. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10067. }
  10068. // A method carrying CR/LF would split the request line and smuggle a whole
  10069. // request ahead of the real one. A space or an empty method corrupts the
  10070. // request line. All must be rejected before anything reaches the wire.
  10071. const std::string evil_methods[] = {
  10072. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10073. "GET\r\nInjected: pwned",
  10074. "GET\r",
  10075. "GET\n",
  10076. "GE T",
  10077. "",
  10078. };
  10079. for (const auto &evil : evil_methods) {
  10080. detail::BufferStream strm;
  10081. auto n = detail::write_request_line(strm, evil, "/");
  10082. EXPECT_LT(n, 0);
  10083. EXPECT_TRUE(strm.get_buffer().empty());
  10084. }
  10085. }
  10086. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10087. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10088. // through Client::send must fail with Error::Write and no request, neither
  10089. // the smuggled one nor the real one, may reach the server.
  10090. Server svr;
  10091. std::atomic<int> request_count(0);
  10092. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10093. request_count++;
  10094. res.status = StatusCode::OK_200;
  10095. return Server::HandlerResponse::Handled;
  10096. });
  10097. auto port = svr.bind_to_any_port(HOST);
  10098. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10099. auto se = detail::scope_exit([&] {
  10100. svr.stop();
  10101. thread.join();
  10102. ASSERT_FALSE(svr.is_running());
  10103. });
  10104. svr.wait_until_ready();
  10105. {
  10106. Client cli(HOST, port);
  10107. const std::string evil_methods[] = {
  10108. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10109. "GE T",
  10110. "",
  10111. };
  10112. for (const auto &evil : evil_methods) {
  10113. Request req;
  10114. req.method = evil;
  10115. req.path = "/";
  10116. auto res = cli.send(req);
  10117. EXPECT_FALSE(res);
  10118. EXPECT_EQ(Error::Write, res.error());
  10119. }
  10120. auto handle =
  10121. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10122. EXPECT_FALSE(handle.is_valid());
  10123. EXPECT_EQ(Error::Write, handle.error);
  10124. // A valid request on the same client still goes through.
  10125. auto res = cli.Get("/");
  10126. ASSERT_TRUE(res);
  10127. EXPECT_EQ(StatusCode::OK_200, res->status);
  10128. }
  10129. EXPECT_EQ(1, request_count.load());
  10130. }
  10131. // Sends a raw request and verifies that there isn't a crash or exception.
  10132. static void test_raw_request(const std::string &req,
  10133. std::string *out = nullptr) {
  10134. Server svr;
  10135. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10136. res.set_content("ok", "text/plain");
  10137. });
  10138. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10139. res.set_content("ok", "text/plain");
  10140. });
  10141. svr.Get("/header_field_value_check",
  10142. [&](const Request & /*req*/, Response &res) {
  10143. res.set_content("ok", "text/plain");
  10144. });
  10145. svr.CustomRoute("PROPFIND", "/dav",
  10146. [&](const Request & /*req*/, Response &res) {
  10147. res.status = StatusCode::MultiStatus_207;
  10148. });
  10149. // Server read timeout must be longer than the client read timeout for the
  10150. // bug to reproduce, probably to force the server to process a request
  10151. // without a trailing blank line.
  10152. const time_t client_read_timeout_sec = 1;
  10153. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10154. bool listen_thread_ok = false;
  10155. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10156. auto se = detail::scope_exit([&] {
  10157. svr.stop();
  10158. t.join();
  10159. ASSERT_FALSE(svr.is_running());
  10160. EXPECT_TRUE(listen_thread_ok);
  10161. });
  10162. svr.wait_until_ready();
  10163. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10164. }
  10165. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10166. // A certain header line causes an exception if the header property is parsed
  10167. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10168. test_raw_request(
  10169. "GET /hi HTTP/1.1\r\n"
  10170. " : "
  10171. " "
  10172. " ");
  10173. }
  10174. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10175. // A certain header line causes an exception if the header property *name* is
  10176. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10177. // greedy matcher and requires backtracking when there are a lot of ":"
  10178. // characters.
  10179. // This occurs with libc++ but not libstdc++.
  10180. test_raw_request(
  10181. "GET /hi HTTP/1.1\r\n"
  10182. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10183. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10184. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10185. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10186. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10187. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10188. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10189. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10190. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10191. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10192. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10193. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10194. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10195. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10196. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10197. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10198. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10199. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10200. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10201. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10202. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10203. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10204. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10205. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10206. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10207. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10208. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10209. "&&&%%%");
  10210. }
  10211. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10212. // Make sure this doesn't crash the server.
  10213. // In a previous version of the header line regex, the "\r" rendered the line
  10214. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10215. // a new position where the leading white space ended and the field value
  10216. // began.
  10217. // The crash occurs with libc++ but not libstdc++.
  10218. test_raw_request("GET /hi HTTP/1.1\r\n"
  10219. "a:" +
  10220. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10221. "\r\n"
  10222. "\r\n");
  10223. }
  10224. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10225. const char *rejected[] = {
  10226. // RFC 9112 §3: one SP between the parts, and nothing else
  10227. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10228. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10229. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10230. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10231. // A request-target has no fragment
  10232. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10233. // An HTTP/1.1 request needs a Host
  10234. "GET /hi HTTP/1.1\r\n\r\n",
  10235. };
  10236. for (auto request : rejected) {
  10237. std::string out;
  10238. test_raw_request(request, &out);
  10239. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10240. }
  10241. std::string out;
  10242. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10243. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10244. }
  10245. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10246. // RFC 9112 §6.1
  10247. const char *requests[] = {
  10248. "PUT /put_hi HTTP/1.1\r\n"
  10249. "Host: localhost\r\n"
  10250. "Content-Length: 0\r\n"
  10251. "Transfer-Encoding: chunked\r\n"
  10252. "\r\n"
  10253. "0\r\n\r\n",
  10254. "PUT /put_hi HTTP/1.0\r\n"
  10255. "Connection: keep-alive\r\n"
  10256. "Transfer-Encoding: chunked\r\n"
  10257. "\r\n"
  10258. "0\r\n\r\n",
  10259. };
  10260. for (auto request : requests) {
  10261. std::string out;
  10262. test_raw_request(request, &out);
  10263. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10264. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10265. }
  10266. }
  10267. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10268. std::string out;
  10269. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10270. "Content-Type: text/plain\r\n"
  10271. "Transfer-Encoding: chunked\r\n"
  10272. "\r\n"
  10273. "nothex\r\n",
  10274. &out);
  10275. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10276. }
  10277. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10278. std::string out;
  10279. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10280. "Content-Type: text/plain\r\n"
  10281. "Transfer-Encoding: chunked\r\n"
  10282. "\r\n"
  10283. "3\r\n"
  10284. "xyz\r\n"
  10285. "NaN\r\n",
  10286. &out);
  10287. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10288. }
  10289. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10290. std::string out;
  10291. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10292. "Content-Type: text/plain\r\n"
  10293. "Transfer-Encoding: chunked\r\n"
  10294. "\r\n"
  10295. // Length is too large for 64 bits.
  10296. "1ffffffffffffffff\r\n"
  10297. "xyz\r\n",
  10298. &out);
  10299. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10300. }
  10301. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10302. test_raw_request("GET /hi HTTP/1.1\r\n"
  10303. "Content-Type: text/plain\r\n\r");
  10304. }
  10305. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10306. std::string out;
  10307. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10308. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10309. }
  10310. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10311. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10312. std::string out;
  10313. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10314. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10315. }
  10316. }
  10317. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10318. std::string out;
  10319. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10320. "Host: localhost\r\n"
  10321. "Connection: close\r\n\r\n",
  10322. &out);
  10323. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10324. }
  10325. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10326. Server svr;
  10327. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10328. EXPECT_TRUE(!req.remote_addr.empty());
  10329. });
  10330. thread t = thread([&] { svr.listen(HOST, PORT); });
  10331. auto se = detail::scope_exit([&] {
  10332. svr.stop();
  10333. t.join();
  10334. ASSERT_FALSE(svr.is_running());
  10335. });
  10336. svr.wait_until_ready();
  10337. // Send an invalid request line to trigger Bad Request
  10338. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10339. std::string out;
  10340. ASSERT_TRUE(send_request(5, bad_req, &out));
  10341. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10342. }
  10343. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10344. // answered right away rather than blocking on a read that waits for EOF.
  10345. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10346. std::string out;
  10347. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10348. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10349. }
  10350. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10351. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10352. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10353. for (const auto *method : methods) {
  10354. Server svr;
  10355. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10356. EXPECT_FALSE(svr.is_valid()) << method;
  10357. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10358. }
  10359. }
  10360. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10361. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10362. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10363. for (const auto *method : methods) {
  10364. Server svr;
  10365. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10366. EXPECT_FALSE(svr.is_valid()) << method;
  10367. }
  10368. }
  10369. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10370. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10371. "COPY", "MOVE", "LOCK",
  10372. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10373. Server svr;
  10374. for (const auto *method : methods) {
  10375. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10376. }
  10377. EXPECT_TRUE(svr.is_valid());
  10378. }
  10379. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10380. Server svr;
  10381. svr.CustomRoute("POST", "/x",
  10382. [](const Request &, Response &, const ContentReader &) {});
  10383. EXPECT_FALSE(svr.is_valid());
  10384. }
  10385. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10386. Server svr;
  10387. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10388. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10389. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10390. EXPECT_FALSE(svr.is_valid());
  10391. }
  10392. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10393. Server svr;
  10394. auto captured = Error::Success;
  10395. svr.set_error_logger(
  10396. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10397. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10398. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10399. }
  10400. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10401. std::string out;
  10402. std::string request(
  10403. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10404. test_raw_request(request, &out);
  10405. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10406. }
  10407. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10408. std::string out;
  10409. std::string request(
  10410. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10411. test_raw_request(request, &out);
  10412. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10413. }
  10414. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10415. std::string out;
  10416. std::string request(
  10417. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10418. test_raw_request(request, &out);
  10419. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10420. }
  10421. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10422. std::string out;
  10423. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10424. "Host: localhost\r\n"
  10425. "Test: \r\n\r\n",
  10426. &out);
  10427. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10428. }
  10429. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10430. Server svr;
  10431. std::string x_custom;
  10432. std::string cookie;
  10433. std::string xff;
  10434. std::string x_unicode;
  10435. std::string x_iis;
  10436. svr.Get("/check", [&](const Request &req, Response &res) {
  10437. x_custom = req.get_header_value("X-Custom");
  10438. cookie = req.get_header_value("Cookie");
  10439. xff = req.get_header_value("X-Forwarded-For");
  10440. x_unicode = req.get_header_value("X-Unicode");
  10441. x_iis = req.get_header_value("X-IIS");
  10442. res.set_content("ok", "text/plain");
  10443. });
  10444. thread t = thread([&] { svr.listen(HOST, PORT); });
  10445. auto se = detail::scope_exit([&] {
  10446. svr.stop();
  10447. t.join();
  10448. ASSERT_FALSE(svr.is_running());
  10449. });
  10450. svr.wait_until_ready();
  10451. const std::string req = "GET /check HTTP/1.1\r\n"
  10452. "Host: localhost\r\n"
  10453. "X-Custom: a%0D%0AInjected: b\r\n"
  10454. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10455. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10456. "X-Unicode: %E3%81%82\r\n"
  10457. "X-IIS: %u00E9\r\n"
  10458. "Connection: close\r\n"
  10459. "\r\n";
  10460. std::string res;
  10461. ASSERT_TRUE(send_request(5, req, &res));
  10462. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10463. // Every value must be returned verbatim (wire form), with no decoding.
  10464. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10465. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10466. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10467. EXPECT_EQ("%E3%81%82", x_unicode);
  10468. EXPECT_EQ("%u00E9", x_iis);
  10469. }
  10470. // Applications that previously relied on automatic percent-decoding can
  10471. // reproduce the old behavior by explicitly calling decode_path_component()
  10472. // or, for RFC 3986 conformance, decode_uri_component().
  10473. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10474. Server svr;
  10475. std::string decoded;
  10476. svr.Get("/check", [&](const Request &req, Response &res) {
  10477. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10478. res.set_content("ok", "text/plain");
  10479. });
  10480. thread t = thread([&] { svr.listen(HOST, PORT); });
  10481. auto se = detail::scope_exit([&] {
  10482. svr.stop();
  10483. t.join();
  10484. ASSERT_FALSE(svr.is_running());
  10485. });
  10486. svr.wait_until_ready();
  10487. const std::string req = "GET /check HTTP/1.1\r\n"
  10488. "Host: localhost\r\n"
  10489. "X-Custom: hello%20world\r\n"
  10490. "Connection: close\r\n"
  10491. "\r\n";
  10492. std::string res;
  10493. ASSERT_TRUE(send_request(5, req, &res));
  10494. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10495. EXPECT_EQ("hello world", decoded);
  10496. }
  10497. // Regression test for #2033. Browsers send Referer values that include
  10498. // percent-encoded characters such as %0A inside the URL. Decoding the
  10499. // header value would either trip the post-decode CR/LF/NUL guard (the
  10500. // original bug, returning 400) or, after that guard was relaxed, silently
  10501. // store a literal LF — both unacceptable. The wire form must round-trip.
  10502. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10503. Server svr;
  10504. std::string referer;
  10505. svr.Get("/check", [&](const Request &req, Response &res) {
  10506. referer = req.get_header_value("Referer");
  10507. res.set_content("ok", "text/plain");
  10508. });
  10509. thread t = thread([&] { svr.listen(HOST, PORT); });
  10510. auto se = detail::scope_exit([&] {
  10511. svr.stop();
  10512. t.join();
  10513. ASSERT_FALSE(svr.is_running());
  10514. });
  10515. svr.wait_until_ready();
  10516. const std::string req = "GET /check HTTP/1.1\r\n"
  10517. "Host: localhost\r\n"
  10518. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10519. "Connection: close\r\n"
  10520. "\r\n";
  10521. std::string res;
  10522. ASSERT_TRUE(send_request(5, req, &res));
  10523. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10524. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10525. }
  10526. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10527. Server svr;
  10528. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10529. res.set_header("Cache-Control", "no-cache");
  10530. res.set_chunked_content_provider(
  10531. "text/event-stream", [](size_t offset, DataSink &sink) {
  10532. std::string s = "data:";
  10533. s += std::to_string(offset);
  10534. s += "\n\n";
  10535. auto ret = sink.write(s.data(), s.size());
  10536. EXPECT_TRUE(ret);
  10537. std::this_thread::sleep_for(std::chrono::seconds(1));
  10538. return true;
  10539. });
  10540. });
  10541. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10542. svr.wait_until_ready();
  10543. Client client(HOST, PORT);
  10544. const Headers headers = {{"Accept", "text/event-stream"}};
  10545. auto get_thread = std::thread([&client, &headers]() {
  10546. auto res = client.Get(
  10547. "/events", headers,
  10548. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10549. });
  10550. auto se = detail::scope_exit([&] {
  10551. svr.stop();
  10552. get_thread.join();
  10553. listen_thread.join();
  10554. ASSERT_FALSE(svr.is_running());
  10555. });
  10556. // Give GET time to get a few messages.
  10557. std::this_thread::sleep_for(std::chrono::seconds(2));
  10558. }
  10559. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10560. httplib::Server svr;
  10561. svr.Post("/hi",
  10562. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10563. res.status = StatusCode::OK_200;
  10564. });
  10565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10566. svr.wait_until_ready();
  10567. Client cli(HOST, PORT);
  10568. auto res = cli.Post("/hi", "data", "text/plain");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::OK_200, res->status);
  10571. svr.stop();
  10572. thread.join();
  10573. ASSERT_FALSE(svr.is_running());
  10574. res = cli.Post("/hi", "data", "text/plain");
  10575. ASSERT_FALSE(res);
  10576. }
  10577. TEST(ServerStopTest, ListenFailure) {
  10578. Server svr;
  10579. auto t = thread([&]() {
  10580. auto ret = svr.listen("????", PORT);
  10581. EXPECT_FALSE(ret);
  10582. });
  10583. svr.wait_until_ready();
  10584. svr.stop();
  10585. t.join();
  10586. }
  10587. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10588. TEST(ServerStopTest, Decommision) {
  10589. Server svr;
  10590. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10591. for (int i = 0; i < 4; i++) {
  10592. auto is_even = !(i % 2);
  10593. std::thread t{[&] {
  10594. try {
  10595. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10596. if (is_even) {
  10597. throw std::runtime_error("Some thing that happens to go wrong.");
  10598. }
  10599. svr.listen(HOST, PORT);
  10600. } catch (...) { svr.decommission(); }
  10601. }};
  10602. svr.wait_until_ready();
  10603. // Server is up
  10604. {
  10605. Client cli(HOST, PORT);
  10606. auto res = cli.Get("/hi");
  10607. if (is_even) {
  10608. EXPECT_FALSE(res);
  10609. } else {
  10610. EXPECT_TRUE(res);
  10611. EXPECT_EQ("hi...", res->body);
  10612. }
  10613. }
  10614. svr.stop();
  10615. t.join();
  10616. // Server is down...
  10617. {
  10618. Client cli(HOST, PORT);
  10619. auto res = cli.Get("/hi");
  10620. EXPECT_FALSE(res);
  10621. }
  10622. }
  10623. }
  10624. #endif
  10625. // Helper function for string body upload progress tests
  10626. template <typename SetupHandler, typename ClientCall>
  10627. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10628. ClientCall &&client_call,
  10629. const string &body) {
  10630. Server svr;
  10631. setup_handler(svr);
  10632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10633. auto se = detail::scope_exit([&] {
  10634. svr.stop();
  10635. t.join();
  10636. });
  10637. svr.wait_until_ready();
  10638. Client cli(HOST, PORT);
  10639. vector<uint64_t> progress_values;
  10640. bool progress_called = false;
  10641. auto res =
  10642. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10643. progress_values.push_back(current);
  10644. progress_called = true;
  10645. return true;
  10646. });
  10647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10648. EXPECT_EQ(200, res->status);
  10649. EXPECT_TRUE(progress_called);
  10650. }
  10651. TEST(UploadProgressTest, PostStringBodyBasic) {
  10652. TestStringBodyUploadProgress(
  10653. [](Server &svr) {
  10654. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10655. res.set_content("received", "text/plain");
  10656. });
  10657. },
  10658. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10659. return cli.Post("/test", body, "text/plain", progress_callback);
  10660. },
  10661. "test data for upload progress");
  10662. }
  10663. TEST(UploadProgressTest, PutStringBodyBasic) {
  10664. TestStringBodyUploadProgress(
  10665. [](Server &svr) {
  10666. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10667. res.set_content("put received", "text/plain");
  10668. });
  10669. },
  10670. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10671. return cli.Put("/test", body, "text/plain", progress_callback);
  10672. },
  10673. "put test data for upload progress");
  10674. }
  10675. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10676. TestStringBodyUploadProgress(
  10677. [](Server &svr) {
  10678. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10679. res.set_content("patch received", "text/plain");
  10680. });
  10681. },
  10682. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10683. return cli.Patch("/test", body, "text/plain", progress_callback);
  10684. },
  10685. "patch test data for upload progress");
  10686. }
  10687. // Helper function for content provider upload progress tests
  10688. template <typename SetupHandler, typename ClientCall>
  10689. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10690. ClientCall &&client_call) {
  10691. Server svr;
  10692. setup_handler(svr);
  10693. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10694. auto se = detail::scope_exit([&] {
  10695. svr.stop();
  10696. t.join();
  10697. });
  10698. svr.wait_until_ready();
  10699. Client cli(HOST, PORT);
  10700. vector<uint64_t> progress_values;
  10701. auto res =
  10702. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10703. progress_values.push_back(current);
  10704. return true;
  10705. });
  10706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10707. EXPECT_EQ(200, res->status);
  10708. EXPECT_FALSE(progress_values.empty());
  10709. }
  10710. TEST(UploadProgressTest, PostContentProviderProgress) {
  10711. TestContentProviderUploadProgress(
  10712. [](Server &svr) {
  10713. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10714. res.set_content("provider received", "text/plain");
  10715. });
  10716. },
  10717. [](Client &cli, UploadProgress progress_callback) {
  10718. return cli.Post(
  10719. "/test", 9,
  10720. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10721. sink.os << "test data";
  10722. return true;
  10723. },
  10724. "text/plain", progress_callback);
  10725. });
  10726. }
  10727. // Helper function for multipart upload progress tests
  10728. template <typename SetupHandler, typename ClientCall>
  10729. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10730. ClientCall &&client_call,
  10731. const string &endpoint) {
  10732. Server svr;
  10733. setup_handler(svr);
  10734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10735. auto se = detail::scope_exit([&] {
  10736. svr.stop();
  10737. t.join();
  10738. });
  10739. svr.wait_until_ready();
  10740. Client cli(HOST, PORT);
  10741. vector<uint64_t> progress_values;
  10742. UploadFormDataItems items = {
  10743. {"field1", "value1", "", ""},
  10744. {"field2", "longer value for progress tracking test", "", ""},
  10745. {"file1", "file content data for upload progress", "test.txt",
  10746. "text/plain"}};
  10747. auto res = client_call(cli, endpoint, items,
  10748. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10749. progress_values.push_back(current);
  10750. return true;
  10751. });
  10752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10753. EXPECT_EQ(200, res->status);
  10754. EXPECT_FALSE(progress_values.empty());
  10755. }
  10756. TEST(UploadProgressTest, PostMultipartProgress) {
  10757. TestMultipartUploadProgress(
  10758. [](Server &svr) {
  10759. svr.Post("/multipart", [](const Request &req, Response &res) {
  10760. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10761. res.set_content("multipart received", "text/plain");
  10762. });
  10763. },
  10764. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10765. UploadProgress progress_callback) {
  10766. return cli.Post(endpoint, items, progress_callback);
  10767. },
  10768. "/multipart");
  10769. }
  10770. // Helper function for basic download progress tests
  10771. template <typename SetupHandler, typename ClientCall>
  10772. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10773. ClientCall &&client_call, const string &endpoint,
  10774. size_t expected_content_size) {
  10775. Server svr;
  10776. setup_handler(svr);
  10777. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10778. auto se = detail::scope_exit([&] {
  10779. svr.stop();
  10780. t.join();
  10781. });
  10782. svr.wait_until_ready();
  10783. Client cli(HOST, PORT);
  10784. vector<uint64_t> progress_values;
  10785. auto res = client_call(cli, endpoint,
  10786. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10787. progress_values.push_back(current);
  10788. return true;
  10789. });
  10790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10791. EXPECT_EQ(200, res->status);
  10792. EXPECT_FALSE(progress_values.empty());
  10793. EXPECT_EQ(expected_content_size, res->body.size());
  10794. }
  10795. TEST(DownloadProgressTest, GetBasic) {
  10796. TestBasicDownloadProgress(
  10797. [](Server &svr) {
  10798. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10799. string content(1000, 'D');
  10800. res.set_content(content, "text/plain");
  10801. });
  10802. },
  10803. [](Client &cli, const string &endpoint,
  10804. DownloadProgress progress_callback) {
  10805. return cli.Get(endpoint, progress_callback);
  10806. },
  10807. "/download", 1000u);
  10808. }
  10809. // Helper function for content receiver download progress tests
  10810. template <typename SetupHandler, typename ClientCall>
  10811. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10812. ClientCall &&client_call,
  10813. const string &endpoint,
  10814. size_t expected_content_size) {
  10815. Server svr;
  10816. setup_handler(svr);
  10817. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10818. auto se = detail::scope_exit([&] {
  10819. svr.stop();
  10820. t.join();
  10821. });
  10822. svr.wait_until_ready();
  10823. Client cli(HOST, PORT);
  10824. vector<uint64_t> progress_values;
  10825. string received_body;
  10826. auto res = client_call(
  10827. cli, endpoint,
  10828. [&](const char *data, size_t data_length) -> bool {
  10829. received_body.append(data, data_length);
  10830. return true;
  10831. },
  10832. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10833. progress_values.push_back(current);
  10834. return true;
  10835. });
  10836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10837. EXPECT_EQ(200, res->status);
  10838. EXPECT_FALSE(progress_values.empty());
  10839. EXPECT_EQ(expected_content_size, received_body.size());
  10840. EXPECT_TRUE(res->body.empty());
  10841. }
  10842. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10843. TestContentReceiverDownloadProgress(
  10844. [](Server &svr) {
  10845. svr.Get("/download-receiver",
  10846. [](const Request & /*req*/, Response &res) {
  10847. string content(2000, 'R');
  10848. res.set_content(content, "text/plain");
  10849. });
  10850. },
  10851. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10852. DownloadProgress progress_callback) {
  10853. return cli.Get(endpoint, content_receiver, progress_callback);
  10854. },
  10855. "/download-receiver", 2000u);
  10856. }
  10857. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10858. // A provider reaching a pass with nothing to hand over - an empty buffer
  10859. // popped off a queue, say - must not be taken to mean the body is finished.
  10860. // It used to end the loop with the terminating chunk unwritten while the
  10861. // server still considered the response complete, so the peer waited for an
  10862. // end that never arrived.
  10863. Server svr;
  10864. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10865. auto step = std::make_shared<int>(0);
  10866. res.set_chunked_content_provider("text/plain",
  10867. [step](size_t /*offset*/, DataSink &sink) {
  10868. switch ((*step)++) {
  10869. case 0: sink.write("", 0); break;
  10870. case 1: sink.write("hello", 5); break;
  10871. default: sink.done(); break;
  10872. }
  10873. return true;
  10874. });
  10875. });
  10876. auto port = svr.bind_to_any_port(HOST);
  10877. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10878. auto listen_se = detail::scope_exit([&] {
  10879. svr.stop();
  10880. listen_thread.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. Client cli(HOST, port);
  10885. // Without the fix the body is never terminated, so bound the wait rather
  10886. // than letting the test hang on the default read timeout.
  10887. cli.set_read_timeout(5, 0);
  10888. auto res = cli.Get("/stream");
  10889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10890. EXPECT_EQ(StatusCode::OK_200, res->status);
  10891. EXPECT_EQ("hello", res->body);
  10892. }
  10893. TEST(StreamingTest, NoContentLengthStreaming) {
  10894. Server svr;
  10895. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10896. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10897. if (offset < 6) {
  10898. sink.os << (offset < 3 ? "a" : "b");
  10899. } else {
  10900. sink.done();
  10901. }
  10902. return true;
  10903. });
  10904. });
  10905. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10906. auto listen_se = detail::scope_exit([&] {
  10907. svr.stop();
  10908. listen_thread.join();
  10909. ASSERT_FALSE(svr.is_running());
  10910. });
  10911. svr.wait_until_ready();
  10912. Client client(HOST, PORT);
  10913. auto get_thread = std::thread([&client]() {
  10914. std::string s;
  10915. auto res =
  10916. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10917. s += std::string(data, len);
  10918. return true;
  10919. });
  10920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10921. EXPECT_EQ(StatusCode::OK_200, res->status);
  10922. EXPECT_EQ("aaabbb", s);
  10923. });
  10924. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10925. // Give GET time to get a few messages.
  10926. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10927. }
  10928. TEST(MountTest, Unmount) {
  10929. Server svr;
  10930. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10931. auto se = detail::scope_exit([&] {
  10932. svr.stop();
  10933. listen_thread.join();
  10934. ASSERT_FALSE(svr.is_running());
  10935. });
  10936. svr.wait_until_ready();
  10937. Client cli("localhost", PORT);
  10938. svr.set_mount_point("/mount2", "./www2");
  10939. auto res = cli.Get("/");
  10940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10941. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10942. res = cli.Get("/mount2/dir/test.html");
  10943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10944. EXPECT_EQ(StatusCode::OK_200, res->status);
  10945. svr.set_mount_point("/", "./www");
  10946. res = cli.Get("/dir/");
  10947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10948. EXPECT_EQ(StatusCode::OK_200, res->status);
  10949. svr.remove_mount_point("/");
  10950. res = cli.Get("/dir/");
  10951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10953. svr.remove_mount_point("/mount2");
  10954. res = cli.Get("/mount2/dir/test.html");
  10955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10956. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10957. }
  10958. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10959. Server svr;
  10960. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10961. svr.Get("/api/hello", [](const Request &, Response &res) {
  10962. res.set_content("api", "text/plain");
  10963. });
  10964. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. listen_thread.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. Client cli(HOST, PORT);
  10972. auto res = cli.Get("/dir/test.html");
  10973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10974. EXPECT_EQ(StatusCode::OK_200, res->status);
  10975. res = cli.Get("/api/hello");
  10976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10977. EXPECT_EQ(StatusCode::OK_200, res->status);
  10978. EXPECT_EQ("api", res->body);
  10979. }
  10980. TEST(MountTest, PathSegmentBoundary) {
  10981. Server svr;
  10982. svr.set_mount_point("/mount2", "./www2");
  10983. svr.set_mount_point("/", "./www");
  10984. auto port = svr.bind_to_any_port(HOST);
  10985. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10986. auto se = detail::scope_exit([&] {
  10987. svr.stop();
  10988. listen_thread.join();
  10989. ASSERT_FALSE(svr.is_running());
  10990. });
  10991. svr.wait_until_ready();
  10992. Client cli(HOST, port);
  10993. auto res = cli.Get("/mount2/dir/test.html");
  10994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10995. EXPECT_EQ(StatusCode::OK_200, res->status);
  10996. // "/mount2" must not match part-way through a path segment.
  10997. res = cli.Get("/mount2dir/test.html");
  10998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10999. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11000. // A mount point ending in '/' keeps matching every path below it.
  11001. res = cli.Get("/dir/test.html");
  11002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11003. EXPECT_EQ(StatusCode::OK_200, res->status);
  11004. }
  11005. TEST(MountTest, Redicect) {
  11006. Server svr;
  11007. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11008. auto se = detail::scope_exit([&] {
  11009. svr.stop();
  11010. listen_thread.join();
  11011. ASSERT_FALSE(svr.is_running());
  11012. });
  11013. svr.set_mount_point("/", "./www");
  11014. svr.wait_until_ready();
  11015. Client cli("localhost", PORT);
  11016. auto res = cli.Get("/dir/");
  11017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11018. EXPECT_EQ(StatusCode::OK_200, res->status);
  11019. res = cli.Get("/dir");
  11020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11021. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11022. res = cli.Get("/file");
  11023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11024. EXPECT_EQ(StatusCode::OK_200, res->status);
  11025. res = cli.Get("/file/");
  11026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11027. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11028. cli.set_follow_location(true);
  11029. res = cli.Get("/dir");
  11030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11031. EXPECT_EQ(StatusCode::OK_200, res->status);
  11032. }
  11033. TEST(MountTest, MultibytesPathName) {
  11034. Server svr;
  11035. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11036. auto se = detail::scope_exit([&] {
  11037. svr.stop();
  11038. listen_thread.join();
  11039. ASSERT_FALSE(svr.is_running());
  11040. });
  11041. svr.set_mount_point("/", "./www");
  11042. svr.wait_until_ready();
  11043. Client cli("localhost", PORT);
  11044. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11046. EXPECT_EQ(StatusCode::OK_200, res->status);
  11047. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11048. }
  11049. // A mount point serves no path with an empty segment or one ending in '.' or
  11050. // a space, so a guard in the pre-routing handler sees the path of every file
  11051. // that is served
  11052. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11053. Server svr;
  11054. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11055. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11056. if (req.path == "/dir/test.html") {
  11057. res.status = StatusCode::Unauthorized_401;
  11058. return Server::HandlerResponse::Handled;
  11059. }
  11060. return Server::HandlerResponse::Unhandled;
  11061. });
  11062. auto port = svr.bind_to_any_port(HOST);
  11063. ASSERT_LT(0, port);
  11064. thread t = thread([&] { svr.listen_after_bind(); });
  11065. auto se = detail::scope_exit([&] {
  11066. svr.stop();
  11067. t.join();
  11068. ASSERT_FALSE(svr.is_running());
  11069. });
  11070. svr.wait_until_ready();
  11071. Client cli(HOST, port);
  11072. for (auto path :
  11073. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11074. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11075. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11076. "/dir/test.html%3A%3A$DATA"}) {
  11077. SCOPED_TRACE(path);
  11078. auto res = cli.Get(path);
  11079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11081. }
  11082. }
  11083. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11084. Server svr;
  11085. svr.set_mount_point("/", "./www");
  11086. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11087. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11088. auto port = svr.bind_to_any_port(HOST);
  11089. ASSERT_GT(port, 0);
  11090. thread t = thread([&] { svr.listen_after_bind(); });
  11091. auto se = detail::scope_exit([&] {
  11092. svr.stop();
  11093. t.join();
  11094. ASSERT_FALSE(svr.is_running());
  11095. });
  11096. svr.wait_until_ready();
  11097. Client cli(HOST, port);
  11098. auto res = cli.Get("/dir/test.abcde");
  11099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11100. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11101. res = cli.Get("/dir/test.html");
  11102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11103. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11104. }
  11105. #ifdef _WIN32
  11106. // Issue #2435: mmap::open() must succeed even when another handle holds
  11107. // the file open for writing (e.g. an active log file).
  11108. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11109. const char *path = "mmap_concurrent_writer_test.txt";
  11110. const char *content = "hello";
  11111. {
  11112. std::ofstream f(path, std::ios::binary);
  11113. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11114. }
  11115. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11116. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11117. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11118. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11119. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11120. detail::mmap m(path);
  11121. ASSERT_TRUE(m.is_open());
  11122. EXPECT_EQ(strlen(content), m.size());
  11123. char buf[8];
  11124. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11125. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11126. }
  11127. #endif
  11128. #ifndef _WIN32
  11129. // A directory or a device has no size to serve.
  11130. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11131. const char *path = "./mmap_not_regular_test_dir";
  11132. ASSERT_EQ(0, ::mkdir(path, 0755));
  11133. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11134. for (auto p : {path, "/dev/null"}) {
  11135. detail::mmap m(p);
  11136. EXPECT_FALSE(m.is_open()) << p;
  11137. EXPECT_EQ(0U, m.size()) << p;
  11138. }
  11139. Server svr;
  11140. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11141. res.set_file_content("/dev/null");
  11142. });
  11143. auto port = svr.bind_to_any_port(HOST);
  11144. thread t = thread([&] { svr.listen_after_bind(); });
  11145. auto se = detail::scope_exit([&] {
  11146. svr.stop();
  11147. t.join();
  11148. });
  11149. svr.wait_until_ready();
  11150. auto res = Client(HOST, port).Get("/null");
  11151. ASSERT_TRUE(res);
  11152. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11153. }
  11154. #endif
  11155. #ifdef __linux__
  11156. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11157. TEST(MmapTest, FileIsNotMapped) {
  11158. const char *path = "mmap_not_mapped_test.txt";
  11159. {
  11160. std::ofstream f(path, std::ios::binary);
  11161. f << "hello";
  11162. }
  11163. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11164. detail::mmap m(path);
  11165. ASSERT_TRUE(m.is_open());
  11166. std::ifstream maps("/proc/self/maps");
  11167. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11168. std::istreambuf_iterator<char>());
  11169. EXPECT_EQ(std::string::npos, mappings.find(path));
  11170. }
  11171. #endif
  11172. TEST(KeepAliveTest, ReadTimeout) {
  11173. Server svr;
  11174. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11175. std::this_thread::sleep_for(std::chrono::seconds(2));
  11176. res.set_content("a", "text/plain");
  11177. });
  11178. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11179. res.set_content("b", "text/plain");
  11180. });
  11181. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11182. auto se = detail::scope_exit([&] {
  11183. svr.stop();
  11184. listen_thread.join();
  11185. ASSERT_FALSE(svr.is_running());
  11186. });
  11187. svr.wait_until_ready();
  11188. Client cli("localhost", PORT);
  11189. cli.set_keep_alive(true);
  11190. cli.set_read_timeout(std::chrono::seconds(1));
  11191. auto resa = cli.Get("/a");
  11192. ASSERT_FALSE(resa);
  11193. EXPECT_EQ(Error::Read, resa.error());
  11194. auto resb = cli.Get("/b");
  11195. ASSERT_TRUE(resb);
  11196. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11197. EXPECT_EQ("b", resb->body);
  11198. }
  11199. TEST(KeepAliveTest, MaxCount) {
  11200. size_t keep_alive_max_count = 3;
  11201. Server svr;
  11202. svr.set_keep_alive_max_count(keep_alive_max_count);
  11203. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11204. res.set_content("Hello World!", "text/plain");
  11205. });
  11206. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11207. auto se = detail::scope_exit([&] {
  11208. svr.stop();
  11209. listen_thread.join();
  11210. ASSERT_FALSE(svr.is_running());
  11211. });
  11212. svr.wait_until_ready();
  11213. Client cli(HOST, PORT);
  11214. cli.set_keep_alive(true);
  11215. for (size_t i = 0; i < 5; i++) {
  11216. auto result = cli.Get("/hi");
  11217. ASSERT_TRUE(result);
  11218. EXPECT_EQ(StatusCode::OK_200, result->status);
  11219. if (i == keep_alive_max_count - 1) {
  11220. EXPECT_EQ("close", result->get_header_value("Connection"));
  11221. } else {
  11222. EXPECT_FALSE(result->has_header("Connection"));
  11223. }
  11224. }
  11225. }
  11226. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11227. // can pull the next one into the server's buffer. The server must serve it
  11228. // without waiting for the socket to become readable again. The keep-alive
  11229. // timeout outlasts the client's read timeout, so a request left waiting for it
  11230. // shows up as a missing response.
  11231. static void serve_pipelining_routes(Server &svr,
  11232. const std::function<void(int)> &client) {
  11233. svr.set_keep_alive_timeout(5);
  11234. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11235. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11236. });
  11237. svr.Post("/echo", [](const Request &req, Response &res) {
  11238. res.set_content("echo " + req.body, "text/plain");
  11239. });
  11240. auto port = svr.bind_to_any_port(HOST);
  11241. thread t = thread([&] { svr.listen_after_bind(); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. t.join();
  11245. });
  11246. svr.wait_until_ready();
  11247. client(port);
  11248. }
  11249. static std::string
  11250. send_pipelined_requests(const std::vector<std::string> &parts) {
  11251. Server svr;
  11252. std::string res;
  11253. serve_pipelining_routes(svr, [&](int port) {
  11254. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11255. });
  11256. return res;
  11257. }
  11258. static void expect_in_order(const std::string &res,
  11259. const std::vector<std::string> &bodies) {
  11260. size_t pos = 0;
  11261. for (const auto &body : bodies) {
  11262. pos = res.find(body, pos);
  11263. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11264. pos += body.size();
  11265. }
  11266. }
  11267. TEST(KeepAliveTest, PipelinedRequests) {
  11268. auto res = send_pipelined_requests(
  11269. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11270. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11271. "Content-Length: 4\r\n\r\nbody"
  11272. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11273. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11274. }
  11275. // The second request starts in the server's buffer and ends on the socket.
  11276. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11277. auto res =
  11278. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11279. "GET /hi/2 HTTP/1.1\r\nHo",
  11280. "st: localhost\r\nConnection: close\r\n\r\n"});
  11281. expect_in_order(res, {"hi 1", "hi 2"});
  11282. }
  11283. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11284. // CRLF after a body does not turn into a 400 for the next request.
  11285. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11286. auto res = send_pipelined_requests(
  11287. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11288. "Content-Length: 4\r\n\r\nbody\r\n"
  11289. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11290. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11291. expect_in_order(res, {"echo body", "hi 2"});
  11292. }
  11293. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11294. // must not be served as the next request.
  11295. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11296. auto res = send_pipelined_requests(
  11297. {"INVALID REQUEST LINE\r\n\r\n"
  11298. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11299. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11300. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11301. }
  11302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11303. // Over TLS, the next request is held by the TLS library as already decrypted
  11304. // data rather than on the socket.
  11305. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11307. std::string res;
  11308. serve_pipelining_routes(svr, [&](int port) {
  11309. // One part, so all three requests arrive in one TLS record
  11310. EXPECT_TRUE(send_ssl_request_in_parts(
  11311. 2,
  11312. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11313. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11314. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11315. &res, port));
  11316. });
  11317. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11318. }
  11319. #endif
  11320. TEST(KeepAliveTest, Issue1041) {
  11321. Server svr;
  11322. svr.set_keep_alive_timeout(3);
  11323. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11324. res.set_content("Hello World!", "text/plain");
  11325. });
  11326. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11327. auto se = detail::scope_exit([&] {
  11328. svr.stop();
  11329. listen_thread.join();
  11330. ASSERT_FALSE(svr.is_running());
  11331. });
  11332. svr.wait_until_ready();
  11333. Client cli(HOST, PORT);
  11334. cli.set_keep_alive(true);
  11335. auto result = cli.Get("/hi");
  11336. ASSERT_TRUE(result);
  11337. EXPECT_EQ(StatusCode::OK_200, result->status);
  11338. std::this_thread::sleep_for(std::chrono::seconds(5));
  11339. result = cli.Get("/hi");
  11340. ASSERT_TRUE(result);
  11341. EXPECT_EQ(StatusCode::OK_200, result->status);
  11342. }
  11343. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11344. Server svr;
  11345. svr.set_keep_alive_max_count(0);
  11346. std::set<int> remote_ports;
  11347. svr.Get("/hi", [&](const Request &req, Response &res) {
  11348. remote_ports.insert(req.remote_port);
  11349. res.set_content("hi", "text/plain");
  11350. });
  11351. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11352. auto se = detail::scope_exit([&] {
  11353. svr.stop();
  11354. listen_thread.join();
  11355. ASSERT_FALSE(svr.is_running());
  11356. });
  11357. svr.wait_until_ready();
  11358. Client cli(HOST, PORT);
  11359. cli.set_keep_alive(true);
  11360. for (int i = 0; i < 3; i++) {
  11361. auto res = cli.Get("/hi");
  11362. ASSERT_TRUE(res);
  11363. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11364. }
  11365. // All three over one connection
  11366. EXPECT_EQ(1u, remote_ports.size());
  11367. }
  11368. TEST(KeepAliveTest, Issue1959) {
  11369. Server svr;
  11370. svr.set_keep_alive_timeout(5);
  11371. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11372. res.set_content("a", "text/plain");
  11373. });
  11374. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11375. auto se = detail::scope_exit([&] {
  11376. if (!svr.is_running()) return;
  11377. svr.stop();
  11378. listen_thread.join();
  11379. ASSERT_FALSE(svr.is_running());
  11380. });
  11381. svr.wait_until_ready();
  11382. Client cli("localhost", PORT);
  11383. cli.set_keep_alive(true);
  11384. using namespace std::chrono;
  11385. auto start = steady_clock::now();
  11386. cli.Get("/a");
  11387. svr.stop();
  11388. listen_thread.join();
  11389. auto end = steady_clock::now();
  11390. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11391. EXPECT_LT(elapsed, 5000);
  11392. }
  11393. #ifdef CPPHTTPLIB_SSL_ENABLED
  11394. TEST(KeepAliveTest, SSLClientReconnection) {
  11395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11396. ASSERT_TRUE(svr.is_valid());
  11397. svr.set_keep_alive_timeout(1);
  11398. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11399. res.set_content("Hello World!", "text/plain");
  11400. });
  11401. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11402. auto se = detail::scope_exit([&] {
  11403. svr.stop();
  11404. listen_thread.join();
  11405. ASSERT_FALSE(svr.is_running());
  11406. });
  11407. svr.wait_until_ready();
  11408. SSLClient cli(HOST, PORT);
  11409. cli.enable_server_certificate_verification(false);
  11410. cli.set_keep_alive(true);
  11411. auto result = cli.Get("/hi");
  11412. ASSERT_TRUE(result);
  11413. EXPECT_EQ(StatusCode::OK_200, result->status);
  11414. result = cli.Get("/hi");
  11415. ASSERT_TRUE(result);
  11416. EXPECT_EQ(StatusCode::OK_200, result->status);
  11417. std::this_thread::sleep_for(std::chrono::seconds(2));
  11418. // Recoonect
  11419. result = cli.Get("/hi");
  11420. ASSERT_TRUE(result);
  11421. EXPECT_EQ(StatusCode::OK_200, result->status);
  11422. result = cli.Get("/hi");
  11423. ASSERT_TRUE(result);
  11424. EXPECT_EQ(StatusCode::OK_200, result->status);
  11425. }
  11426. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11427. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11428. ASSERT_TRUE(svr.is_valid());
  11429. svr.set_keep_alive_timeout(1);
  11430. std::string content = "reconnect";
  11431. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11432. res.set_content("Hello World!", "text/plain");
  11433. });
  11434. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11435. auto se = detail::scope_exit([&] {
  11436. svr.stop();
  11437. listen_thread.join();
  11438. ASSERT_FALSE(svr.is_running());
  11439. });
  11440. svr.wait_until_ready();
  11441. SSLClient cli(HOST, PORT);
  11442. cli.enable_server_certificate_verification(false);
  11443. cli.set_keep_alive(true);
  11444. auto result = cli.Post(
  11445. "/hi", content.size(),
  11446. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11447. sink.write(content.c_str(), content.size());
  11448. return true;
  11449. },
  11450. "text/plain");
  11451. ASSERT_TRUE(result);
  11452. EXPECT_EQ(200, result->status);
  11453. std::this_thread::sleep_for(std::chrono::seconds(2));
  11454. // Recoonect
  11455. result = cli.Post(
  11456. "/hi", content.size(),
  11457. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11458. sink.write(content.c_str(), content.size());
  11459. return true;
  11460. },
  11461. "text/plain");
  11462. ASSERT_TRUE(result);
  11463. EXPECT_EQ(200, result->status);
  11464. result = cli.Post(
  11465. "/hi", content.size(),
  11466. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11467. sink.write(content.c_str(), content.size());
  11468. return true;
  11469. },
  11470. "text/plain");
  11471. ASSERT_TRUE(result);
  11472. EXPECT_EQ(200, result->status);
  11473. }
  11474. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11475. using namespace httplib::tls;
  11476. {
  11477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11478. ASSERT_TRUE(svr.is_valid());
  11479. svr.Get("/sni", [&](const Request &req, Response &res) {
  11480. std::string expected = req.sni();
  11481. EXPECT_EQ(expected, req.get_param_value("expected"));
  11482. res.set_content("ok", "text/plain");
  11483. });
  11484. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11485. auto se = detail::scope_exit([&] {
  11486. svr.stop();
  11487. listen_thread.join();
  11488. ASSERT_FALSE(svr.is_running());
  11489. });
  11490. svr.wait_until_ready();
  11491. {
  11492. SSLClient cli("localhost", PORT);
  11493. cli.enable_server_certificate_verification(false);
  11494. auto res = cli.Get("/sni?expected=localhost");
  11495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11496. }
  11497. {
  11498. SSLClient cli("::1", PORT);
  11499. cli.enable_server_certificate_verification(false);
  11500. auto res = cli.Get("/sni?expected=");
  11501. // NOTE: This may fail if the server is listening on IPv4 only
  11502. // (e.g., when localhost resolves to 127.0.0.1 only)
  11503. if (res) {
  11504. EXPECT_EQ(StatusCode::OK_200, res->status);
  11505. } else {
  11506. EXPECT_EQ(Error::Connection, res.error());
  11507. }
  11508. }
  11509. }
  11510. }
  11511. // The SNI of a failed handshake does not reach the next connection that the
  11512. // same worker thread serves
  11513. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11515. ASSERT_TRUE(svr.is_valid());
  11516. svr.new_task_queue = [] { return new ThreadPool(1); };
  11517. svr.Get("/sni", [](const Request &req, Response &res) {
  11518. res.set_content(req.sni(), "text/plain");
  11519. });
  11520. auto port = svr.bind_to_any_port("127.0.0.1");
  11521. ASSERT_LT(0, port);
  11522. thread t = thread([&] { svr.listen_after_bind(); });
  11523. auto se = detail::scope_exit([&] {
  11524. svr.stop();
  11525. t.join();
  11526. ASSERT_FALSE(svr.is_running());
  11527. });
  11528. svr.wait_until_ready();
  11529. {
  11530. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11531. SSLClient cli("localhost", port);
  11532. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11533. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11534. auto res = cli.Get("/sni");
  11535. ASSERT_FALSE(res);
  11536. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11537. }
  11538. // An IP host sends no SNI (RFC 6066)
  11539. SSLClient cli("127.0.0.1", port);
  11540. cli.enable_server_certificate_verification(false);
  11541. auto res = cli.Get("/sni");
  11542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11543. EXPECT_EQ("", res->body);
  11544. }
  11545. #endif
  11546. TEST(ClientProblemDetectionTest, ContentProvider) {
  11547. Server svr;
  11548. size_t content_length = 1024 * 1024;
  11549. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11550. res.set_content_provider(
  11551. content_length, "text/plain",
  11552. [&](size_t offset, size_t length, DataSink &sink) {
  11553. auto out_len = std::min(length, static_cast<size_t>(1024));
  11554. std::string out(out_len, '@');
  11555. sink.write(out.data(), out_len);
  11556. return offset < 4096;
  11557. },
  11558. [](bool success) { ASSERT_FALSE(success); });
  11559. });
  11560. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11561. res.set_content_provider(
  11562. 0, "text/plain",
  11563. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11564. EXPECT_TRUE(false);
  11565. return true;
  11566. },
  11567. [](bool success) { ASSERT_FALSE(success); });
  11568. });
  11569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. listen_thread.join();
  11573. ASSERT_FALSE(svr.is_running());
  11574. });
  11575. svr.wait_until_ready();
  11576. Client cli("localhost", PORT);
  11577. {
  11578. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11579. size_t /*data_length*/) { return false; });
  11580. ASSERT_FALSE(res);
  11581. }
  11582. {
  11583. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11584. size_t /*data_length*/) { return false; });
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. }
  11587. }
  11588. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11589. // A provider that reports success without writing anything and without
  11590. // calling done() used to be handed the same offset and length again on every
  11591. // pass, so it spun for as long as the peer stayed connected.
  11592. Server svr;
  11593. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11594. res.set_content("ok", "text/plain");
  11595. });
  11596. auto port = svr.bind_to_any_port(HOST);
  11597. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11598. auto se = detail::scope_exit([&] {
  11599. svr.stop();
  11600. listen_thread.join();
  11601. ASSERT_FALSE(svr.is_running());
  11602. });
  11603. svr.wait_until_ready();
  11604. std::atomic<int> call_count{0};
  11605. Client cli(HOST, port);
  11606. auto res = cli.Post(
  11607. "/", 1024,
  11608. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11609. // Give up after enough passes to show the spin, so that losing the
  11610. // check below fails this test instead of hanging it.
  11611. return ++call_count < 100;
  11612. },
  11613. "text/plain");
  11614. ASSERT_FALSE(res);
  11615. EXPECT_EQ(Error::Write, res.error());
  11616. EXPECT_EQ(1, call_count.load());
  11617. }
  11618. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11619. // A writer only has to assign `write`. The other three used to be left as
  11620. // empty std::functions, so a provider calling one threw
  11621. // std::bad_function_call out of the thread running it and took the whole
  11622. // process down.
  11623. DataSink sink;
  11624. std::string written;
  11625. sink.write = [&](const char *data, size_t data_len) {
  11626. written.append(data, data_len);
  11627. return true;
  11628. };
  11629. EXPECT_TRUE(sink.is_writable());
  11630. sink.done();
  11631. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11632. EXPECT_TRUE(written.empty());
  11633. }
  11634. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11635. // A sink that cannot carry trailers still has to finish.
  11636. DataSink sink;
  11637. auto done_count = 0;
  11638. sink.done = [&]() { done_count++; };
  11639. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11640. EXPECT_EQ(1, done_count);
  11641. }
  11642. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11643. Server svr;
  11644. const std::string body(4096, 'x');
  11645. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11646. res.set_content_provider(body.size(), "text/plain",
  11647. [&](size_t offset, size_t length, DataSink &sink) {
  11648. sink.write(body.data() + offset, length);
  11649. sink.done();
  11650. return true;
  11651. });
  11652. });
  11653. auto port = svr.bind_to_any_port(HOST);
  11654. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11655. auto se = detail::scope_exit([&] {
  11656. svr.stop();
  11657. listen_thread.join();
  11658. ASSERT_FALSE(svr.is_running());
  11659. });
  11660. svr.wait_until_ready();
  11661. Client cli(HOST, port);
  11662. auto res = cli.Get("/");
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. EXPECT_EQ(StatusCode::OK_200, res->status);
  11665. EXPECT_EQ(body, res->body);
  11666. }
  11667. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11668. Server svr;
  11669. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11670. res.set_content_provider(
  11671. 1024, "text/plain",
  11672. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11673. sink.write("hello", 5);
  11674. sink.done(); // short of the 1024 bytes the response promised
  11675. return true;
  11676. });
  11677. });
  11678. auto port = svr.bind_to_any_port(HOST);
  11679. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11680. auto se = detail::scope_exit([&] {
  11681. svr.stop();
  11682. listen_thread.join();
  11683. ASSERT_FALSE(svr.is_running());
  11684. });
  11685. svr.wait_until_ready();
  11686. Client cli(HOST, port);
  11687. cli.set_read_timeout(5, 0);
  11688. // The response is short of its Content-Length, so the client cannot read a
  11689. // complete body. What matters is that this returns at all: a no-op done()
  11690. // would leave the writer looping over a provider that never makes progress.
  11691. auto res = cli.Get("/");
  11692. EXPECT_FALSE(res);
  11693. }
  11694. // Read as the next response by a peer that sees it after a framed body.
  11695. static const std::string smuggled_response =
  11696. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11697. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11698. Server svr;
  11699. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11700. res.set_content_provider(
  11701. 5, "text/plain",
  11702. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11703. auto data = "AAAAA" + smuggled_response;
  11704. sink.write(data.data(), data.size());
  11705. return true;
  11706. });
  11707. });
  11708. thread t = thread([&] { svr.listen(HOST, PORT); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. t.join();
  11712. ASSERT_FALSE(svr.is_running());
  11713. });
  11714. svr.wait_until_ready();
  11715. std::string resp;
  11716. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11717. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11718. resp.clear();
  11719. ASSERT_TRUE(send_request(
  11720. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11721. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11722. }
  11723. TEST(NoContentTest, BodyIsNotSent) {
  11724. Server svr;
  11725. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11726. res.status = StatusCode::NoContent_204;
  11727. res.set_content(smuggled_response, "text/plain");
  11728. });
  11729. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11730. res.status = StatusCode::NotModified_304;
  11731. res.set_chunked_content_provider(
  11732. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11733. sink.write(smuggled_response.data(), smuggled_response.size());
  11734. sink.done();
  11735. return true;
  11736. });
  11737. });
  11738. thread t = thread([&] { svr.listen(HOST, PORT); });
  11739. auto se = detail::scope_exit([&] {
  11740. svr.stop();
  11741. t.join();
  11742. ASSERT_FALSE(svr.is_running());
  11743. });
  11744. svr.wait_until_ready();
  11745. for (auto path : {"/204", "/304"}) {
  11746. std::string resp;
  11747. ASSERT_TRUE(send_request(
  11748. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11749. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11750. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11751. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11752. }
  11753. }
  11754. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11755. Server svr;
  11756. std::atomic<bool> smuggled(false);
  11757. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11758. res.set_content("ok", "text/plain");
  11759. });
  11760. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11761. smuggled = true;
  11762. });
  11763. auto port = svr.bind_to_any_port(HOST);
  11764. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11765. auto se = detail::scope_exit([&] {
  11766. svr.stop();
  11767. listen_thread.join();
  11768. ASSERT_FALSE(svr.is_running());
  11769. });
  11770. svr.wait_until_ready();
  11771. // What follows the body would be read as the next request.
  11772. Client cli(HOST, port);
  11773. auto res = cli.Post(
  11774. "/", 5,
  11775. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11776. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11777. sink.write(data.data(), data.size());
  11778. return true;
  11779. },
  11780. "text/plain");
  11781. ASSERT_FALSE(res);
  11782. EXPECT_EQ(Error::Write, res.error());
  11783. EXPECT_FALSE(smuggled);
  11784. }
  11785. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11786. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11787. // The compressed path builds the whole body before connecting, so this
  11788. // fails client-side and never reaches a server.
  11789. Client cli(HOST, PORT);
  11790. cli.set_compress(true);
  11791. auto res = cli.Post(
  11792. "/", 1024,
  11793. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11794. sink.write("hello", 5);
  11795. sink.done(); // short of the 1024 bytes the request announced
  11796. return true;
  11797. },
  11798. "text/plain");
  11799. ASSERT_FALSE(res);
  11800. EXPECT_EQ(Error::Write, res.error());
  11801. }
  11802. #endif
  11803. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11804. Server svr;
  11805. svr.set_error_handler([](Request const &, Response &res) -> void {
  11806. res.set_chunked_content_provider(
  11807. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11808. sink.os << "hello";
  11809. sink.os << "world";
  11810. sink.done();
  11811. return true;
  11812. });
  11813. });
  11814. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11815. auto se = detail::scope_exit([&] {
  11816. svr.stop();
  11817. listen_thread.join();
  11818. ASSERT_FALSE(svr.is_running());
  11819. });
  11820. svr.wait_until_ready();
  11821. Client cli("localhost", PORT);
  11822. auto res = cli.Get("/");
  11823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11825. EXPECT_EQ("helloworld", res->body);
  11826. }
  11827. // A body set after a content provider must replace it, not be sent through it.
  11828. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11829. Server svr;
  11830. svr.set_mount_point("/", "./www");
  11831. svr.set_file_request_handler([](const Request &req, Response &res) {
  11832. if (req.path == "/dir/test.html") {
  11833. res.status = StatusCode::Forbidden_403;
  11834. res.set_content(std::string(5000, 'D'), "text/plain");
  11835. } else if (req.path == "/file") {
  11836. res.status = StatusCode::Forbidden_403;
  11837. res.body = "Denied";
  11838. }
  11839. });
  11840. auto port = svr.bind_to_any_port(HOST);
  11841. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11842. auto se = detail::scope_exit([&] {
  11843. svr.stop();
  11844. t.join();
  11845. ASSERT_FALSE(svr.is_running());
  11846. });
  11847. svr.wait_until_ready();
  11848. Client cli(HOST, port);
  11849. {
  11850. auto res = cli.Get("/dir/test.html");
  11851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11852. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11853. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11854. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11855. }
  11856. {
  11857. auto res = cli.Get("/file");
  11858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11859. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11860. EXPECT_EQ("Denied", res->body);
  11861. }
  11862. {
  11863. auto res = cli.Get("/dir/index.html");
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ(StatusCode::OK_200, res->status);
  11866. EXPECT_EQ(0U, res->body.find("<html>"));
  11867. }
  11868. }
  11869. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11870. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11871. Server svr;
  11872. std::vector<bool> released;
  11873. std::mutex released_mutex;
  11874. auto releaser = [&](bool success) {
  11875. std::lock_guard<std::mutex> guard(released_mutex);
  11876. released.push_back(success);
  11877. };
  11878. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11879. return sink.write(&"hello"[offset], length);
  11880. };
  11881. svr.Get("/sized", [&](const Request &, Response &res) {
  11882. res.status = StatusCode::NotFound_404;
  11883. res.set_content_provider(5, "text/plain", provider, releaser);
  11884. });
  11885. svr.Get("/chunked", [&](const Request &, Response &res) {
  11886. res.status = StatusCode::ServiceUnavailable_503;
  11887. res.set_chunked_content_provider(
  11888. "text/plain",
  11889. [](size_t, DataSink &sink) {
  11890. sink.os << "chunk";
  11891. sink.done();
  11892. return true;
  11893. },
  11894. releaser);
  11895. });
  11896. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11897. res.set_content_provider(5, "text/plain", provider, releaser);
  11898. throw std::runtime_error("after the provider");
  11899. });
  11900. svr.set_error_handler([](const Request &req, Response &res) {
  11901. // Leave the exception handler's content to it.
  11902. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11903. res.set_content(std::string(1000, 'E'), "text/html");
  11904. return Server::HandlerResponse::Handled;
  11905. });
  11906. svr.set_exception_handler(
  11907. [](const Request &, Response &res, std::exception_ptr) {
  11908. res.status = StatusCode::InternalServerError_500;
  11909. res.set_content(std::string(1000, 'X'), "text/html");
  11910. });
  11911. auto port = svr.bind_to_any_port(HOST);
  11912. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11913. auto se = detail::scope_exit([&] {
  11914. svr.stop();
  11915. t.join();
  11916. ASSERT_FALSE(svr.is_running());
  11917. });
  11918. svr.wait_until_ready();
  11919. Client cli(HOST, port);
  11920. {
  11921. auto res = cli.Get("/sized");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11924. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11925. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11926. }
  11927. {
  11928. auto res = cli.Get("/chunked");
  11929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11930. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11931. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11932. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11933. }
  11934. {
  11935. auto res = cli.Get("/throw");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11938. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11939. }
  11940. std::lock_guard<std::mutex> guard(released_mutex);
  11941. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11942. }
  11943. #endif
  11944. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11945. Server svr;
  11946. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11947. return sink.write(&"abc"[offset], length);
  11948. };
  11949. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11950. res.set_file_content("./www/dir/test.html");
  11951. res.set_content("body", "text/plain");
  11952. });
  11953. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11954. res.set_content(std::string(100, 'B'), "text/plain");
  11955. res.set_file_content("./www/dir/test.html");
  11956. });
  11957. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11958. res.set_content(std::string(100, 'B'), "text/plain");
  11959. res.set_content_provider(3, "text/x-provider", abc);
  11960. });
  11961. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11962. res.set_content_provider(3, "text/x-provider", abc);
  11963. res.set_content(std::string(100, 'B'), "text/plain");
  11964. });
  11965. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11966. res.set_content_provider(3, "text/x-provider", abc);
  11967. res.set_file_content("./www/dir/test.html", "text/x-file");
  11968. });
  11969. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11970. res.set_file_content("./www/dir/test.html");
  11971. res.set_header("Content-Type", "text/x-handler");
  11972. });
  11973. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11974. res.set_content_provider(3, "text/plain", abc);
  11975. res.body = "direct";
  11976. });
  11977. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11978. res.set_file_content("./www/dir/test.html");
  11979. res.body = "direct";
  11980. });
  11981. auto port = svr.bind_to_any_port(HOST);
  11982. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11983. auto se = detail::scope_exit([&] {
  11984. svr.stop();
  11985. t.join();
  11986. ASSERT_FALSE(svr.is_running());
  11987. });
  11988. svr.wait_until_ready();
  11989. Client cli(HOST, port);
  11990. auto expect_body = [&](const char *path, const std::string &body,
  11991. const std::string &type) {
  11992. // Uncompressed, so Content-Length can be compared with the body.
  11993. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11994. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11995. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11996. EXPECT_EQ(body, res->body) << path;
  11997. EXPECT_EQ(std::to_string(body.size()),
  11998. res->get_header_value("Content-Length"))
  11999. << path;
  12000. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12001. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12002. };
  12003. expect_body("/file-then-body", "body", "text/plain");
  12004. expect_body("/body-then-file", "test.html", "text/html");
  12005. expect_body("/body-then-provider", "abc", "text/x-provider");
  12006. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12007. expect_body("/provider-then-file", "test.html", "text/x-file");
  12008. expect_body("/file-then-header", "test.html", "text/x-handler");
  12009. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12010. expect_body("/file-then-direct-body", "direct", "text/plain");
  12011. // Ranges are checked against the body, not the dropped provider.
  12012. {
  12013. auto res = cli.Get("/provider-then-direct-body",
  12014. Headers{{make_range_header({{1, 2}})}});
  12015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12016. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12017. EXPECT_EQ("ir", res->body);
  12018. }
  12019. {
  12020. auto res = cli.Get("/file-then-direct-body",
  12021. Headers{{make_range_header({{7, 8}})}});
  12022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12023. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12024. }
  12025. }
  12026. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12027. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12028. const char *path = "./truncated_while_served.txt";
  12029. const size_t size = 32 * 1024 * 1024;
  12030. {
  12031. std::ofstream f(path, std::ios::binary);
  12032. f << std::string(size, 'x');
  12033. }
  12034. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12035. // Over TLS, where the bytes are encrypted in this process rather than
  12036. // copied by send().
  12037. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12038. svr.Get("/file", [&](const Request &, Response &res) {
  12039. res.set_file_content(path, "text/plain");
  12040. });
  12041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. thread.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. });
  12047. svr.wait_until_ready();
  12048. // The file shrinks once the first bytes are in, as a rewrite in place
  12049. // would, and reading the mapping past its new end used to raise SIGBUS.
  12050. SSLClient cli(HOST, PORT);
  12051. cli.enable_server_certificate_verification(false);
  12052. size_t received = 0;
  12053. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12054. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12055. received += len;
  12056. return true;
  12057. });
  12058. EXPECT_FALSE(res);
  12059. EXPECT_LT(received, size);
  12060. }
  12061. #endif
  12062. // Forward declaration (see the base64_encode note).
  12063. namespace httplib {
  12064. namespace detail {
  12065. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12066. const std::string &content_type,
  12067. EncodingType encoding);
  12068. } // namespace detail
  12069. } // namespace httplib
  12070. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12071. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12072. ASSERT_TRUE(mm->is_open());
  12073. Response res;
  12074. detail::set_file_content_provider(res, mm, "text/html",
  12075. detail::EncodingType::None);
  12076. std::string out;
  12077. DataSink sink;
  12078. sink.write = [&](const char *d, size_t l) {
  12079. out.append(d, l);
  12080. return true;
  12081. };
  12082. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12083. EXPECT_EQ("test.html", out);
  12084. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12085. EXPECT_EQ("test.html", out);
  12086. }
  12087. TEST(LongPollingTest, ClientCloseDetection) {
  12088. Server svr;
  12089. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12090. res.set_chunked_content_provider(
  12091. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12092. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12093. sink.os << "hello";
  12094. auto count = 10;
  12095. while (count > 0 && sink.is_writable()) {
  12096. this_thread::sleep_for(chrono::milliseconds(10));
  12097. count--;
  12098. }
  12099. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12100. return true;
  12101. });
  12102. });
  12103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12104. auto se = detail::scope_exit([&] {
  12105. svr.stop();
  12106. listen_thread.join();
  12107. ASSERT_FALSE(svr.is_running());
  12108. });
  12109. svr.wait_until_ready();
  12110. Client cli("localhost", PORT);
  12111. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12112. EXPECT_EQ("hello", string(data, data_length));
  12113. return false; // close the socket immediately.
  12114. });
  12115. ASSERT_FALSE(res);
  12116. }
  12117. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12118. Server svr;
  12119. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12120. res.set_chunked_content_provider(
  12121. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12122. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12123. sink.os << "hello";
  12124. EXPECT_TRUE(sink.os.good());
  12125. // Wait for the client to close the connection
  12126. auto count = 10;
  12127. while (count > 0 && sink.is_writable()) {
  12128. this_thread::sleep_for(chrono::milliseconds(10));
  12129. count--;
  12130. }
  12131. // After client disconnect, write repeatedly until the socket
  12132. // write actually fails (small writes may be absorbed by the
  12133. // kernel buffer)
  12134. std::string chunk(1024, 'x');
  12135. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12136. sink.os << chunk;
  12137. }
  12138. EXPECT_TRUE(sink.os.fail());
  12139. return true;
  12140. });
  12141. });
  12142. auto port = svr.bind_to_any_port("localhost");
  12143. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12144. auto se = detail::scope_exit([&] {
  12145. svr.stop();
  12146. listen_thread.join();
  12147. ASSERT_FALSE(svr.is_running());
  12148. });
  12149. svr.wait_until_ready();
  12150. Client cli("localhost", port);
  12151. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12152. EXPECT_EQ("hello", string(data, data_length));
  12153. return false; // close the socket immediately.
  12154. });
  12155. ASSERT_FALSE(res);
  12156. }
  12157. TEST(GetWithParametersTest, GetWithParameters) {
  12158. Server svr;
  12159. svr.Get("/", [&](const Request &req, Response &) {
  12160. EXPECT_EQ("world", req.get_param_value("hello"));
  12161. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12162. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12163. });
  12164. svr.Get("/params", [&](const Request &req, Response &) {
  12165. EXPECT_EQ("world", req.get_param_value("hello"));
  12166. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12167. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12168. });
  12169. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12170. EXPECT_EQ("resource-id", req.matches[1]);
  12171. EXPECT_EQ("foo", req.get_param_value("param1"));
  12172. EXPECT_EQ("bar", req.get_param_value("param2"));
  12173. });
  12174. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12175. EXPECT_EQ("user-id", req.path_params.at("id"));
  12176. EXPECT_EQ("foo", req.get_param_value("param1"));
  12177. EXPECT_EQ("bar", req.get_param_value("param2"));
  12178. });
  12179. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12180. auto se = detail::scope_exit([&] {
  12181. svr.stop();
  12182. listen_thread.join();
  12183. ASSERT_FALSE(svr.is_running());
  12184. });
  12185. svr.wait_until_ready();
  12186. {
  12187. Client cli(HOST, PORT);
  12188. Params params;
  12189. params.emplace("hello", "world");
  12190. params.emplace("hello2", "world2");
  12191. params.emplace("hello3", "world3");
  12192. auto res = cli.Get("/", params, Headers{});
  12193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12194. EXPECT_EQ(StatusCode::OK_200, res->status);
  12195. }
  12196. {
  12197. Client cli(HOST, PORT);
  12198. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12200. EXPECT_EQ(StatusCode::OK_200, res->status);
  12201. }
  12202. {
  12203. Client cli(HOST, PORT);
  12204. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12206. EXPECT_EQ(StatusCode::OK_200, res->status);
  12207. }
  12208. {
  12209. Client cli(HOST, PORT);
  12210. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12212. EXPECT_EQ(StatusCode::OK_200, res->status);
  12213. }
  12214. }
  12215. TEST(GetWithParametersTest, GetWithParameters2) {
  12216. Server svr;
  12217. svr.Get("/", [&](const Request &req, Response &res) {
  12218. auto text = req.get_param_value("hello");
  12219. res.set_content(text, "text/plain");
  12220. });
  12221. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12222. auto se = detail::scope_exit([&] {
  12223. svr.stop();
  12224. listen_thread.join();
  12225. ASSERT_FALSE(svr.is_running());
  12226. });
  12227. svr.wait_until_ready();
  12228. Client cli("localhost", PORT);
  12229. Params params;
  12230. params.emplace("hello", "world");
  12231. std::string body;
  12232. auto res = cli.Get("/", params, Headers{},
  12233. [&](const char *data, size_t data_length) {
  12234. body.append(data, data_length);
  12235. return true;
  12236. });
  12237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12238. EXPECT_EQ(StatusCode::OK_200, res->status);
  12239. EXPECT_EQ("world", body);
  12240. }
  12241. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12242. Server svr;
  12243. svr.Get("/search", [&](const Request &req, Response &res) {
  12244. auto q = req.get_param_value("q");
  12245. res.set_content(q, "text/plain");
  12246. });
  12247. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12248. auto se = detail::scope_exit([&] {
  12249. svr.stop();
  12250. listen_thread.join();
  12251. ASSERT_FALSE(svr.is_running());
  12252. });
  12253. svr.wait_until_ready();
  12254. Client cli("localhost", PORT);
  12255. // Verify that Get(path, params) works without requiring Headers argument
  12256. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12258. EXPECT_EQ(StatusCode::OK_200, res->status);
  12259. EXPECT_EQ("cpp-httplib", res->body);
  12260. }
  12261. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12262. auto host = "httpbingo.org";
  12263. auto path = std::string{"/range/32"};
  12264. #ifdef CPPHTTPLIB_SSL_ENABLED
  12265. SSLClient cli(host);
  12266. #else
  12267. Client cli(host);
  12268. #endif
  12269. cli.set_default_headers({make_range_header({{1, 10}})});
  12270. cli.set_connection_timeout(5);
  12271. {
  12272. auto res = cli.Get(path);
  12273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12274. EXPECT_EQ("bcdefghijk", res->body);
  12275. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12276. }
  12277. {
  12278. auto res = cli.Get(path);
  12279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12280. EXPECT_EQ("bcdefghijk", res->body);
  12281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12282. }
  12283. }
  12284. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12285. Server svr;
  12286. svr.set_default_headers({{"Hello", "World"}});
  12287. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12288. res.set_content("ok", "text/plain");
  12289. });
  12290. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12291. auto se = detail::scope_exit([&] {
  12292. svr.stop();
  12293. listen_thread.join();
  12294. ASSERT_FALSE(svr.is_running());
  12295. });
  12296. svr.wait_until_ready();
  12297. Client cli("localhost", PORT);
  12298. auto res = cli.Get("/");
  12299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12300. EXPECT_EQ(StatusCode::OK_200, res->status);
  12301. EXPECT_EQ("ok", res->body);
  12302. EXPECT_EQ("World", res->get_header_value("Hello"));
  12303. }
  12304. #ifdef CPPHTTPLIB_SSL_ENABLED
  12305. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12307. ASSERT_TRUE(svr.is_valid());
  12308. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12309. std::this_thread::sleep_for(std::chrono::seconds(2));
  12310. res.set_content("a", "text/plain");
  12311. });
  12312. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12313. res.set_content("b", "text/plain");
  12314. });
  12315. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12316. auto se = detail::scope_exit([&] {
  12317. svr.stop();
  12318. listen_thread.join();
  12319. ASSERT_FALSE(svr.is_running());
  12320. });
  12321. svr.wait_until_ready();
  12322. SSLClient cli("localhost", PORT);
  12323. cli.enable_server_certificate_verification(false);
  12324. cli.set_keep_alive(true);
  12325. cli.set_read_timeout(std::chrono::seconds(1));
  12326. auto resa = cli.Get("/a");
  12327. ASSERT_TRUE(!resa);
  12328. EXPECT_EQ(Error::Read, resa.error());
  12329. auto resb = cli.Get("/b");
  12330. ASSERT_TRUE(resb);
  12331. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12332. EXPECT_EQ("b", resb->body);
  12333. }
  12334. // Closing an idle keep-alive connection sends close_notify and returns. The
  12335. // server must not wait for the client's close_notify: an idle client never
  12336. // sends one, so the worker would be held until the read timeout expires, and
  12337. // stop() would wait for it.
  12338. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12340. ASSERT_TRUE(svr.is_valid());
  12341. svr.set_keep_alive_timeout(1);
  12342. svr.set_read_timeout(10, 0);
  12343. svr.Get("/", [](const Request &, Response &res) {
  12344. res.set_content("ok", "text/plain");
  12345. });
  12346. auto port = svr.bind_to_any_port(HOST);
  12347. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12348. auto se = detail::scope_exit([&] {
  12349. if (listen_thread.joinable()) {
  12350. svr.stop();
  12351. listen_thread.join();
  12352. }
  12353. });
  12354. svr.wait_until_ready();
  12355. SSLClient cli(HOST, port);
  12356. cli.enable_server_certificate_verification(false);
  12357. cli.set_keep_alive(true);
  12358. auto res = cli.Get("/");
  12359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12360. EXPECT_EQ(StatusCode::OK_200, res->status);
  12361. // Stay idle past the keep-alive timeout so the server closes the connection.
  12362. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12363. auto start = std::chrono::steady_clock::now();
  12364. svr.stop();
  12365. listen_thread.join();
  12366. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12367. std::chrono::steady_clock::now() - start)
  12368. .count();
  12369. EXPECT_LT(elapsed, 3000);
  12370. }
  12371. #endif
  12372. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12373. protected:
  12374. ServerTestWithAI_PASSIVE()
  12375. : cli_(HOST, PORT)
  12376. #ifdef CPPHTTPLIB_SSL_ENABLED
  12377. ,
  12378. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12379. #endif
  12380. {
  12381. #ifdef CPPHTTPLIB_SSL_ENABLED
  12382. cli_.enable_server_certificate_verification(false);
  12383. #endif
  12384. }
  12385. virtual void SetUp() {
  12386. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12387. res.set_content("Hello World!", "text/plain");
  12388. });
  12389. t_ = thread(
  12390. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12391. svr_.wait_until_ready();
  12392. }
  12393. virtual void TearDown() {
  12394. svr_.stop();
  12395. t_.join();
  12396. }
  12397. #ifdef CPPHTTPLIB_SSL_ENABLED
  12398. SSLClient cli_;
  12399. SSLServer svr_;
  12400. #else
  12401. Client cli_;
  12402. Server svr_;
  12403. #endif
  12404. thread t_;
  12405. };
  12406. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12407. auto res = cli_.Get("/hi");
  12408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12409. EXPECT_EQ(StatusCode::OK_200, res->status);
  12410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12411. EXPECT_EQ("Hello World!", res->body);
  12412. }
  12413. class ServerUpDownTest : public ::testing::Test {
  12414. protected:
  12415. ServerUpDownTest() : cli_(HOST, PORT) {}
  12416. virtual void SetUp() {
  12417. t_ = thread([&]() {
  12418. svr_.bind_to_any_port(HOST);
  12419. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12420. ASSERT_TRUE(svr_.listen_after_bind());
  12421. });
  12422. svr_.wait_until_ready();
  12423. }
  12424. virtual void TearDown() {
  12425. svr_.stop();
  12426. t_.join();
  12427. }
  12428. Client cli_;
  12429. Server svr_;
  12430. thread t_;
  12431. };
  12432. TEST_F(ServerUpDownTest, QuickStartStop) {
  12433. // Should not crash, especially when run with
  12434. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12435. }
  12436. class PayloadMaxLengthTest : public ::testing::Test {
  12437. protected:
  12438. PayloadMaxLengthTest()
  12439. : cli_(HOST, PORT)
  12440. #ifdef CPPHTTPLIB_SSL_ENABLED
  12441. ,
  12442. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12443. #endif
  12444. {
  12445. #ifdef CPPHTTPLIB_SSL_ENABLED
  12446. cli_.enable_server_certificate_verification(false);
  12447. #endif
  12448. }
  12449. virtual void SetUp() {
  12450. svr_.set_payload_max_length(8);
  12451. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12452. res.set_content("test", "text/plain");
  12453. });
  12454. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12455. svr_.wait_until_ready();
  12456. }
  12457. virtual void TearDown() {
  12458. svr_.stop();
  12459. t_.join();
  12460. }
  12461. #ifdef CPPHTTPLIB_SSL_ENABLED
  12462. SSLClient cli_;
  12463. SSLServer svr_;
  12464. #else
  12465. Client cli_;
  12466. Server svr_;
  12467. #endif
  12468. thread t_;
  12469. };
  12470. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12471. auto res = cli_.Post("/test", "123456789", "text/plain");
  12472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12473. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12474. res = cli_.Post("/test", "12345678", "text/plain");
  12475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12476. EXPECT_EQ(StatusCode::OK_200, res->status);
  12477. }
  12478. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12479. // Test chunked encoding with payload exceeding the 8-byte limit
  12480. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12481. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12483. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12484. }
  12485. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12486. // Test chunked encoding with payload within the 8-byte limit
  12487. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12488. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12490. EXPECT_EQ(StatusCode::OK_200, res->status);
  12491. }
  12492. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12493. // Test using send_request to send chunked data exceeding payload limit
  12494. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12495. "Host: " +
  12496. std::string(HOST) + ":" + std::to_string(PORT) +
  12497. "\r\n"
  12498. "Transfer-Encoding: chunked\r\n"
  12499. "Connection: close\r\n"
  12500. "\r\n"
  12501. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12502. "0123456789\r\n"
  12503. "0\r\n" // End chunk
  12504. "\r\n";
  12505. std::string response;
  12506. bool result = send_request(1, chunked_request, &response);
  12507. if (!result) {
  12508. // If send_request fails, it might be because the server closed the
  12509. // connection due to payload limit enforcement, which is acceptable
  12510. SUCCEED()
  12511. << "Server rejected oversized chunked request (connection closed)";
  12512. } else {
  12513. // If we got a response, check if it's an error response or connection was
  12514. // closed early Short response length indicates connection was closed due to
  12515. // payload limit
  12516. if (response.length() <= 10) {
  12517. SUCCEED() << "Server closed connection for oversized chunked request";
  12518. } else {
  12519. // Check for error status codes
  12520. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12521. response.find("Payload Too Large") != std::string::npos ||
  12522. response.find("400") != std::string::npos);
  12523. }
  12524. }
  12525. }
  12526. class LargePayloadMaxLengthTest : public ::testing::Test {
  12527. protected:
  12528. LargePayloadMaxLengthTest()
  12529. : cli_(HOST, PORT)
  12530. #ifdef CPPHTTPLIB_SSL_ENABLED
  12531. ,
  12532. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12533. #endif
  12534. {
  12535. #ifdef CPPHTTPLIB_SSL_ENABLED
  12536. cli_.enable_server_certificate_verification(false);
  12537. #endif
  12538. }
  12539. virtual void SetUp() {
  12540. // Set 10MB payload limit
  12541. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12542. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12543. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12544. res.set_content("Large payload test", "text/plain");
  12545. });
  12546. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12547. svr_.wait_until_ready();
  12548. }
  12549. virtual void TearDown() {
  12550. svr_.stop();
  12551. t_.join();
  12552. }
  12553. #ifdef CPPHTTPLIB_SSL_ENABLED
  12554. SSLClient cli_;
  12555. SSLServer svr_;
  12556. #else
  12557. Client cli_;
  12558. Server svr_;
  12559. #endif
  12560. thread t_;
  12561. };
  12562. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12563. // Test chunked encoding with payload within 10MB limit
  12564. std::string medium_payload(5 * 1024 * 1024,
  12565. 'A'); // 5MB payload, within 10MB limit
  12566. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12568. EXPECT_EQ(StatusCode::OK_200, res->status);
  12569. }
  12570. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12571. // Test chunked encoding with payload exceeding 10MB limit
  12572. std::string large_payload(12 * 1024 * 1024,
  12573. 'B'); // 12MB payload, exceeds 10MB limit
  12574. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12575. // Server may either return 413 or close the connection
  12576. if (res) {
  12577. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12578. } else {
  12579. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12580. }
  12581. }
  12582. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12583. Server svr;
  12584. svr.Get("/", [](const Request &, Response &res) {
  12585. // Claims the most the client accepts, far more than it sends, then drops
  12586. // the connection.
  12587. res.set_content_provider(std::string().max_size(), "text/plain",
  12588. [](size_t, size_t, DataSink &sink) {
  12589. sink.write("abc", 3);
  12590. return false;
  12591. });
  12592. });
  12593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12594. auto se = detail::scope_exit([&] {
  12595. svr.stop();
  12596. thread.join();
  12597. ASSERT_FALSE(svr.is_running());
  12598. });
  12599. svr.wait_until_ready();
  12600. Client cli(HOST, PORT);
  12601. cli.set_payload_max_length(0);
  12602. EXPECT_FALSE(cli.Get("/"));
  12603. }
  12604. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12605. // Stream API does, not as a plain read failure
  12606. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12607. Server svr;
  12608. svr.Get("/big", [](const Request &, Response &res) {
  12609. res.set_content(std::string(100000, 'b'), "text/plain");
  12610. });
  12611. auto port = svr.bind_to_any_port(HOST);
  12612. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12613. auto se = detail::scope_exit([&] {
  12614. svr.stop();
  12615. thread.join();
  12616. });
  12617. svr.wait_until_ready();
  12618. Client cli(HOST, port);
  12619. cli.set_payload_max_length(1000);
  12620. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12621. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12622. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12623. [](const char *, size_t) { return true; });
  12624. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12625. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12626. // Small on the wire, over the limit once decompressed
  12627. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12628. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12629. #endif
  12630. }
  12631. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12632. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12633. // path.
  12634. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12635. Server svr;
  12636. const size_t LIMIT = 64 * 1024; // 64KB
  12637. svr.set_payload_max_length(LIMIT);
  12638. size_t total = 0;
  12639. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12640. const ContentReader &content_reader) {
  12641. content_reader([&](const char * /*data*/, size_t len) {
  12642. total += len;
  12643. return true;
  12644. });
  12645. res.status = 200;
  12646. res.set_content("stream_ok", "text/plain");
  12647. });
  12648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12649. auto se = detail::scope_exit([&] {
  12650. svr.stop();
  12651. thread.join();
  12652. ASSERT_FALSE(svr.is_running());
  12653. });
  12654. svr.wait_until_ready();
  12655. // Prepare 256KB raw data and gzip-compress it
  12656. std::string raw(256 * 1024, 'A');
  12657. std::string gz;
  12658. {
  12659. z_stream zs{};
  12660. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12661. Z_DEFAULT_STRATEGY);
  12662. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12663. zs.avail_in = static_cast<uInt>(raw.size());
  12664. char outbuf[4096];
  12665. int ret;
  12666. do {
  12667. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12668. zs.avail_out = sizeof(outbuf);
  12669. ret = deflate(&zs, Z_FINISH);
  12670. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12671. } while (ret != Z_STREAM_END);
  12672. deflateEnd(&zs);
  12673. }
  12674. Client cli(HOST, PORT);
  12675. cli.set_connection_timeout(std::chrono::seconds(5));
  12676. Headers headers = {{"Content-Encoding", "gzip"}};
  12677. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12678. "application/octet-stream");
  12679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12680. // Server must reject oversized decompressed payloads with 413.
  12681. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12682. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12683. EXPECT_LE(total, LIMIT);
  12684. }
  12685. #endif
  12686. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12687. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12688. // the payload must be passed through untouched instead of being rejected.
  12689. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12690. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12691. Server svr;
  12692. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12693. res.set_content(body, "image/jpeg");
  12694. res.set_header("Content-Encoding", "UTF-8");
  12695. });
  12696. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12697. res.set_content(body, "image/jpeg");
  12698. res.set_header("Content-Encoding", "identity");
  12699. });
  12700. svr.Post("/echo", [](const Request &req, Response &res) {
  12701. res.set_content(req.body, "image/jpeg");
  12702. });
  12703. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12704. auto se = detail::scope_exit([&] {
  12705. svr.stop();
  12706. t.join();
  12707. ASSERT_FALSE(svr.is_running());
  12708. });
  12709. svr.wait_until_ready();
  12710. Client cli(HOST, PORT);
  12711. {
  12712. auto res = cli.Get("/image");
  12713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12714. EXPECT_EQ(StatusCode::OK_200, res->status);
  12715. EXPECT_EQ(body, res->body);
  12716. }
  12717. {
  12718. auto res = cli.Get("/identity");
  12719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12720. EXPECT_EQ(StatusCode::OK_200, res->status);
  12721. EXPECT_EQ(body, res->body);
  12722. }
  12723. {
  12724. // The same applies to a request body reaching the server.
  12725. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12726. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12728. EXPECT_EQ(StatusCode::OK_200, res->status);
  12729. EXPECT_EQ(body, res->body);
  12730. }
  12731. }
  12732. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12733. // gzip-encoded response even when the build has no zlib support.
  12734. static const char GZIPPED_HELLO_WORLD[] = {
  12735. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12736. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12737. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12738. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12739. // A content coding is a whole token, not something the field value merely
  12740. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12741. // as "fibre" look like Brotli, and turned a multi-coding value like
  12742. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12743. // it was never meant to see.
  12744. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12745. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12746. Server svr;
  12747. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12748. res.set_content(body, "image/jpeg");
  12749. res.set_header("Content-Encoding", "fibre");
  12750. });
  12751. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12752. res.set_content(body, "image/jpeg");
  12753. res.set_header("Content-Encoding", "gzip, br");
  12754. });
  12755. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12756. res.set_content(body, "image/jpeg");
  12757. res.set_header("Content-Encoding", "x-zstd-ish");
  12758. });
  12759. auto port = svr.bind_to_any_port(HOST);
  12760. thread t = thread([&]() { svr.listen_after_bind(); });
  12761. auto se = detail::scope_exit([&] {
  12762. svr.stop();
  12763. t.join();
  12764. ASSERT_FALSE(svr.is_running());
  12765. });
  12766. svr.wait_until_ready();
  12767. Client cli(HOST, port);
  12768. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12769. auto res = cli.Get(path);
  12770. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12771. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12772. // Not a coding we recognize, so the payload comes back untouched
  12773. EXPECT_EQ(body, res->body) << path;
  12774. }
  12775. }
  12776. // A content coding cpp-httplib recognizes but was not built with must be
  12777. // reported as such. Handing the still-compressed payload back to the caller
  12778. // would silently corrupt it.
  12779. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12780. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12781. Server svr;
  12782. // "image/jpeg" keeps the server from applying a content coding of its own,
  12783. // so the hand-crafted Content-Encoding below survives.
  12784. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12785. res.set_content(gzipped, "image/jpeg");
  12786. res.set_header("Content-Encoding", "gzip");
  12787. });
  12788. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12789. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12790. res.set_content(gzipped, "image/jpeg");
  12791. res.set_header("Content-Encoding", "GZIP");
  12792. });
  12793. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12794. auto se = detail::scope_exit([&] {
  12795. svr.stop();
  12796. t.join();
  12797. ASSERT_FALSE(svr.is_running());
  12798. });
  12799. svr.wait_until_ready();
  12800. Client cli(HOST, PORT);
  12801. {
  12802. auto res = cli.Get("/gzipped");
  12803. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12805. EXPECT_EQ("Hello World!", res->body);
  12806. #else
  12807. ASSERT_FALSE(res);
  12808. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12809. #endif
  12810. }
  12811. {
  12812. // open_stream() must behave the same way.
  12813. auto handle = cli.open_stream("GET", "/gzipped");
  12814. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12815. ASSERT_TRUE(handle.is_valid());
  12816. std::string received;
  12817. char buf[256];
  12818. ssize_t n;
  12819. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12820. received.append(buf, static_cast<size_t>(n));
  12821. }
  12822. EXPECT_EQ("Hello World!", received);
  12823. #else
  12824. EXPECT_FALSE(handle.is_valid());
  12825. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12826. #endif
  12827. }
  12828. {
  12829. // A differently-cased coding must not be mistaken for an unknown one, or
  12830. // the body would be handed back still compressed.
  12831. auto res = cli.Get("/gzipped-uppercase");
  12832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12834. EXPECT_EQ("Hello World!", res->body);
  12835. #else
  12836. ASSERT_FALSE(res);
  12837. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12838. #endif
  12839. }
  12840. }
  12841. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12842. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12843. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12844. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12845. // body a second time and appending a second Content-Encoding field line, so
  12846. // clients that decode one coding per listed value handed back raw gzip bytes.
  12847. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12848. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12849. Server svr;
  12850. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12851. // keeps the server from applying a coding of its own.
  12852. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12853. res.set_content(gzipped, "text/plain");
  12854. res.set_header("Content-Encoding", "gzip");
  12855. });
  12856. auto port = svr.bind_to_any_port(HOST);
  12857. thread t = thread([&]() { svr.listen_after_bind(); });
  12858. auto se = detail::scope_exit([&] {
  12859. svr.stop();
  12860. t.join();
  12861. ASSERT_FALSE(svr.is_running());
  12862. });
  12863. svr.wait_until_ready();
  12864. Client cli(HOST, port);
  12865. Headers headers = {{"Accept-Encoding", "gzip"}};
  12866. auto res = cli.Get("/pre-gzipped", headers);
  12867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12868. EXPECT_EQ(StatusCode::OK_200, res->status);
  12869. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12870. EXPECT_EQ("Hello World!", res->body);
  12871. }
  12872. // set_compress(false) sends every handler response as it is, buffered or
  12873. // streamed
  12874. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12875. const std::string text(1000, 'a');
  12876. Server svr;
  12877. svr.set_compress(false);
  12878. svr.Get("/buffered", [&](const Request &, Response &res) {
  12879. res.set_content(text, "text/plain");
  12880. });
  12881. svr.Get("/streamed", [&](const Request &, Response &res) {
  12882. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12883. sink.write(text.data(), text.size());
  12884. sink.done();
  12885. return true;
  12886. });
  12887. });
  12888. auto port = svr.bind_to_any_port(HOST);
  12889. ASSERT_LT(0, port);
  12890. thread t = thread([&] { svr.listen_after_bind(); });
  12891. auto se = detail::scope_exit([&] {
  12892. svr.stop();
  12893. t.join();
  12894. ASSERT_FALSE(svr.is_running());
  12895. });
  12896. svr.wait_until_ready();
  12897. Client cli(HOST, port);
  12898. cli.set_decompress(false);
  12899. for (auto path : {"/buffered", "/streamed"}) {
  12900. SCOPED_TRACE(path);
  12901. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12903. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12904. EXPECT_EQ(text, res->body);
  12905. }
  12906. }
  12907. // A chunked provider settles its coding where the headers are written and
  12908. // reuses it at write time. Both ends of that have to hold: a handler's own
  12909. // Content-Encoding suppresses the coding, and a response without one is still
  12910. // compressed as it always was.
  12911. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12912. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12913. const std::string plain = "Hello World! Hello World! Hello World!";
  12914. Server svr;
  12915. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12916. res.set_header("Content-Encoding", "gzip");
  12917. res.set_chunked_content_provider(
  12918. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12919. sink.write(gzipped.data(), gzipped.size());
  12920. sink.done();
  12921. return true;
  12922. });
  12923. });
  12924. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12925. res.set_chunked_content_provider(
  12926. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12927. sink.write(plain.data(), plain.size());
  12928. sink.done();
  12929. return true;
  12930. });
  12931. });
  12932. auto port = svr.bind_to_any_port(HOST);
  12933. thread t = thread([&]() { svr.listen_after_bind(); });
  12934. auto se = detail::scope_exit([&] {
  12935. svr.stop();
  12936. t.join();
  12937. ASSERT_FALSE(svr.is_running());
  12938. });
  12939. svr.wait_until_ready();
  12940. Client cli(HOST, port);
  12941. Headers headers = {{"Accept-Encoding", "gzip"}};
  12942. {
  12943. auto res = cli.Get("/pre-gzipped", headers);
  12944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12945. EXPECT_EQ(StatusCode::OK_200, res->status);
  12946. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12947. EXPECT_EQ("Hello World!", res->body);
  12948. }
  12949. {
  12950. auto res = cli.Get("/negotiated", headers);
  12951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12952. EXPECT_EQ(StatusCode::OK_200, res->status);
  12953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12954. EXPECT_EQ(plain, res->body);
  12955. }
  12956. }
  12957. #endif
  12958. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12959. // the same message as the comma-joined one, so both have to be read the same
  12960. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12961. // single gzip coding, and a body the sender says was encoded twice was handed
  12962. // back after one pass, still compressed but presented as decoded.
  12963. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12964. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12965. Server svr;
  12966. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12967. res.set_content(body, "image/jpeg");
  12968. res.headers.emplace("Content-Encoding", "gzip");
  12969. res.headers.emplace("Content-Encoding", "gzip");
  12970. });
  12971. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12972. res.set_content(body, "image/jpeg");
  12973. res.set_header("Content-Encoding", "gzip, gzip");
  12974. });
  12975. auto port = svr.bind_to_any_port(HOST);
  12976. thread t = thread([&]() { svr.listen_after_bind(); });
  12977. auto se = detail::scope_exit([&] {
  12978. svr.stop();
  12979. t.join();
  12980. ASSERT_FALSE(svr.is_running());
  12981. });
  12982. svr.wait_until_ready();
  12983. Client cli(HOST, port);
  12984. // Two codings is not something cpp-httplib decodes, so both representations
  12985. // take the pass-through path rather than one of them being gunzipped once.
  12986. for (const char *path : {"/split", "/joined"}) {
  12987. auto res = cli.Get(path);
  12988. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12989. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12990. EXPECT_EQ(body, res->body) << path;
  12991. }
  12992. }
  12993. // Regression test for DoS vulnerability: a malicious server sending a response
  12994. // without Content-Length header must not cause unbounded memory consumption on
  12995. // the client side. The client should stop reading after a reasonable limit,
  12996. // similar to the server-side set_payload_max_length protection.
  12997. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12998. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12999. #ifndef _WIN32
  13000. signal(SIGPIPE, SIG_IGN);
  13001. #endif
  13002. auto server_thread = std::thread([] {
  13003. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13004. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13005. default_socket_options(srv);
  13006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13007. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13008. sockaddr_in addr{};
  13009. addr.sin_family = AF_INET;
  13010. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13011. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13012. int opt = 1;
  13013. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13014. #ifdef _WIN32
  13015. reinterpret_cast<const char *>(&opt),
  13016. #else
  13017. &opt,
  13018. #endif
  13019. sizeof(opt));
  13020. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13021. ::listen(srv, 1);
  13022. sockaddr_in cli_addr{};
  13023. socklen_t cli_len = sizeof(cli_addr);
  13024. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13025. if (cli != INVALID_SOCKET) {
  13026. char buf[4096];
  13027. ::recv(cli, buf, sizeof(buf), 0);
  13028. // Malicious response: no Content-Length, no chunked encoding
  13029. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13030. "Connection: close\r\n"
  13031. "\r\n";
  13032. ::send(cli,
  13033. #ifdef _WIN32
  13034. static_cast<const char *>(response_header.c_str()),
  13035. static_cast<int>(response_header.size()),
  13036. #else
  13037. response_header.c_str(), response_header.size(),
  13038. #endif
  13039. 0);
  13040. // Send 10MB of data
  13041. std::string chunk(64 * 1024, 'A');
  13042. size_t total_sent = 0;
  13043. while (total_sent < MALICIOUS_DATA_SIZE) {
  13044. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13045. auto sent = ::send(cli,
  13046. #ifdef _WIN32
  13047. static_cast<const char *>(chunk.c_str()),
  13048. static_cast<int>(to_send),
  13049. #else
  13050. chunk.c_str(), to_send,
  13051. #endif
  13052. 0);
  13053. if (sent <= 0) break;
  13054. total_sent += static_cast<size_t>(sent);
  13055. }
  13056. detail::close_socket(cli);
  13057. }
  13058. detail::close_socket(srv);
  13059. });
  13060. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13061. size_t total_read = 0;
  13062. {
  13063. Client cli("127.0.0.1", PORT + 2);
  13064. cli.set_read_timeout(5, 0);
  13065. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13066. auto stream = cli.open_stream("GET", "/malicious");
  13067. ASSERT_TRUE(stream.is_valid());
  13068. char buffer[64 * 1024];
  13069. ssize_t n;
  13070. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13071. total_read += static_cast<size_t>(n);
  13072. }
  13073. } // StreamHandle and Client destroyed here, closing the socket
  13074. server_thread.join();
  13075. // With set_payload_max_length, the client must stop reading before consuming
  13076. // all 10MB. The read loop should be cut off at or near the configured limit.
  13077. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13078. << "Client read " << total_read << " bytes, exceeding the configured "
  13079. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13080. }
  13081. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13082. // the entire response body without truncation.
  13083. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13084. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13085. #ifndef _WIN32
  13086. signal(SIGPIPE, SIG_IGN);
  13087. #endif
  13088. auto server_thread = std::thread([] {
  13089. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13090. default_socket_options(srv);
  13091. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13092. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13093. sockaddr_in addr{};
  13094. addr.sin_family = AF_INET;
  13095. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13096. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13097. int opt = 1;
  13098. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13099. #ifdef _WIN32
  13100. reinterpret_cast<const char *>(&opt),
  13101. #else
  13102. &opt,
  13103. #endif
  13104. sizeof(opt));
  13105. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13106. ::listen(srv, 1);
  13107. sockaddr_in cli_addr{};
  13108. socklen_t cli_len = sizeof(cli_addr);
  13109. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13110. if (cli != INVALID_SOCKET) {
  13111. char buf[4096];
  13112. ::recv(cli, buf, sizeof(buf), 0);
  13113. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13114. "Connection: close\r\n"
  13115. "\r\n";
  13116. ::send(cli,
  13117. #ifdef _WIN32
  13118. static_cast<const char *>(response_header.c_str()),
  13119. static_cast<int>(response_header.size()),
  13120. #else
  13121. response_header.c_str(), response_header.size(),
  13122. #endif
  13123. 0);
  13124. std::string chunk(64 * 1024, 'A');
  13125. size_t total_sent = 0;
  13126. while (total_sent < DATA_SIZE) {
  13127. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13128. auto sent = ::send(cli,
  13129. #ifdef _WIN32
  13130. static_cast<const char *>(chunk.c_str()),
  13131. static_cast<int>(to_send),
  13132. #else
  13133. chunk.c_str(), to_send,
  13134. #endif
  13135. 0);
  13136. if (sent <= 0) break;
  13137. total_sent += static_cast<size_t>(sent);
  13138. }
  13139. #ifdef _WIN32
  13140. ::shutdown(cli, SD_SEND);
  13141. #else
  13142. ::shutdown(cli, SHUT_WR);
  13143. #endif
  13144. // Drain until the client closes its end, ensuring all data is delivered
  13145. char drain[1024];
  13146. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13147. detail::close_socket(cli);
  13148. }
  13149. detail::close_socket(srv);
  13150. });
  13151. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13152. size_t total_read = 0;
  13153. {
  13154. Client cli("127.0.0.1", PORT + 2);
  13155. cli.set_read_timeout(5, 0);
  13156. cli.set_payload_max_length(0); // 0 means no limit
  13157. auto stream = cli.open_stream("GET", "/data");
  13158. ASSERT_TRUE(stream.is_valid());
  13159. char buffer[64 * 1024];
  13160. ssize_t n;
  13161. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13162. total_read += static_cast<size_t>(n);
  13163. }
  13164. }
  13165. server_thread.join();
  13166. EXPECT_EQ(total_read, DATA_SIZE)
  13167. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13168. << " bytes without truncation, but only read " << total_read << " bytes.";
  13169. }
  13170. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13171. // enormous Content-Length must not cause the client to pre-allocate a huge
  13172. // response body buffer. The reservation is capped at payload_max_length_, and
  13173. // the read itself fails when the body exceeds the limit.
  13174. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13175. #ifndef _WIN32
  13176. signal(SIGPIPE, SIG_IGN);
  13177. #endif
  13178. auto server_thread = std::thread([] {
  13179. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13180. default_socket_options(srv);
  13181. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13182. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13183. sockaddr_in addr{};
  13184. addr.sin_family = AF_INET;
  13185. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13186. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13187. int opt = 1;
  13188. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13189. #ifdef _WIN32
  13190. reinterpret_cast<const char *>(&opt),
  13191. #else
  13192. &opt,
  13193. #endif
  13194. sizeof(opt));
  13195. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13196. ::listen(srv, 1);
  13197. sockaddr_in cli_addr{};
  13198. socklen_t cli_len = sizeof(cli_addr);
  13199. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13200. if (cli != INVALID_SOCKET) {
  13201. char buf[4096];
  13202. ::recv(cli, buf, sizeof(buf), 0);
  13203. // Malicious response: claim a 20GB body but send only a tiny payload.
  13204. std::string response = "HTTP/1.1 200 OK\r\n"
  13205. "Content-Length: 20000000000\r\n"
  13206. "\r\n"
  13207. "abc";
  13208. ::send(cli,
  13209. #ifdef _WIN32
  13210. static_cast<const char *>(response.c_str()),
  13211. static_cast<int>(response.size()),
  13212. #else
  13213. response.c_str(), response.size(),
  13214. #endif
  13215. 0);
  13216. detail::close_socket(cli);
  13217. }
  13218. detail::close_socket(srv);
  13219. });
  13220. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13221. {
  13222. Client cli("127.0.0.1", PORT + 2);
  13223. cli.set_read_timeout(5, 0);
  13224. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13225. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13226. // (server claims more bytes than payload_max_length permits), but it must
  13227. // not exhaust memory before getting there.
  13228. auto res = cli.Get("/malicious");
  13229. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13230. }
  13231. server_thread.join();
  13232. }
  13233. // Verify that content_receiver bypasses the default payload_max_length,
  13234. // allowing streaming downloads larger than 100MB without requiring an explicit
  13235. // set_payload_max_length call.
  13236. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13237. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13238. #ifndef _WIN32
  13239. signal(SIGPIPE, SIG_IGN);
  13240. #endif
  13241. auto server_thread = std::thread([] {
  13242. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13243. default_socket_options(srv);
  13244. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13245. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13246. sockaddr_in addr{};
  13247. addr.sin_family = AF_INET;
  13248. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13249. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13250. int opt = 1;
  13251. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13252. #ifdef _WIN32
  13253. reinterpret_cast<const char *>(&opt),
  13254. #else
  13255. &opt,
  13256. #endif
  13257. sizeof(opt));
  13258. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13259. ::listen(srv, 1);
  13260. sockaddr_in cli_addr{};
  13261. socklen_t cli_len = sizeof(cli_addr);
  13262. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13263. if (cli != INVALID_SOCKET) {
  13264. char buf[4096];
  13265. ::recv(cli, buf, sizeof(buf), 0);
  13266. // Response with Content-Length larger than default 100MB limit
  13267. auto content_length = std::to_string(DATA_SIZE);
  13268. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13269. "Content-Length: " +
  13270. content_length +
  13271. "\r\n"
  13272. "Connection: close\r\n"
  13273. "\r\n";
  13274. ::send(cli,
  13275. #ifdef _WIN32
  13276. static_cast<const char *>(response_header.c_str()),
  13277. static_cast<int>(response_header.size()),
  13278. #else
  13279. response_header.c_str(), response_header.size(),
  13280. #endif
  13281. 0);
  13282. std::string chunk(64 * 1024, 'A');
  13283. size_t total_sent = 0;
  13284. while (total_sent < DATA_SIZE) {
  13285. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13286. auto sent = ::send(cli,
  13287. #ifdef _WIN32
  13288. static_cast<const char *>(chunk.c_str()),
  13289. static_cast<int>(to_send),
  13290. #else
  13291. chunk.c_str(), to_send,
  13292. #endif
  13293. 0);
  13294. if (sent <= 0) break;
  13295. total_sent += static_cast<size_t>(sent);
  13296. }
  13297. detail::close_socket(cli);
  13298. }
  13299. detail::close_socket(srv);
  13300. });
  13301. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13302. size_t total_received = 0;
  13303. {
  13304. Client cli("127.0.0.1", PORT + 2);
  13305. cli.set_read_timeout(10, 0);
  13306. // Do NOT call set_payload_max_length — use the default 100MB limit
  13307. auto res =
  13308. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13309. total_received += data_length;
  13310. return true;
  13311. });
  13312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13313. EXPECT_EQ(StatusCode::OK_200, res->status);
  13314. }
  13315. server_thread.join();
  13316. EXPECT_EQ(total_received, DATA_SIZE)
  13317. << "With content_receiver, the client should read all " << DATA_SIZE
  13318. << " bytes despite the default 100MB payload_max_length, but only read "
  13319. << total_received << " bytes.";
  13320. }
  13321. // Verify that an explicit set_payload_max_length smaller than the response is
  13322. // enforced even when a content_receiver is used.
  13323. TEST(ClientVulnerabilityTest,
  13324. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13325. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13326. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13327. #ifndef _WIN32
  13328. signal(SIGPIPE, SIG_IGN);
  13329. #endif
  13330. auto server_thread = std::thread([] {
  13331. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13332. default_socket_options(srv);
  13333. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13334. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13335. sockaddr_in addr{};
  13336. addr.sin_family = AF_INET;
  13337. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13338. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13339. int opt = 1;
  13340. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13341. #ifdef _WIN32
  13342. reinterpret_cast<const char *>(&opt),
  13343. #else
  13344. &opt,
  13345. #endif
  13346. sizeof(opt));
  13347. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13348. ::listen(srv, 1);
  13349. sockaddr_in cli_addr{};
  13350. socklen_t cli_len = sizeof(cli_addr);
  13351. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13352. if (cli != INVALID_SOCKET) {
  13353. char buf[4096];
  13354. ::recv(cli, buf, sizeof(buf), 0);
  13355. auto content_length = std::to_string(DATA_SIZE);
  13356. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13357. "Content-Length: " +
  13358. content_length +
  13359. "\r\n"
  13360. "Connection: close\r\n"
  13361. "\r\n";
  13362. ::send(cli,
  13363. #ifdef _WIN32
  13364. static_cast<const char *>(response_header.c_str()),
  13365. static_cast<int>(response_header.size()),
  13366. #else
  13367. response_header.c_str(), response_header.size(),
  13368. #endif
  13369. 0);
  13370. std::string chunk(64 * 1024, 'A');
  13371. size_t total_sent = 0;
  13372. while (total_sent < DATA_SIZE) {
  13373. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13374. auto sent = ::send(cli,
  13375. #ifdef _WIN32
  13376. static_cast<const char *>(chunk.c_str()),
  13377. static_cast<int>(to_send),
  13378. #else
  13379. chunk.c_str(), to_send,
  13380. #endif
  13381. 0);
  13382. if (sent <= 0) break;
  13383. total_sent += static_cast<size_t>(sent);
  13384. }
  13385. detail::close_socket(cli);
  13386. }
  13387. detail::close_socket(srv);
  13388. });
  13389. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13390. size_t total_received = 0;
  13391. {
  13392. Client cli("127.0.0.1", PORT + 2);
  13393. cli.set_read_timeout(10, 0);
  13394. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13395. auto res =
  13396. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13397. total_received += data_length;
  13398. return true;
  13399. });
  13400. // Should fail because 200MB exceeds the explicit 150MB limit
  13401. EXPECT_FALSE(res);
  13402. }
  13403. server_thread.join();
  13404. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13405. << "Client with content_receiver should respect the explicit "
  13406. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13407. << total_received << " bytes.";
  13408. }
  13409. // Verify that an explicit set_payload_max_length larger than the response
  13410. // allows the content_receiver to read all data successfully.
  13411. TEST(ClientVulnerabilityTest,
  13412. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13413. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13414. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13415. #ifndef _WIN32
  13416. signal(SIGPIPE, SIG_IGN);
  13417. #endif
  13418. auto server_thread = std::thread([] {
  13419. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13420. default_socket_options(srv);
  13421. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13422. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13423. sockaddr_in addr{};
  13424. addr.sin_family = AF_INET;
  13425. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13426. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13427. int opt = 1;
  13428. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13429. #ifdef _WIN32
  13430. reinterpret_cast<const char *>(&opt),
  13431. #else
  13432. &opt,
  13433. #endif
  13434. sizeof(opt));
  13435. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13436. ::listen(srv, 1);
  13437. sockaddr_in cli_addr{};
  13438. socklen_t cli_len = sizeof(cli_addr);
  13439. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13440. if (cli != INVALID_SOCKET) {
  13441. char buf[4096];
  13442. ::recv(cli, buf, sizeof(buf), 0);
  13443. auto content_length = std::to_string(DATA_SIZE);
  13444. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13445. "Content-Length: " +
  13446. content_length +
  13447. "\r\n"
  13448. "Connection: close\r\n"
  13449. "\r\n";
  13450. ::send(cli,
  13451. #ifdef _WIN32
  13452. static_cast<const char *>(response_header.c_str()),
  13453. static_cast<int>(response_header.size()),
  13454. #else
  13455. response_header.c_str(), response_header.size(),
  13456. #endif
  13457. 0);
  13458. std::string chunk(64 * 1024, 'A');
  13459. size_t total_sent = 0;
  13460. while (total_sent < DATA_SIZE) {
  13461. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13462. auto sent = ::send(cli,
  13463. #ifdef _WIN32
  13464. static_cast<const char *>(chunk.c_str()),
  13465. static_cast<int>(to_send),
  13466. #else
  13467. chunk.c_str(), to_send,
  13468. #endif
  13469. 0);
  13470. if (sent <= 0) break;
  13471. total_sent += static_cast<size_t>(sent);
  13472. }
  13473. #ifdef _WIN32
  13474. ::shutdown(cli, SD_SEND);
  13475. #else
  13476. ::shutdown(cli, SHUT_WR);
  13477. #endif
  13478. char drain[1024];
  13479. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13480. detail::close_socket(cli);
  13481. }
  13482. detail::close_socket(srv);
  13483. });
  13484. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13485. size_t total_received = 0;
  13486. {
  13487. Client cli("127.0.0.1", PORT + 2);
  13488. cli.set_read_timeout(10, 0);
  13489. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13490. auto res =
  13491. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13492. total_received += data_length;
  13493. return true;
  13494. });
  13495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13496. EXPECT_EQ(StatusCode::OK_200, res->status);
  13497. }
  13498. server_thread.join();
  13499. EXPECT_EQ(total_received, DATA_SIZE)
  13500. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13501. << " bytes (larger than " << DATA_SIZE
  13502. << " bytes response), content_receiver should read all data, but only "
  13503. "read "
  13504. << total_received << " bytes.";
  13505. }
  13506. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13507. // Regression test for "zip bomb" attack on the client side: a malicious server
  13508. // sends a small gzip-compressed response that decompresses to a huge payload.
  13509. // The client must enforce payload_max_length on the decompressed size.
  13510. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13511. constexpr size_t DECOMPRESSED_SIZE =
  13512. 10 * 1024 * 1024; // 10MB after decompression
  13513. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13514. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13515. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13516. std::string compressed;
  13517. {
  13518. httplib::detail::gzip_compressor compressor;
  13519. bool ok =
  13520. compressor.compress(uncompressed.data(), uncompressed.size(),
  13521. /*last=*/true, [&](const char *buf, size_t len) {
  13522. compressed.append(buf, len);
  13523. return true;
  13524. });
  13525. ASSERT_TRUE(ok);
  13526. }
  13527. // Sanity: compressed data should be much smaller than the decompressed size
  13528. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13529. #ifndef _WIN32
  13530. signal(SIGPIPE, SIG_IGN);
  13531. #endif
  13532. // Set up the listening socket in the main thread so the server is guaranteed
  13533. // to be ready before the client connects (eliminates race condition).
  13534. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13535. default_socket_options(srv);
  13536. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13537. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13538. sockaddr_in addr{};
  13539. addr.sin_family = AF_INET;
  13540. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13541. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13542. int opt = 1;
  13543. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13544. #ifdef _WIN32
  13545. reinterpret_cast<const char *>(&opt),
  13546. #else
  13547. &opt,
  13548. #endif
  13549. sizeof(opt));
  13550. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13551. ASSERT_EQ(0, ::listen(srv, 1));
  13552. auto server_thread = std::thread([&compressed, srv] {
  13553. sockaddr_in cli_addr{};
  13554. socklen_t cli_len = sizeof(cli_addr);
  13555. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13556. if (cli != INVALID_SOCKET) {
  13557. // Read the full HTTP request (until \r\n\r\n)
  13558. char buf[4096];
  13559. size_t total = 0;
  13560. while (total < sizeof(buf)) {
  13561. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13562. if (n <= 0) break;
  13563. total += static_cast<size_t>(n);
  13564. // Check for end of headers
  13565. if (total >= 4) {
  13566. std::string req(buf, total);
  13567. if (req.find("\r\n\r\n") != std::string::npos) break;
  13568. }
  13569. }
  13570. // Malicious response: gzip-compressed body, no Content-Length
  13571. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13572. "Content-Encoding: gzip\r\n"
  13573. "Connection: close\r\n"
  13574. "\r\n";
  13575. ::send(cli,
  13576. #ifdef _WIN32
  13577. static_cast<const char *>(response_header.c_str()),
  13578. static_cast<int>(response_header.size()),
  13579. #else
  13580. response_header.c_str(), response_header.size(),
  13581. #endif
  13582. 0);
  13583. // Send the compressed payload (small on the wire, huge when decompressed)
  13584. size_t total_sent = 0;
  13585. while (total_sent < compressed.size()) {
  13586. auto to_send = std::min(compressed.size() - total_sent,
  13587. static_cast<size_t>(64 * 1024));
  13588. auto sent =
  13589. ::send(cli,
  13590. #ifdef _WIN32
  13591. static_cast<const char *>(compressed.c_str() + total_sent),
  13592. static_cast<int>(to_send),
  13593. #else
  13594. compressed.c_str() + total_sent, to_send,
  13595. #endif
  13596. 0);
  13597. if (sent <= 0) break;
  13598. total_sent += static_cast<size_t>(sent);
  13599. }
  13600. detail::close_socket(cli);
  13601. }
  13602. });
  13603. auto se = detail::scope_exit([&] {
  13604. detail::close_socket(srv);
  13605. server_thread.join();
  13606. });
  13607. size_t total_decompressed = 0;
  13608. {
  13609. Client cli("127.0.0.1", PORT + 3);
  13610. cli.set_read_timeout(5, 0);
  13611. cli.set_decompress(true);
  13612. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13613. auto stream = cli.open_stream("GET", "/zipbomb");
  13614. ASSERT_TRUE(stream.is_valid());
  13615. char buffer[64 * 1024];
  13616. ssize_t n;
  13617. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13618. total_decompressed += static_cast<size_t>(n);
  13619. }
  13620. }
  13621. // The decompressed size must be capped by payload_max_length. Without
  13622. // protection, the client would decompress the full 10MB from a tiny
  13623. // compressed payload, enabling a zip bomb DoS attack.
  13624. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13625. << "Client decompressed " << total_decompressed
  13626. << " bytes from a gzip response. The decompressed size should be "
  13627. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13628. }
  13629. #endif
  13630. TEST(HostAndPortPropertiesTest, NoSSL) {
  13631. httplib::Client cli("www.google.com", 1234);
  13632. ASSERT_EQ("www.google.com", cli.host());
  13633. ASSERT_EQ(1234, cli.port());
  13634. }
  13635. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13636. httplib::Client cli("www.google.com:1234");
  13637. ASSERT_EQ("www.google.com", cli.host());
  13638. ASSERT_EQ(1234, cli.port());
  13639. }
  13640. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13641. // Port number that overflows int — should not crash, client becomes invalid
  13642. httplib::Client cli("http://www.google.com:99999999999999999999");
  13643. ASSERT_FALSE(cli.is_valid());
  13644. }
  13645. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13646. // Port 99999 exceeds valid range (1-65535) — should not crash
  13647. httplib::Client cli("http://www.google.com:99999");
  13648. ASSERT_FALSE(cli.is_valid());
  13649. auto res = cli.Get("/");
  13650. EXPECT_FALSE(res);
  13651. EXPECT_EQ(Error::Connection, res.error());
  13652. }
  13653. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13654. httplib::Client cli("http://user:pass@localhost:1234");
  13655. ASSERT_FALSE(cli.is_valid());
  13656. EXPECT_FALSE(cli.Get("/"));
  13657. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13658. }
  13659. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13660. httplib::Client cli("http://www.google.com:80abc");
  13661. ASSERT_FALSE(cli.is_valid());
  13662. }
  13663. #ifdef CPPHTTPLIB_SSL_ENABLED
  13664. TEST(HostAndPortPropertiesTest, SSL) {
  13665. httplib::SSLClient cli("www.google.com");
  13666. ASSERT_EQ("www.google.com", cli.host());
  13667. ASSERT_EQ(443, cli.port());
  13668. }
  13669. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13670. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13671. std::string cert;
  13672. read_file(CA_CERT_FILE, cert);
  13673. httplib::SSLClient httplib_client("www.google.com");
  13674. // Load CA store first time
  13675. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13676. // Load CA store second time (update)
  13677. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13678. // Verify client is still valid and can make connections
  13679. httplib_client.enable_server_certificate_verification(true);
  13680. auto res = httplib_client.Get("/");
  13681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13682. // Google may return 200 or 301 depending on various factors
  13683. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13684. res->status == StatusCode::MovedPermanently_301);
  13685. }
  13686. TEST(SSLClientTest, ServerNameIndication_Online) {
  13687. auto host = "httpbingo.org";
  13688. auto path = std::string{"/get"};
  13689. SSLClient cli(host, 443);
  13690. auto res = cli.Get(path);
  13691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13692. ASSERT_EQ(StatusCode::OK_200, res->status);
  13693. }
  13694. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13695. // Use a site that will cause SSL verification failure due to self-signed cert
  13696. SSLClient cli("self-signed.badssl.com", 443);
  13697. cli.enable_server_certificate_verification(true);
  13698. auto res = cli.Get("/");
  13699. ASSERT_TRUE(!res);
  13700. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13701. // Verify backend error is captured for SSLServerVerification
  13702. // This occurs when certificate verification fails
  13703. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13704. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13705. EXPECT_NE(0UL, res.ssl_backend_error());
  13706. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13707. res.ssl_error());
  13708. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13709. #if !defined(_WIN32) || \
  13710. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13711. // On non-Windows or when Windows Schannel is disabled, the error comes
  13712. // from OpenSSL's verification
  13713. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13714. res.ssl_backend_error());
  13715. #endif
  13716. #endif
  13717. }
  13718. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13719. // Use a site where hostname doesn't match the certificate
  13720. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13721. SSLClient cli("wrong.host.badssl.com", 443);
  13722. cli.enable_server_certificate_verification(true);
  13723. cli.enable_server_hostname_verification(true);
  13724. auto res = cli.Get("/");
  13725. ASSERT_TRUE(!res);
  13726. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13727. // Verify backend error is captured for hostname verification failure
  13728. EXPECT_NE(0UL, res.ssl_backend_error());
  13729. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13730. res.ssl_error());
  13731. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13732. #if !defined(_WIN32) || \
  13733. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13734. // On non-Windows or when Windows Schannel is disabled, the error comes
  13735. // from OpenSSL's hostname verification
  13736. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13737. res.ssl_backend_error());
  13738. #endif
  13739. #endif
  13740. }
  13741. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13742. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13743. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13744. SSLClient cli("www.google.com", 443);
  13745. cli.enable_server_certificate_verification(true);
  13746. auto res = cli.Get("/");
  13747. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13748. }
  13749. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13750. SSLClient cli("www.google.com", 443);
  13751. cli.enable_server_certificate_verification(true);
  13752. cli.enable_windows_certificate_verification(false);
  13753. auto res = cli.Get("/");
  13754. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13755. }
  13756. // The server sends an intermediate cross-signed by a root Windows trusts,
  13757. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13758. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13759. SSLClient cli("accounts.spotify.com", 443);
  13760. auto res = cli.Get("/");
  13761. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13762. << " ssl_backend_error=" << res.ssl_backend_error();
  13763. }
  13764. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13765. // policy status, which no backend reports for a self-signed certificate.
  13766. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13767. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13768. ASSERT_TRUE(svr.is_valid());
  13769. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13770. auto se = detail::scope_exit([&] {
  13771. svr.stop();
  13772. t.join();
  13773. ASSERT_FALSE(svr.is_running());
  13774. });
  13775. svr.wait_until_ready();
  13776. SSLClient cli("127.0.0.1", PORT);
  13777. cli.set_connection_timeout(30);
  13778. auto res = cli.Get("/");
  13779. ASSERT_FALSE(res);
  13780. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13781. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13782. }
  13783. #endif
  13784. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13785. Client cli("https://google.com");
  13786. auto res = cli.Get("/");
  13787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13788. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13789. }
  13790. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13791. SSLClient cli("google.com");
  13792. cli.set_ca_cert_path(CA_CERT_FILE);
  13793. auto res = cli.Get("/");
  13794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13795. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13796. }
  13797. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13798. SSLClient cli("google.com");
  13799. cli.enable_server_certificate_verification(true);
  13800. cli.set_ca_cert_path("hello");
  13801. auto res = cli.Get("/");
  13802. ASSERT_TRUE(!res);
  13803. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13804. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13805. // should be set
  13806. EXPECT_EQ(0, res.ssl_error());
  13807. // Verify backend error is captured for SSLLoadingCerts
  13808. // This error occurs when loading CA certificates fails
  13809. EXPECT_NE(0UL, res.ssl_backend_error());
  13810. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13811. // OpenSSL specific error codes:
  13812. // > openssl errstr 0x80000002
  13813. // error:80000002:system library::No such file or directory
  13814. // > openssl errstr 0xA000126
  13815. // error:0A000126:SSL routines::unexpected eof while reading
  13816. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13817. res.ssl_backend_error() == 0xA000126);
  13818. #endif
  13819. }
  13820. TEST(SSLClientTest, ServerCertificateVerification4) {
  13821. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13822. ASSERT_TRUE(svr.is_valid());
  13823. svr.Get("/test", [&](const Request &, Response &res) {
  13824. res.set_content("test", "text/plain");
  13825. svr.stop();
  13826. ASSERT_TRUE(true);
  13827. });
  13828. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13829. auto se = detail::scope_exit([&] {
  13830. t.join();
  13831. ASSERT_FALSE(svr.is_running());
  13832. });
  13833. svr.wait_until_ready();
  13834. SSLClient cli("127.0.0.1", PORT);
  13835. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13836. cli.enable_server_certificate_verification(true);
  13837. cli.set_connection_timeout(30);
  13838. auto res = cli.Get("/test");
  13839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13840. ASSERT_EQ(StatusCode::OK_200, res->status);
  13841. }
  13842. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13843. std::string cert;
  13844. read_file(CA_CERT_FILE, cert);
  13845. SSLClient cli("google.com");
  13846. cli.load_ca_cert_store(cert.data(), cert.size());
  13847. const auto res = cli.Get("/");
  13848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13849. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13850. }
  13851. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13852. // clang-format off
  13853. static constexpr char cert[] =
  13854. "GlobalSign Root CA\n"
  13855. "==================\n"
  13856. "-----BEGIN CERTIFICATE-----\n"
  13857. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13858. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13859. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13860. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13861. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13862. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13863. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13864. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13865. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13866. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13867. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13868. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13869. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13870. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13871. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13872. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13873. "-----END CERTIFICATE-----\n";
  13874. // clang-format on
  13875. SSLClient cli("google.com");
  13876. cli.load_ca_cert_store(cert, sizeof(cert));
  13877. const auto res = cli.Get("/");
  13878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13879. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13880. }
  13881. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13882. SSLClient cli("www.youtube.com");
  13883. cli.set_ca_cert_path(CA_CERT_FILE);
  13884. cli.enable_server_certificate_verification(true);
  13885. cli.set_follow_location(true);
  13886. auto res = cli.Get("/");
  13887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13888. ASSERT_EQ(StatusCode::OK_200, res->status);
  13889. }
  13890. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13891. SSLClient cli("wWw.YouTube.Com");
  13892. cli.set_ca_cert_path(CA_CERT_FILE);
  13893. cli.enable_server_certificate_verification(true);
  13894. cli.enable_server_hostname_verification(true);
  13895. cli.set_follow_location(true);
  13896. auto res = cli.Get("/");
  13897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13898. ASSERT_EQ(StatusCode::OK_200, res->status);
  13899. }
  13900. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13901. SSLClient cli("gOoGlE.COm");
  13902. cli.enable_server_certificate_verification(true);
  13903. cli.enable_server_hostname_verification(true);
  13904. cli.set_follow_location(true);
  13905. auto res = cli.Get("/");
  13906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13907. ASSERT_EQ(StatusCode::OK_200, res->status);
  13908. }
  13909. TEST(SSLClientTest, Issue2004_Online) {
  13910. Client client("https://google.com");
  13911. client.set_follow_location(true);
  13912. auto res = client.Get("/");
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. ASSERT_EQ(StatusCode::OK_200, res->status);
  13915. auto body = res->body;
  13916. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13917. }
  13918. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13919. // Create SSLClient with invalid cert/key to make is_valid() return false
  13920. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13921. "nonexistent_key.pem");
  13922. // is_valid() should be false due to cert loading failure
  13923. ASSERT_FALSE(cli.is_valid());
  13924. auto res = cli.Get("/");
  13925. ASSERT_FALSE(res);
  13926. EXPECT_EQ(Error::SSLConnection, res.error());
  13927. }
  13928. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13929. // Test for Issue #2251: SSL error not properly reported when client cert
  13930. // and key paths are swapped or mismatched
  13931. // This simulates the scenario where user accidentally swaps the cert and key
  13932. // files
  13933. // Using client cert file as private key and vice versa (completely wrong)
  13934. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13935. // Should fail validation due to cert/key mismatch
  13936. ASSERT_FALSE(cli.is_valid());
  13937. // Attempt to make a request should fail with proper error
  13938. auto res = cli.Get("/");
  13939. ASSERT_FALSE(res);
  13940. EXPECT_EQ(Error::SSLConnection, res.error());
  13941. // SSL error should be recorded in the Result object (this is the key fix for
  13942. // Issue #2251)
  13943. auto backend_error = res.ssl_backend_error();
  13944. EXPECT_NE(0u, backend_error);
  13945. }
  13946. // Tests cert/key mismatch detection at the TLS context level
  13947. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13948. // Test that using mismatched cert/key causes connection failure.
  13949. // We verify this at the SSLClient level rather than through internal
  13950. // TLS API functions.
  13951. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13952. cli.enable_server_certificate_verification(false);
  13953. cli.set_connection_timeout(2);
  13954. // The mismatch should cause a connection or handshake error
  13955. auto res = cli.Get("/test");
  13956. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13957. // Either way, the request should fail
  13958. EXPECT_FALSE(res);
  13959. }
  13960. #endif
  13961. #if 0
  13962. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13963. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13964. ASSERT_TRUE(cli != nullptr);
  13965. cli->set_address_family(AF_INET6);
  13966. cli->set_interface("en0");
  13967. auto res = cli->Get("/get");
  13968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13969. ASSERT_EQ(StatusCode::OK_200, res->status);
  13970. }
  13971. #endif
  13972. // Client certificate tests - work with all TLS backends
  13973. #ifdef CPPHTTPLIB_SSL_ENABLED
  13974. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13975. void ClientCertPresent(
  13976. const std::string &client_cert_file,
  13977. const std::string &client_private_key_file,
  13978. const std::string &client_encrypted_private_key_pass = std::string(),
  13979. const ClientCertServerSetup &setup = nullptr) {
  13980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13981. ASSERT_TRUE(svr.is_valid());
  13982. if (setup) { setup(svr); }
  13983. svr.Get("/test", [&](const Request &req, Response &res) {
  13984. res.set_content("test", "text/plain");
  13985. auto cert = req.peer_cert();
  13986. ASSERT_TRUE(static_cast<bool>(cert));
  13987. std::string common_name = cert.subject_cn();
  13988. EXPECT_EQ("Common Name", common_name);
  13989. });
  13990. auto port = svr.bind_to_any_port(HOST);
  13991. ASSERT_LT(0, port);
  13992. thread t = thread([&]() { svr.listen_after_bind(); });
  13993. auto se = detail::scope_exit([&] {
  13994. svr.stop();
  13995. t.join();
  13996. ASSERT_FALSE(svr.is_running());
  13997. });
  13998. svr.wait_until_ready();
  13999. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14000. client_encrypted_private_key_pass);
  14001. cli.enable_server_certificate_verification(false);
  14002. cli.set_connection_timeout(30);
  14003. auto res = cli.Get("/test");
  14004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14005. ASSERT_EQ(StatusCode::OK_200, res->status);
  14006. }
  14007. TEST(SSLClientServerTest, ClientCertPresent) {
  14008. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14009. }
  14010. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14011. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14012. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14013. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14014. }
  14015. // Expects svr, which must require client certificates, to reject a client
  14016. // that has none
  14017. void RejectsClientWithoutCert(SSLServer &svr) {
  14018. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14019. auto port = svr.bind_to_any_port(HOST);
  14020. ASSERT_LT(0, port);
  14021. thread t = thread([&]() { svr.listen_after_bind(); });
  14022. auto se = detail::scope_exit([&] {
  14023. svr.stop();
  14024. t.join();
  14025. ASSERT_FALSE(svr.is_running());
  14026. });
  14027. svr.wait_until_ready();
  14028. SSLClient cli(HOST, port);
  14029. cli.set_connection_timeout(30);
  14030. // Skip the server certificate check, so that the request fails because the
  14031. // client certificate is missing rather than because cert.pem is not trusted
  14032. cli.enable_server_certificate_verification(false);
  14033. auto res = cli.Get("/test");
  14034. ASSERT_FALSE(res);
  14035. // The server rejects the client during the handshake, or on TLS 1.3 right
  14036. // after it, which the client notices on its first write or read
  14037. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14038. res.error() == Error::Write || res.error() == Error::Read)
  14039. << to_string(res.error());
  14040. if (res.error() == Error::SSLConnection) {
  14041. EXPECT_NE(0UL, res.ssl_backend_error());
  14042. }
  14043. // A rejection noticed on the write keeps the TLS error the write hit
  14044. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14045. }
  14046. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14048. ASSERT_TRUE(svr.is_valid());
  14049. if (setup) { setup(svr); }
  14050. RejectsClientWithoutCert(svr);
  14051. }
  14052. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14053. // A server that requires client certificates must keep requiring them after
  14054. // setup changes it, and keep accepting a client that has one
  14055. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14056. ClientCertMissing(setup);
  14057. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14058. setup);
  14059. }
  14060. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14061. ClientCertStillRequired([](SSLServer &svr) {
  14062. ASSERT_TRUE(tls::set_verify_callback(
  14063. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14064. });
  14065. }
  14066. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14067. ClientCertStillRequired([](SSLServer &svr) {
  14068. ASSERT_TRUE(tls::set_verify_callback(
  14069. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14070. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14071. });
  14072. }
  14073. // The client verifies the server certificate during the handshake, so a
  14074. // server that fails the check never gets the client certificate, even when a
  14075. // verifier of the client's own accepts it
  14076. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14077. struct Case {
  14078. const char *trusted_ca;
  14079. const char *host;
  14080. Error error;
  14081. };
  14082. // cert2.pem names localhost: the first client does not trust it, and the
  14083. // second trusts it but asks for another name
  14084. for (const auto &c :
  14085. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14086. Case{SERVER_CERT2_FILE, "example.com",
  14087. Error::SSLServerHostnameVerification}}) {
  14088. for (auto with_verifier : {false, true}) {
  14089. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14090. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14091. CLIENT_CA_CERT_FILE);
  14092. ASSERT_TRUE(svr.is_valid());
  14093. std::atomic<bool> got_client_cert{false};
  14094. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14095. [&](const tls::VerifyContext &) {
  14096. got_client_cert = true;
  14097. return true;
  14098. }));
  14099. auto port = svr.bind_to_any_port("127.0.0.1");
  14100. ASSERT_LT(0, port);
  14101. thread t = thread([&] { svr.listen_after_bind(); });
  14102. svr.wait_until_ready();
  14103. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14104. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14105. cli.set_ca_cert_path(c.trusted_ca);
  14106. if (with_verifier) {
  14107. cli.set_server_certificate_verifier(
  14108. [](const tls::VerifyContext &) { return true; });
  14109. }
  14110. auto res = cli.Get("/");
  14111. EXPECT_FALSE(res);
  14112. EXPECT_EQ(c.error, res.error());
  14113. svr.stop();
  14114. t.join();
  14115. EXPECT_FALSE(got_client_cert);
  14116. }
  14117. }
  14118. }
  14119. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14120. std::string cert_pem, key_pem, ca_pem;
  14121. read_file(SERVER_CERT_FILE, cert_pem);
  14122. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14123. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14124. ASSERT_TRUE(
  14125. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14126. }
  14127. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14129. ASSERT_TRUE(svr.is_valid());
  14130. UpdateCertsPemWithClientCA(svr);
  14131. RejectsClientWithoutCert(svr);
  14132. }
  14133. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14134. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14135. }
  14136. // A TLS error from one request must not show up in a later request's Result
  14137. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14139. ASSERT_TRUE(svr.is_valid());
  14140. svr.Get("/test", [](const Request &, Response &res) {
  14141. res.set_content("test", "text/plain");
  14142. });
  14143. auto port = svr.bind_to_any_port(HOST);
  14144. ASSERT_LT(0, port);
  14145. thread t = thread([&]() { svr.listen_after_bind(); });
  14146. auto se = detail::scope_exit([&] {
  14147. svr.stop();
  14148. t.join();
  14149. ASSERT_FALSE(svr.is_running());
  14150. });
  14151. svr.wait_until_ready();
  14152. SSLClient cli(HOST, port);
  14153. cli.set_connection_timeout(30);
  14154. cli.enable_server_hostname_verification(false);
  14155. // cert.pem is not trusted, so the handshake fails
  14156. ASSERT_FALSE(cli.Get("/test"));
  14157. cli.enable_server_certificate_verification(false);
  14158. auto res = cli.Get("/test");
  14159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14160. EXPECT_EQ(0, res.ssl_error());
  14161. EXPECT_EQ(0UL, res.ssl_backend_error());
  14162. }
  14163. // PEM memory-based constructor tests (works with all TLS backends).
  14164. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14165. // terminator after it.
  14166. void PemMemoryClientCertPresent(
  14167. const std::string &client_cert_file,
  14168. const std::string &client_private_key_file,
  14169. const std::string &client_encrypted_private_key_pass = std::string(),
  14170. bool exact_size = false) {
  14171. // Read PEM files into memory
  14172. std::string server_cert_pem, server_key_pem;
  14173. std::string client_ca_pem;
  14174. std::string client_cert_pem, client_key_pem;
  14175. read_file(SERVER_CERT_FILE, server_cert_pem);
  14176. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14177. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14178. read_file(client_cert_file, client_cert_pem);
  14179. read_file(client_private_key_file, client_key_pem);
  14180. std::list<std::vector<char>> exact_copies;
  14181. auto data = [&](const std::string &pem) -> const char * {
  14182. if (!exact_size) { return pem.c_str(); }
  14183. exact_copies.emplace_back(pem.begin(), pem.end());
  14184. return exact_copies.back().data();
  14185. };
  14186. // Create server with PEM memory
  14187. SSLServer::PemMemory server_pem = {
  14188. data(server_cert_pem),
  14189. server_cert_pem.size(),
  14190. data(server_key_pem),
  14191. server_key_pem.size(),
  14192. data(client_ca_pem),
  14193. client_ca_pem.size(),
  14194. nullptr // no password for server key
  14195. };
  14196. SSLServer svr(server_pem);
  14197. ASSERT_TRUE(svr.is_valid());
  14198. svr.Get("/test", [&](const Request &req, Response &res) {
  14199. res.set_content("test", "text/plain");
  14200. auto cert = req.peer_cert();
  14201. ASSERT_TRUE(static_cast<bool>(cert));
  14202. EXPECT_EQ("Common Name", cert.subject_cn());
  14203. });
  14204. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14205. auto se = detail::scope_exit([&] {
  14206. svr.stop();
  14207. t.join();
  14208. ASSERT_FALSE(svr.is_running());
  14209. });
  14210. svr.wait_until_ready();
  14211. // Create client with PEM memory
  14212. const char *password = client_encrypted_private_key_pass.empty()
  14213. ? nullptr
  14214. : client_encrypted_private_key_pass.c_str();
  14215. SSLClient::PemMemory client_pem = {
  14216. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14217. client_key_pem.size(), password};
  14218. SSLClient cli(HOST, PORT, client_pem);
  14219. cli.enable_server_certificate_verification(false);
  14220. cli.set_connection_timeout(30);
  14221. auto res = cli.Get("/test");
  14222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14223. ASSERT_EQ(StatusCode::OK_200, res->status);
  14224. }
  14225. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14226. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14227. }
  14228. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14229. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14230. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14231. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14232. }
  14233. // A server built from PEM memory with a client CA requires client certificates,
  14234. // also when the CA is a NUL-terminated string passed with a length of 0
  14235. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14236. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14237. read_file(SERVER_CERT_FILE, server_cert_pem);
  14238. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14239. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14240. SSLServer::PemMemory server_pem = {
  14241. server_cert_pem.c_str(),
  14242. server_cert_pem.size(),
  14243. server_key_pem.c_str(),
  14244. server_key_pem.size(),
  14245. client_ca_pem.c_str(),
  14246. client_ca_pem.size(),
  14247. nullptr // no password for server key
  14248. };
  14249. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14250. SCOPED_TRACE(client_ca_pem_len);
  14251. server_pem.client_ca_pem_len = client_ca_pem_len;
  14252. SSLServer svr(server_pem);
  14253. ASSERT_TRUE(svr.is_valid());
  14254. RejectsClientWithoutCert(svr);
  14255. }
  14256. // An empty CA fails to load instead of turning the check off
  14257. server_pem.client_ca_pem = "";
  14258. server_pem.client_ca_pem_len = 0;
  14259. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14260. }
  14261. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14262. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14263. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14264. true);
  14265. }
  14266. // A length shorter than the PEM cuts it short, so it no longer loads
  14267. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14268. std::string cert, key;
  14269. read_file(SERVER_CERT_FILE, cert);
  14270. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14271. for (auto cut_cert : {true, false}) {
  14272. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14273. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14274. SSLServer::PemMemory server_pem = {
  14275. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14276. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14277. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14278. key_len, nullptr};
  14279. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14280. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14281. key.c_str(), key_len, nullptr};
  14282. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14283. }
  14284. }
  14285. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14286. class NoListenSSLServer : public SSLServer {
  14287. public:
  14288. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14289. const char *client_ca_cert_file_path,
  14290. const char *client_ca_cert_dir_path = nullptr)
  14291. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14292. client_ca_cert_dir_path),
  14293. stop_(false) {}
  14294. std::atomic_bool stop_;
  14295. private:
  14296. bool process_and_close_socket(socket_t /*sock*/) override {
  14297. // Don't create SSL context
  14298. while (!stop_.load()) {
  14299. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14300. }
  14301. return true;
  14302. }
  14303. };
  14304. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14305. CLIENT_CA_CERT_FILE);
  14306. ASSERT_TRUE(svr.is_valid());
  14307. svr.Get("/test", [&](const Request &, Response &res) {
  14308. res.set_content("test", "text/plain");
  14309. });
  14310. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14311. auto se = detail::scope_exit([&] {
  14312. svr.stop_ = true;
  14313. svr.stop();
  14314. t.join();
  14315. ASSERT_FALSE(svr.is_running());
  14316. });
  14317. svr.wait_until_ready();
  14318. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14319. cli.enable_server_certificate_verification(false);
  14320. cli.set_connection_timeout(1);
  14321. auto res = cli.Get("/test");
  14322. ASSERT_TRUE(!res);
  14323. EXPECT_EQ(Error::SSLConnection, res.error());
  14324. // Timeout results in WantRead error code (maps to backend-specific value)
  14325. EXPECT_NE(0, res.ssl_error());
  14326. }
  14327. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14328. // Test SSLServer with client certificate verification using the standard
  14329. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14331. CLIENT_CA_CERT_DIR);
  14332. ASSERT_TRUE(svr.is_valid());
  14333. svr.Get("/test", [&](const Request &req, Response &res) {
  14334. res.set_content("test", "text/plain");
  14335. auto cert = req.peer_cert();
  14336. ASSERT_TRUE(static_cast<bool>(cert));
  14337. auto common_name = cert.subject_cn();
  14338. EXPECT_EQ("Common Name", common_name);
  14339. });
  14340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14341. auto se = detail::scope_exit([&] {
  14342. svr.stop();
  14343. t.join();
  14344. ASSERT_FALSE(svr.is_running());
  14345. });
  14346. svr.wait_until_ready();
  14347. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14348. cli.enable_server_certificate_verification(false);
  14349. cli.set_connection_timeout(30);
  14350. auto res = cli.Get("/test");
  14351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14352. ASSERT_EQ(StatusCode::OK_200, res->status);
  14353. }
  14354. // Test verify_hostname on every backend: a host is named by a SAN only
  14355. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14356. using namespace httplib::tls;
  14357. // We need a running server to test against
  14358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14359. ASSERT_TRUE(svr.is_valid());
  14360. svr.Get("/test", [](const Request &, Response &res) {
  14361. res.set_content("ok", "text/plain");
  14362. });
  14363. thread t([&]() { svr.listen(HOST, PORT); });
  14364. auto se = detail::scope_exit([&] {
  14365. svr.stop();
  14366. t.join();
  14367. });
  14368. svr.wait_until_ready();
  14369. bool verify_callback_called = false;
  14370. bool verify_result_wrong = false;
  14371. SSLClient cli(HOST, PORT);
  14372. cli.enable_server_certificate_verification(true);
  14373. cli.set_ca_cert_path(CA_CERT_FILE);
  14374. cli.set_connection_timeout(5);
  14375. // Note: Test certificate has CN="Common Name", not "localhost"
  14376. bool verify_result_cn = false;
  14377. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14378. verify_callback_called = true;
  14379. if (!ctx.cert) return false;
  14380. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14381. verify_result_cn = ctx.check_hostname("Common Name");
  14382. // Test 2: wrong hostname should not match
  14383. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14384. return true; // Accept for the purpose of this test
  14385. });
  14386. auto res = cli.Get("/test");
  14387. // The request may succeed or fail depending on cert configuration
  14388. // but the callback should have been called
  14389. ASSERT_TRUE(verify_callback_called)
  14390. << "Verify callback should have been called";
  14391. EXPECT_FALSE(verify_result_cn)
  14392. << "verify_hostname must not match the certificate CN (no SAN)";
  14393. // Wrong hostname should not match
  14394. EXPECT_FALSE(verify_result_wrong)
  14395. << "verify_hostname should not match 'wronghost.example.com'";
  14396. }
  14397. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14398. // backend verifies it.
  14399. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14400. // Certificate CN is "localhost" and it carries no SAN.
  14401. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14402. ASSERT_TRUE(svr.is_valid());
  14403. svr.Get("/test", [](const Request &, Response &res) {
  14404. res.set_content("ok", "text/plain");
  14405. });
  14406. auto port = svr.bind_to_any_port(HOST);
  14407. thread t([&]() { svr.listen_after_bind(); });
  14408. auto se = detail::scope_exit([&] {
  14409. svr.stop();
  14410. t.join();
  14411. });
  14412. svr.wait_until_ready();
  14413. SSLClient cli("localhost", port);
  14414. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14415. cli.enable_server_certificate_verification(true);
  14416. cli.set_connection_timeout(5);
  14417. auto res = cli.Get("/test");
  14418. ASSERT_FALSE(res);
  14419. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14420. // The same certificate is accepted once host name verification is off, so the
  14421. // failure above is the host name and not the chain.
  14422. cli.enable_server_hostname_verification(false);
  14423. res = cli.Get("/test");
  14424. ASSERT_TRUE(res) << to_string(res.error());
  14425. EXPECT_EQ(StatusCode::OK_200, res->status);
  14426. }
  14427. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14428. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14429. // X509_check_ip behavior and must hold for every backend.
  14430. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14431. using namespace httplib::tls;
  14432. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14433. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14434. ASSERT_TRUE(svr.is_valid());
  14435. svr.Get("/test", [](const Request &, Response &res) {
  14436. res.set_content("ok", "text/plain");
  14437. });
  14438. thread t([&]() { svr.listen(HOST, PORT); });
  14439. auto se = detail::scope_exit([&] {
  14440. svr.stop();
  14441. t.join();
  14442. });
  14443. svr.wait_until_ready();
  14444. bool verify_callback_called = false;
  14445. bool ip_matched_via_cn = true;
  14446. SSLClient cli(HOST, PORT);
  14447. cli.enable_server_certificate_verification(true);
  14448. cli.set_ca_cert_path(CA_CERT_FILE);
  14449. cli.set_connection_timeout(5);
  14450. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14451. verify_callback_called = true;
  14452. if (!ctx.cert) return false;
  14453. // The IP appears only in the CN, so it must NOT be accepted.
  14454. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14455. return true; // Accept for the purpose of this test
  14456. });
  14457. cli.Get("/test");
  14458. ASSERT_TRUE(verify_callback_called)
  14459. << "Verify callback should have been called";
  14460. EXPECT_FALSE(ip_matched_via_cn)
  14461. << "An IP host must not be authenticated via the certificate CN";
  14462. }
  14463. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14464. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14465. using namespace httplib::tls;
  14466. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14467. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14468. ASSERT_TRUE(svr.is_valid());
  14469. svr.Get("/test", [](const Request &, Response &res) {
  14470. res.set_content("ok", "text/plain");
  14471. });
  14472. thread t([&]() { svr.listen(HOST, PORT); });
  14473. auto se = detail::scope_exit([&] {
  14474. svr.stop();
  14475. t.join();
  14476. });
  14477. svr.wait_until_ready();
  14478. bool verify_callback_called = false;
  14479. bool san_matched = false;
  14480. bool wrong_ipv6_matched = true;
  14481. bool cn_ipv6_matched = true;
  14482. SSLClient cli(HOST, PORT);
  14483. cli.enable_server_certificate_verification(true);
  14484. cli.set_ca_cert_path(CA_CERT_FILE);
  14485. cli.set_connection_timeout(5);
  14486. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14487. verify_callback_called = true;
  14488. if (!ctx.cert) return false;
  14489. // Matches the IPv6 iPAddress SAN.
  14490. san_matched = ctx.check_hostname("2001:db8::1");
  14491. // A different IPv6 address must not match.
  14492. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14493. // "::1" lives only in the CN, so it must not be accepted.
  14494. cn_ipv6_matched = ctx.check_hostname("::1");
  14495. return true; // Accept for the purpose of this test
  14496. });
  14497. cli.Get("/test");
  14498. ASSERT_TRUE(verify_callback_called)
  14499. << "Verify callback should have been called";
  14500. EXPECT_TRUE(san_matched)
  14501. << "verify_hostname should match an IPv6 iPAddress SAN";
  14502. EXPECT_FALSE(wrong_ipv6_matched)
  14503. << "verify_hostname should not match a non-matching IPv6 address";
  14504. EXPECT_FALSE(cn_ipv6_matched)
  14505. << "An IPv6 host must not be authenticated via the certificate CN";
  14506. }
  14507. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14508. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14509. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14510. using namespace httplib::tls;
  14511. // SANs: DNS:a.zz, IP:42.46.122.122
  14512. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14513. ASSERT_TRUE(svr.is_valid());
  14514. svr.Get("/test", [](const Request &, Response &res) {
  14515. res.set_content("ok", "text/plain");
  14516. });
  14517. auto port = svr.bind_to_any_port(HOST);
  14518. thread t([&]() { svr.listen_after_bind(); });
  14519. auto se = detail::scope_exit([&] {
  14520. svr.stop();
  14521. t.join();
  14522. });
  14523. svr.wait_until_ready();
  14524. bool verify_callback_called = false;
  14525. bool dns_san_matched = false;
  14526. bool ip_san_matched = false;
  14527. bool ip_matched_via_dns_san = true;
  14528. bool dns_matched_via_ip_san = true;
  14529. bool cn_matched_next_to_dns_san = true;
  14530. SSLClient cli(HOST, port);
  14531. cli.enable_server_certificate_verification(true);
  14532. cli.set_ca_cert_path(CA_CERT_FILE);
  14533. cli.set_connection_timeout(5);
  14534. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14535. verify_callback_called = true;
  14536. if (!ctx.cert) return false;
  14537. dns_san_matched = ctx.check_hostname("a.zz");
  14538. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14539. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14540. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14541. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14542. return true; // Accept for the purpose of this test
  14543. });
  14544. cli.Get("/test");
  14545. ASSERT_TRUE(verify_callback_called)
  14546. << "Verify callback should have been called";
  14547. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14548. EXPECT_TRUE(ip_san_matched)
  14549. << "verify_hostname should match an iPAddress SAN";
  14550. EXPECT_FALSE(ip_matched_via_dns_san)
  14551. << "An IP host must not be authenticated via a dNSName SAN";
  14552. EXPECT_FALSE(dns_matched_via_ip_san)
  14553. << "A DNS host must not be authenticated via an iPAddress SAN";
  14554. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14555. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14556. }
  14557. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14558. // "www.*.example.test" names one host and not every host under example.test.
  14559. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14560. using namespace httplib::tls;
  14561. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14562. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14563. ASSERT_TRUE(svr.is_valid());
  14564. svr.Get("/test", [](const Request &, Response &res) {
  14565. res.set_content("ok", "text/plain");
  14566. });
  14567. auto port = svr.bind_to_any_port(HOST);
  14568. thread t([&]() { svr.listen_after_bind(); });
  14569. auto se = detail::scope_exit([&] {
  14570. svr.stop();
  14571. t.join();
  14572. });
  14573. svr.wait_until_ready();
  14574. bool verify_callback_called = false;
  14575. bool leftmost_wildcard_matched = false;
  14576. bool wildcard_spanned_labels = true;
  14577. bool inner_wildcard_matched = true;
  14578. SSLClient cli(HOST, port);
  14579. cli.enable_server_certificate_verification(true);
  14580. cli.set_ca_cert_path(CA_CERT_FILE);
  14581. cli.set_connection_timeout(5);
  14582. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14583. verify_callback_called = true;
  14584. if (!ctx.cert) return false;
  14585. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14586. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14587. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14588. return true; // Accept for the purpose of this test
  14589. });
  14590. cli.Get("/test");
  14591. ASSERT_TRUE(verify_callback_called)
  14592. << "Verify callback should have been called";
  14593. EXPECT_TRUE(leftmost_wildcard_matched)
  14594. << "A leftmost wildcard should match a single label";
  14595. EXPECT_FALSE(wildcard_spanned_labels)
  14596. << "A wildcard label must not match more than one label";
  14597. EXPECT_FALSE(inner_wildcard_matched)
  14598. << "A wildcard outside the leftmost label must not be honoured";
  14599. }
  14600. // sans() must report each SAN entry under its own type.
  14601. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14602. using namespace httplib::tls;
  14603. // SANs: DNS:a.zz, IP:42.46.122.122
  14604. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14605. ASSERT_TRUE(svr.is_valid());
  14606. svr.Get("/test", [](const Request &, Response &res) {
  14607. res.set_content("ok", "text/plain");
  14608. });
  14609. auto port = svr.bind_to_any_port(HOST);
  14610. thread t([&]() { svr.listen_after_bind(); });
  14611. auto se = detail::scope_exit([&] {
  14612. svr.stop();
  14613. t.join();
  14614. });
  14615. svr.wait_until_ready();
  14616. bool verify_callback_called = false;
  14617. std::vector<SanEntry> sans;
  14618. SSLClient cli(HOST, port);
  14619. cli.enable_server_certificate_verification(true);
  14620. cli.set_ca_cert_path(CA_CERT_FILE);
  14621. cli.set_connection_timeout(5);
  14622. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14623. verify_callback_called = true;
  14624. if (!ctx.cert) return false;
  14625. sans = ctx.sans();
  14626. return true; // Accept for the purpose of this test
  14627. });
  14628. cli.Get("/test");
  14629. ASSERT_TRUE(verify_callback_called)
  14630. << "Verify callback should have been called";
  14631. auto has_san = [&](SanType type, const std::string &value) {
  14632. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14633. return san.type == type && san.value == value;
  14634. });
  14635. };
  14636. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14637. << "sans() should report the dNSName SAN";
  14638. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14639. << "sans() should report the iPAddress SAN";
  14640. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14641. << "sans() must not report the dNSName SAN as an address";
  14642. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14643. << "sans() must not report the iPAddress SAN as a DNS name";
  14644. }
  14645. #endif
  14646. // mbedTLS-specific callback constructor test
  14647. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14648. #ifdef CPPHTTPLIB_SSL_ENABLED
  14649. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14651. ASSERT_TRUE(svr.is_valid());
  14652. // Set up a handler to verify client certificate is present
  14653. bool client_cert_verified = false;
  14654. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14655. // Verify that client certificate was provided
  14656. client_cert_verified = true;
  14657. res.set_content("success", "text/plain");
  14658. });
  14659. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14660. auto se = detail::scope_exit([&] {
  14661. svr.stop();
  14662. t.join();
  14663. ASSERT_FALSE(svr.is_running());
  14664. });
  14665. svr.wait_until_ready();
  14666. // Client with certificate
  14667. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14668. cli.enable_server_certificate_verification(false);
  14669. cli.set_connection_timeout(30);
  14670. auto res = cli.Get("/test");
  14671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14672. ASSERT_EQ(StatusCode::OK_200, res->status);
  14673. ASSERT_TRUE(client_cert_verified);
  14674. EXPECT_EQ("success", res->body);
  14675. }
  14676. #endif
  14677. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14678. // backends
  14679. #ifdef CPPHTTPLIB_SSL_ENABLED
  14680. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14681. using namespace httplib::tls;
  14682. // Test that when client CA cert file is provided,
  14683. // the server properly requests and validates client certificates
  14684. // Create a server with client authentication
  14685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14686. ASSERT_TRUE(svr.is_valid());
  14687. bool handler_called = false;
  14688. svr.Get("/test", [&](const Request &req, Response &res) {
  14689. handler_called = true;
  14690. // Verify that a client certificate was provided
  14691. auto cert = req.peer_cert();
  14692. ASSERT_TRUE(static_cast<bool>(cert));
  14693. // Get the issuer name
  14694. std::string issuer_str = cert.issuer_name();
  14695. ASSERT_FALSE(issuer_str.empty());
  14696. // The client certificate should be issued by our test CA
  14697. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14698. res.set_content("authenticated", "text/plain");
  14699. });
  14700. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14701. auto se = detail::scope_exit([&] {
  14702. svr.stop();
  14703. t.join();
  14704. ASSERT_FALSE(svr.is_running());
  14705. });
  14706. svr.wait_until_ready();
  14707. // Connect with a client certificate issued by the CA
  14708. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14709. cli.enable_server_certificate_verification(false);
  14710. cli.set_connection_timeout(30);
  14711. auto res = cli.Get("/test");
  14712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14713. ASSERT_EQ(StatusCode::OK_200, res->status);
  14714. ASSERT_TRUE(handler_called);
  14715. EXPECT_EQ("authenticated", res->body);
  14716. }
  14717. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14718. using namespace httplib::tls;
  14719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14720. ASSERT_TRUE(svr.is_valid());
  14721. svr.Get("/test", [](const Request &, Response &res) {
  14722. res.set_content("ok", "text/plain");
  14723. });
  14724. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14725. auto se = detail::scope_exit([&] {
  14726. svr.stop();
  14727. t.join();
  14728. });
  14729. svr.wait_until_ready();
  14730. SSLClient cli(HOST, PORT);
  14731. cli.enable_server_certificate_verification(false);
  14732. cli.set_connection_timeout(30);
  14733. bool cert_checked = false;
  14734. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14735. if (ctx.cert) {
  14736. auto sans = ctx.sans();
  14737. // Test certificate may or may not have SANs - just verify the API
  14738. // works If SANs exist, verify the types are valid
  14739. for (const auto &san : sans) {
  14740. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14741. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14742. san.type == SanType::OTHER);
  14743. EXPECT_FALSE(san.value.empty());
  14744. }
  14745. cert_checked = true;
  14746. }
  14747. return true;
  14748. });
  14749. auto res = cli.Get("/test");
  14750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14751. EXPECT_TRUE(cert_checked);
  14752. }
  14753. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14754. using namespace httplib::tls;
  14755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14756. ASSERT_TRUE(svr.is_valid());
  14757. svr.Get("/test", [](const Request &, Response &res) {
  14758. res.set_content("ok", "text/plain");
  14759. });
  14760. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14761. auto se = detail::scope_exit([&] {
  14762. svr.stop();
  14763. t.join();
  14764. });
  14765. svr.wait_until_ready();
  14766. SSLClient cli(HOST, PORT);
  14767. cli.enable_server_certificate_verification(false);
  14768. cli.set_connection_timeout(30);
  14769. bool validity_checked = false;
  14770. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14771. if (ctx.cert) {
  14772. time_t not_before = 0, not_after = 0;
  14773. bool result = ctx.validity(not_before, not_after);
  14774. EXPECT_TRUE(result);
  14775. // Verify that not_before < now < not_after for a valid cert
  14776. time_t now = time(nullptr);
  14777. EXPECT_LT(not_before, now);
  14778. EXPECT_GT(not_after, now);
  14779. validity_checked = true;
  14780. }
  14781. return true;
  14782. });
  14783. auto res = cli.Get("/test");
  14784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14785. EXPECT_TRUE(validity_checked);
  14786. }
  14787. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14788. using namespace httplib::tls;
  14789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14790. ASSERT_TRUE(svr.is_valid());
  14791. svr.Get("/test", [](const Request &, Response &res) {
  14792. res.set_content("ok", "text/plain");
  14793. });
  14794. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14795. auto se = detail::scope_exit([&] {
  14796. svr.stop();
  14797. t.join();
  14798. });
  14799. svr.wait_until_ready();
  14800. SSLClient cli(HOST, PORT);
  14801. cli.enable_server_certificate_verification(false);
  14802. cli.set_connection_timeout(30);
  14803. bool serial_checked = false;
  14804. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14805. if (ctx.cert) {
  14806. std::string serial = ctx.serial();
  14807. EXPECT_FALSE(serial.empty());
  14808. // Serial should be a hex string
  14809. for (char c : serial) {
  14810. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14811. (c >= 'a' && c <= 'f'));
  14812. }
  14813. serial_checked = true;
  14814. }
  14815. return true;
  14816. });
  14817. auto res = cli.Get("/test");
  14818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14819. EXPECT_TRUE(serial_checked);
  14820. }
  14821. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14822. // Test 1: Valid CA file - no error should be recorded
  14823. {
  14824. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14825. CLIENT_CA_CERT_FILE);
  14826. ASSERT_TRUE(svr.is_valid());
  14827. // With valid setup, last_ssl_error should be 0
  14828. EXPECT_EQ(0, svr.ssl_last_error());
  14829. }
  14830. // Test 2: Invalid CA file content
  14831. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14832. {
  14833. // Create a temporary file with completely invalid content
  14834. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14835. {
  14836. std::ofstream ofs(temp_invalid_ca);
  14837. ofs << "This is not a certificate file at all\n";
  14838. ofs << "Just plain text content\n";
  14839. }
  14840. // Create server with invalid CA file
  14841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14842. // Clean up temporary file
  14843. std::remove(temp_invalid_ca);
  14844. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14845. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14846. // Note: SSL_CTX_load_verify_locations typically fails first,
  14847. // but our error handling code path is still exercised
  14848. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14849. }
  14850. }
  14851. TEST(VerifyCallbackTest, VerifyContextFields) {
  14852. using namespace httplib::tls;
  14853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14854. ASSERT_TRUE(svr.is_valid());
  14855. svr.Get("/test", [](const Request &, Response &res) {
  14856. res.set_content("ok", "text/plain");
  14857. });
  14858. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14859. auto se = detail::scope_exit([&] {
  14860. svr.stop();
  14861. t.join();
  14862. });
  14863. svr.wait_until_ready();
  14864. SSLClient cli(HOST, PORT);
  14865. cli.enable_server_certificate_verification(false);
  14866. cli.set_connection_timeout(30);
  14867. int callback_count = 0;
  14868. bool saw_leaf_cert = false;
  14869. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14870. if (ctx.cert) {
  14871. callback_count++;
  14872. // We should see at least one certificate (the leaf)
  14873. std::string cn = ctx.subject_cn();
  14874. if (!cn.empty()) { saw_leaf_cert = true; }
  14875. // Verify context fields are populated
  14876. EXPECT_NE(ctx.session, nullptr);
  14877. EXPECT_GE(ctx.depth, 0);
  14878. }
  14879. return true;
  14880. });
  14881. auto res = cli.Get("/test");
  14882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14883. EXPECT_GT(callback_count, 0);
  14884. EXPECT_TRUE(saw_leaf_cert);
  14885. }
  14886. // A verifier that accepts runs alongside the built-in verification, and is the
  14887. // only check once that is turned off.
  14888. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14889. using namespace httplib::tls;
  14890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14891. ASSERT_TRUE(svr.is_valid());
  14892. svr.Get("/test", [](const Request &, Response &res) {
  14893. res.set_content("ok", "text/plain");
  14894. });
  14895. auto port = svr.bind_to_any_port(HOST);
  14896. thread t([&]() { svr.listen_after_bind(); });
  14897. auto se = detail::scope_exit([&] {
  14898. svr.stop();
  14899. t.join();
  14900. });
  14901. svr.wait_until_ready();
  14902. SSLClient cli(HOST, port);
  14903. cli.enable_server_hostname_verification(false);
  14904. auto calls = 0;
  14905. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14906. calls++;
  14907. return true;
  14908. });
  14909. // cert.pem is not trusted
  14910. auto res = cli.Get("/test");
  14911. ASSERT_FALSE(res);
  14912. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14913. EXPECT_GT(calls, 0);
  14914. cli.enable_server_certificate_verification(false);
  14915. res = cli.Get("/test");
  14916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14917. EXPECT_EQ("ok", res->body);
  14918. }
  14919. // A verifier belongs to the client that set it, not to the thread that set it.
  14920. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14921. using namespace httplib::tls;
  14922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14923. ASSERT_TRUE(svr.is_valid());
  14924. svr.Get("/test", [](const Request &, Response &res) {
  14925. res.set_content("ok", "text/plain");
  14926. });
  14927. auto port = svr.bind_to_any_port(HOST);
  14928. thread t([&]() { svr.listen_after_bind(); });
  14929. auto se = detail::scope_exit([&] {
  14930. svr.stop();
  14931. t.join();
  14932. });
  14933. svr.wait_until_ready();
  14934. auto rejecting_calls = 0;
  14935. SSLClient rejecting(HOST, port);
  14936. rejecting.enable_server_certificate_verification(false);
  14937. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14938. rejecting_calls++;
  14939. return false;
  14940. });
  14941. auto accepting_calls = 0;
  14942. SSLClient accepting(HOST, port);
  14943. accepting.enable_server_certificate_verification(false);
  14944. // Set on another thread than the requests below.
  14945. thread([&]() {
  14946. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14947. accepting_calls++;
  14948. return true;
  14949. });
  14950. }).join();
  14951. // Requested on another thread than the verifier was set on.
  14952. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14953. EXPECT_GT(rejecting_calls, 0);
  14954. auto res = accepting.Get("/test");
  14955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14956. EXPECT_GT(accepting_calls, 0);
  14957. }
  14958. // A verifier replaced while a handshake runs it lives until it returns.
  14959. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14960. using namespace httplib::tls;
  14961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14962. ASSERT_TRUE(svr.is_valid());
  14963. svr.Get("/test", [](const Request &, Response &res) {
  14964. res.set_content("ok", "text/plain");
  14965. });
  14966. auto port = svr.bind_to_any_port(HOST);
  14967. thread t([&]() { svr.listen_after_bind(); });
  14968. auto se = detail::scope_exit([&] {
  14969. svr.stop();
  14970. t.join();
  14971. });
  14972. svr.wait_until_ready();
  14973. SSLClient cli(HOST, port);
  14974. cli.enable_server_certificate_verification(false);
  14975. std::promise<void> entered;
  14976. std::promise<void> replaced;
  14977. auto replaced_future = replaced.get_future();
  14978. auto first_call = true;
  14979. // Long enough to live on the heap
  14980. std::string expected(64, 'v');
  14981. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14982. if (first_call) {
  14983. first_call = false;
  14984. entered.set_value();
  14985. replaced_future.wait();
  14986. }
  14987. return expected == std::string(64, 'v');
  14988. });
  14989. thread request([&]() {
  14990. auto res = cli.Get("/test");
  14991. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14992. });
  14993. entered.get_future().wait();
  14994. cli.set_server_certificate_verifier(
  14995. [](const VerifyContext &) { return true; });
  14996. replaced.set_value();
  14997. request.join();
  14998. }
  14999. // VerifyContext::session is the same handle the other tls:: functions take.
  15000. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15001. using namespace httplib::tls;
  15002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15003. ASSERT_TRUE(svr.is_valid());
  15004. svr.Get("/test", [](const Request &, Response &res) {
  15005. res.set_content("ok", "text/plain");
  15006. });
  15007. auto port = svr.bind_to_any_port(HOST);
  15008. thread t([&]() { svr.listen_after_bind(); });
  15009. auto se = detail::scope_exit([&] {
  15010. svr.stop();
  15011. t.join();
  15012. });
  15013. svr.wait_until_ready();
  15014. SSLClient cli(HOST, port);
  15015. cli.enable_server_certificate_verification(false);
  15016. session_t verifier_session = nullptr;
  15017. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15018. verifier_session = ctx.session;
  15019. return true;
  15020. });
  15021. session_t session_verifier_session = nullptr;
  15022. cli.set_session_verifier([&](session_t session) {
  15023. session_verifier_session = session;
  15024. return SSLVerifierResponse::NoDecisionMade;
  15025. });
  15026. auto res = cli.Get("/test");
  15027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15028. EXPECT_NE(nullptr, verifier_session);
  15029. EXPECT_EQ(session_verifier_session, verifier_session);
  15030. }
  15031. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15032. using httplib::tls::TlsError;
  15033. // Test that verify_error_to_string returns empty for success
  15034. std::string success_str = TlsError::verify_error_to_string(0);
  15035. EXPECT_TRUE(success_str.empty());
  15036. // Test that verify_error_to_string returns non-empty for error codes
  15037. // Using a common error code (certificate expired)
  15038. std::string error_str =
  15039. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15040. EXPECT_FALSE(error_str.empty());
  15041. }
  15042. TEST(SessionVerifierTest, CertificateAccepted) {
  15043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15044. ASSERT_TRUE(svr.is_valid());
  15045. svr.Get("/test", [](const Request &, Response &res) {
  15046. res.set_content("ok", "text/plain");
  15047. });
  15048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15049. auto se = detail::scope_exit([&] {
  15050. svr.stop();
  15051. t.join();
  15052. });
  15053. svr.wait_until_ready();
  15054. SSLClient cli(HOST, PORT);
  15055. cli.enable_server_certificate_verification(false);
  15056. cli.set_connection_timeout(30);
  15057. bool callback_called = false;
  15058. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15059. EXPECT_NE(session, nullptr);
  15060. callback_called = true;
  15061. return SSLVerifierResponse::CertificateAccepted;
  15062. });
  15063. auto res = cli.Get("/test");
  15064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15065. EXPECT_EQ(200, res->status);
  15066. EXPECT_TRUE(callback_called);
  15067. }
  15068. TEST(SessionVerifierTest, CertificateRejected) {
  15069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15070. ASSERT_TRUE(svr.is_valid());
  15071. svr.Get("/test", [](const Request &, Response &res) {
  15072. res.set_content("ok", "text/plain");
  15073. });
  15074. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15075. auto se = detail::scope_exit([&] {
  15076. svr.stop();
  15077. t.join();
  15078. });
  15079. svr.wait_until_ready();
  15080. SSLClient cli(HOST, PORT);
  15081. cli.enable_server_certificate_verification(false);
  15082. cli.set_connection_timeout(30);
  15083. bool callback_called = false;
  15084. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15085. EXPECT_NE(session, nullptr);
  15086. callback_called = true;
  15087. return SSLVerifierResponse::CertificateRejected;
  15088. });
  15089. auto res = cli.Get("/test");
  15090. EXPECT_FALSE(res);
  15091. EXPECT_TRUE(callback_called);
  15092. }
  15093. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15094. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15095. ASSERT_TRUE(svr.is_valid());
  15096. svr.Get("/test", [](const Request &, Response &res) {
  15097. res.set_content("ok", "text/plain");
  15098. });
  15099. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15100. auto se = detail::scope_exit([&] {
  15101. svr.stop();
  15102. t.join();
  15103. });
  15104. svr.wait_until_ready();
  15105. // NoDecisionMade with verification disabled should succeed (no default check)
  15106. SSLClient cli(HOST, PORT);
  15107. cli.enable_server_certificate_verification(false);
  15108. cli.set_connection_timeout(30);
  15109. bool callback_called = false;
  15110. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15111. EXPECT_NE(session, nullptr);
  15112. callback_called = true;
  15113. return SSLVerifierResponse::NoDecisionMade;
  15114. });
  15115. auto res = cli.Get("/test");
  15116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15117. EXPECT_EQ(200, res->status);
  15118. EXPECT_TRUE(callback_called);
  15119. }
  15120. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15122. ASSERT_TRUE(svr.is_valid());
  15123. svr.Get("/test", [](const Request &, Response &res) {
  15124. res.set_content("ok", "text/plain");
  15125. });
  15126. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15127. auto se = detail::scope_exit([&] {
  15128. svr.stop();
  15129. t.join();
  15130. });
  15131. svr.wait_until_ready();
  15132. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15133. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15134. // so we only check that the request fails, not whether the callback was
  15135. // called.
  15136. SSLClient cli(HOST, PORT);
  15137. cli.enable_server_certificate_verification(true);
  15138. cli.set_connection_timeout(30);
  15139. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15140. EXPECT_NE(session, nullptr);
  15141. return SSLVerifierResponse::NoDecisionMade;
  15142. });
  15143. auto res = cli.Get("/test");
  15144. EXPECT_FALSE(res);
  15145. }
  15146. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15147. // Test SSL server using PemMemory constructor with client CA certificates
  15148. // Read PEM files
  15149. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15150. read_file(SERVER_CERT_FILE, server_cert_pem);
  15151. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15152. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15153. // Create SSLServer with PemMemory constructor including client CA
  15154. SSLServer::PemMemory server_pem = {
  15155. server_cert_pem.c_str(),
  15156. server_cert_pem.size(),
  15157. server_key_pem.c_str(),
  15158. server_key_pem.size(),
  15159. client_ca_pem.c_str(),
  15160. client_ca_pem.size(),
  15161. nullptr // no password for server key
  15162. };
  15163. SSLServer svr(server_pem);
  15164. ASSERT_TRUE(svr.is_valid());
  15165. // No SSL error should be recorded for valid setup
  15166. EXPECT_EQ(0, svr.ssl_last_error());
  15167. // Set up server endpoints
  15168. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15169. res.set_content("ok", "text/plain");
  15170. });
  15171. // Start server in a thread
  15172. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15173. svr.wait_until_ready();
  15174. // Connect with client certificate (using constructor with paths)
  15175. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15176. cli.enable_server_certificate_verification(false);
  15177. auto res = cli.Get("/test-pem-ca");
  15178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15179. EXPECT_EQ(200, res->status);
  15180. EXPECT_EQ("ok", res->body);
  15181. svr.stop();
  15182. server_thread.join();
  15183. }
  15184. #endif
  15185. #ifdef _WIN32
  15186. TEST(CleanupTest, WSACleanup) {
  15187. int ret = WSACleanup();
  15188. ASSERT_EQ(0, ret);
  15189. }
  15190. #endif
  15191. #ifndef CPPHTTPLIB_SSL_ENABLED
  15192. TEST(NoSSLSupport, SimpleInterface) {
  15193. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15194. }
  15195. #endif
  15196. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15197. TEST(InvalidScheme, SimpleInterface) {
  15198. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15199. }
  15200. #endif
  15201. TEST(NoScheme, SimpleInterface) {
  15202. Client cli("yahoo.com:80");
  15203. ASSERT_TRUE(cli.is_valid());
  15204. }
  15205. TEST(SendAPI, SimpleInterface_Online) {
  15206. Client cli("http://yahoo.com");
  15207. Request req;
  15208. req.method = "GET";
  15209. req.path = "/";
  15210. auto res = cli.send(req);
  15211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15212. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15213. }
  15214. TEST(SendAPI, WithParamsInRequest) {
  15215. Server svr;
  15216. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15217. EXPECT_TRUE(req.has_param("test"));
  15218. EXPECT_EQ("test_value", req.get_param_value("test"));
  15219. });
  15220. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15221. auto se = detail::scope_exit([&] {
  15222. svr.stop();
  15223. t.join();
  15224. ASSERT_FALSE(svr.is_running());
  15225. });
  15226. svr.wait_until_ready();
  15227. Client cli(HOST, PORT);
  15228. {
  15229. Request req;
  15230. req.method = "GET";
  15231. req.path = "/";
  15232. req.params.emplace("test", "test_value");
  15233. auto res = cli.send(req);
  15234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15235. }
  15236. {
  15237. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15239. }
  15240. }
  15241. TEST(ClientImplMethods, GetSocketTest) {
  15242. httplib::Server svr;
  15243. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15244. res.status = StatusCode::OK_200;
  15245. });
  15246. auto port = svr.bind_to_any_port("127.0.0.1");
  15247. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15248. auto se = detail::scope_exit([&] {
  15249. svr.stop();
  15250. thread.join();
  15251. ASSERT_FALSE(svr.is_running());
  15252. });
  15253. svr.wait_until_ready();
  15254. {
  15255. httplib::Client cli("127.0.0.1", port);
  15256. cli.set_keep_alive(true);
  15257. // Use the behavior of cpp-httplib of opening the connection
  15258. // only when the first request happens. If that changes,
  15259. // this test would be obsolete.
  15260. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15261. // This also implicitly tests the server. But other tests would fail much
  15262. // earlier than this one to be considered.
  15263. auto res = cli.Get("/");
  15264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15265. EXPECT_EQ(StatusCode::OK_200, res->status);
  15266. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15267. }
  15268. }
  15269. #ifdef CPPHTTPLIB_SSL_ENABLED
  15270. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15271. Client cli("http://yahoo.com");
  15272. auto res = cli.Get("/");
  15273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15274. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15275. cli.set_follow_location(true);
  15276. res = cli.Get("/");
  15277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15278. EXPECT_EQ(StatusCode::OK_200, res->status);
  15279. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15280. }
  15281. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15282. Client cli("https://yahoo.com");
  15283. auto res = cli.Get("/");
  15284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15285. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15286. cli.set_follow_location(true);
  15287. res = cli.Get("/");
  15288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15289. EXPECT_EQ(StatusCode::OK_200, res->status);
  15290. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15291. }
  15292. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15293. Client cli("https://yahoo.com");
  15294. auto res = cli.Get("/");
  15295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15296. ASSERT_FALSE(!res);
  15297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15298. ASSERT_FALSE(res == nullptr);
  15299. ASSERT_TRUE(res != nullptr);
  15300. EXPECT_EQ(Error::Success, res.error());
  15301. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15302. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15303. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15304. cli.set_follow_location(true);
  15305. res = cli.Get("/");
  15306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15307. EXPECT_EQ(Error::Success, res.error());
  15308. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15309. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15310. EXPECT_EQ(StatusCode::OK_200, res->status);
  15311. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15312. }
  15313. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15314. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15315. Client cli("https://cdnjs.cloudflare.com");
  15316. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15317. Headers{{"Accept-Encoding", "br"}});
  15318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15319. EXPECT_EQ(StatusCode::OK_200, res->status);
  15320. EXPECT_EQ(287630U, res->body.size());
  15321. EXPECT_EQ("application/javascript; charset=utf-8",
  15322. res->get_header_value("Content-Type"));
  15323. }
  15324. #endif
  15325. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15326. #undef REDIR_HOST // Silence compiler warning
  15327. #define REDIR_HOST "https://httpbingo.org"
  15328. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15329. Client cli(REDIR_HOST);
  15330. cli.set_follow_location(true);
  15331. auto res =
  15332. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15334. EXPECT_EQ(StatusCode::OK_200, res->status);
  15335. }
  15336. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15337. Client cli(REDIR_HOST);
  15338. cli.set_follow_location(true);
  15339. Params params;
  15340. params.emplace("url", "http://example.com");
  15341. params.emplace("status_code", "302");
  15342. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15344. EXPECT_EQ(StatusCode::OK_200, res->status);
  15345. }
  15346. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15347. Client cli(REDIR_HOST);
  15348. cli.set_follow_location(true);
  15349. Params params;
  15350. params.emplace("url", "http://example.com");
  15351. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15353. EXPECT_EQ(StatusCode::OK_200, res->status);
  15354. }
  15355. TEST(HttpToHttpsRedirectTest, CertFile) {
  15356. auto ssl_port = PORT + 1;
  15357. Server svr;
  15358. ASSERT_TRUE(svr.is_valid());
  15359. svr.Get("/index", [&](const Request &, Response &res) {
  15360. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15361. "/index");
  15362. svr.stop();
  15363. });
  15364. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15365. ASSERT_TRUE(ssl_svr.is_valid());
  15366. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15367. res.set_content("test", "text/plain");
  15368. ssl_svr.stop();
  15369. });
  15370. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15371. thread t2 =
  15372. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15373. auto se = detail::scope_exit([&] {
  15374. t2.join();
  15375. t.join();
  15376. ASSERT_FALSE(svr.is_running());
  15377. });
  15378. svr.wait_until_ready();
  15379. ssl_svr.wait_until_ready();
  15380. Client cli("127.0.0.1", PORT);
  15381. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15382. cli.enable_server_certificate_verification(true);
  15383. cli.set_follow_location(true);
  15384. cli.set_connection_timeout(30);
  15385. auto res = cli.Get("/index");
  15386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15387. ASSERT_EQ(StatusCode::OK_200, res->status);
  15388. }
  15389. TEST(SSLClientRedirectTest, CertFile) {
  15390. auto ssl_port = PORT + 1;
  15391. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15392. ASSERT_TRUE(ssl_svr1.is_valid());
  15393. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15394. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15395. "/index");
  15396. ssl_svr1.stop();
  15397. });
  15398. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15399. ASSERT_TRUE(ssl_svr2.is_valid());
  15400. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15401. res.set_content("test", "text/plain");
  15402. ssl_svr2.stop();
  15403. });
  15404. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15405. thread t2 =
  15406. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15407. auto se = detail::scope_exit([&] {
  15408. t2.join();
  15409. t.join();
  15410. ASSERT_FALSE(ssl_svr1.is_running());
  15411. });
  15412. ssl_svr1.wait_until_ready();
  15413. ssl_svr2.wait_until_ready();
  15414. SSLClient cli("127.0.0.1", PORT);
  15415. std::string cert;
  15416. read_file(SERVER_CERT2_FILE, cert);
  15417. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15418. cli.enable_server_certificate_verification(true);
  15419. cli.set_follow_location(true);
  15420. cli.set_connection_timeout(30);
  15421. auto res = cli.Get("/index");
  15422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15423. ASSERT_EQ(StatusCode::OK_200, res->status);
  15424. }
  15425. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15426. // another port, so the client follows it with a new client.
  15427. static Result GetThroughTlsRedirectToDifferentPort(
  15428. const std::function<void(SSLClient &)> &setup,
  15429. const char *target_cert = SERVER_CERT2_FILE,
  15430. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15431. auto ssl_port = PORT + 1;
  15432. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15433. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15434. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15435. "/index");
  15436. });
  15437. SSLServer ssl_svr2(target_cert, target_key);
  15438. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15439. res.set_content("test", "text/plain");
  15440. });
  15441. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15442. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15443. auto se = detail::scope_exit([&] {
  15444. ssl_svr2.stop();
  15445. ssl_svr1.stop();
  15446. t2.join();
  15447. t.join();
  15448. });
  15449. ssl_svr1.wait_until_ready();
  15450. ssl_svr2.wait_until_ready();
  15451. SSLClient cli("127.0.0.1", PORT);
  15452. cli.set_follow_location(true);
  15453. cli.set_connection_timeout(30);
  15454. setup(cli);
  15455. return cli.Get("/index");
  15456. }
  15457. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15458. auto calls = 0;
  15459. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15460. cli.enable_server_certificate_verification(false);
  15461. // Accept the first server only.
  15462. cli.set_session_verifier([&](tls::session_t) {
  15463. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15464. : SSLVerifierResponse::CertificateRejected;
  15465. });
  15466. });
  15467. ASSERT_FALSE(res);
  15468. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15469. EXPECT_EQ(2, calls);
  15470. }
  15471. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15472. std::string pinned;
  15473. auto res = GetThroughTlsRedirectToDifferentPort(
  15474. [&](SSLClient &cli) {
  15475. cli.enable_server_certificate_verification(false);
  15476. // Pin the first certificate seen.
  15477. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15478. if (pinned.empty()) { pinned = ctx.serial(); }
  15479. return ctx.serial() == pinned;
  15480. });
  15481. },
  15482. // A certificate other than the first server's.
  15483. SERVER_CERT_FILE);
  15484. EXPECT_FALSE(res);
  15485. EXPECT_FALSE(pinned.empty());
  15486. }
  15487. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15488. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15489. std::string cert;
  15490. read_file(SERVER_CERT2_FILE, cert);
  15491. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15492. });
  15493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15494. EXPECT_EQ(StatusCode::OK_200, res->status);
  15495. }
  15496. // The target's certificate is signed by the root CA, which the first server's
  15497. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15498. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15499. auto res = GetThroughTlsRedirectToDifferentPort(
  15500. [](SSLClient &cli) {
  15501. std::string root_ca, cert;
  15502. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15503. read_file(SERVER_CERT2_FILE, cert);
  15504. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15505. cli.load_ca_cert_store(cert.data(), cert.size());
  15506. cli.enable_server_hostname_verification(false);
  15507. },
  15508. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15510. EXPECT_EQ(StatusCode::OK_200, res->status);
  15511. }
  15512. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15513. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15514. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15515. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15516. auto res = GetThroughTlsRedirectToDifferentPort(
  15517. [](SSLClient &cli) {
  15518. std::string root_ca, cert;
  15519. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15520. read_file(SERVER_CERT2_FILE, cert);
  15521. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15522. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15523. cli.enable_server_hostname_verification(false);
  15524. },
  15525. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15526. ASSERT_FALSE(res);
  15527. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15528. }
  15529. #endif
  15530. #endif
  15531. #ifdef CPPHTTPLIB_SSL_ENABLED
  15532. // Test that set_ca_cert_store() skips system certs (consistent with
  15533. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15534. // should be trusted - system certs should NOT be loaded.
  15535. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15536. // Load a specific cert that is NOT a system CA cert
  15537. std::string cert;
  15538. read_file(SERVER_CERT2_FILE, cert);
  15539. SSLClient cli("google.com");
  15540. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15541. cli.enable_server_certificate_verification(true);
  15542. // This should FAIL because:
  15543. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15544. // 2. System certs should NOT be loaded when custom store is set
  15545. // If system certs WERE loaded, this would succeed
  15546. auto res = cli.Get("/");
  15547. ASSERT_FALSE(res);
  15548. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15549. }
  15550. // Same as above, but through the native store handle path. Regression test:
  15551. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15552. // merged system certs into the user-provided store.
  15553. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15554. std::string cert;
  15555. read_file(SERVER_CERT2_FILE, cert);
  15556. SSLClient cli("google.com");
  15557. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15558. cli.enable_server_certificate_verification(true);
  15559. auto res = cli.Get("/");
  15560. ASSERT_FALSE(res);
  15561. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15562. }
  15563. // A custom store set via the native handle must still verify a server whose
  15564. // cert it does contain.
  15565. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15566. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15567. ASSERT_TRUE(svr.is_valid());
  15568. svr.Get("/test", [&](const Request &, Response &res) {
  15569. res.set_content("test", "text/plain");
  15570. });
  15571. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15572. auto se = detail::scope_exit([&] {
  15573. svr.stop();
  15574. t.join();
  15575. ASSERT_FALSE(svr.is_running());
  15576. });
  15577. svr.wait_until_ready();
  15578. SSLClient cli("127.0.0.1", PORT);
  15579. std::string cert;
  15580. read_file(SERVER_CERT2_FILE, cert);
  15581. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15582. cli.enable_server_certificate_verification(true);
  15583. cli.set_connection_timeout(30);
  15584. auto res = cli.Get("/test");
  15585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15586. ASSERT_EQ(StatusCode::OK_200, res->status);
  15587. }
  15588. // CA certs loaded through the universal Client must be transferred to the
  15589. // client created internally for following an HTTPS redirect. Regression test:
  15590. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15591. // the CA data for redirect transfer.
  15592. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15593. auto ssl_port = PORT + 1;
  15594. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15595. ASSERT_TRUE(ssl_svr1.is_valid());
  15596. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15597. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15598. "/index");
  15599. });
  15600. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15601. ASSERT_TRUE(ssl_svr2.is_valid());
  15602. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15603. res.set_content("test", "text/plain");
  15604. });
  15605. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15606. thread t2 =
  15607. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15608. auto se = detail::scope_exit([&] {
  15609. ssl_svr2.stop();
  15610. ssl_svr1.stop();
  15611. t2.join();
  15612. t.join();
  15613. ASSERT_FALSE(ssl_svr1.is_running());
  15614. });
  15615. ssl_svr1.wait_until_ready();
  15616. ssl_svr2.wait_until_ready();
  15617. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15618. std::string cert;
  15619. read_file(SERVER_CERT2_FILE, cert);
  15620. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15621. cli.enable_server_certificate_verification(true);
  15622. cli.set_follow_location(true);
  15623. cli.set_connection_timeout(30);
  15624. auto res = cli.Get("/index");
  15625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15626. ASSERT_EQ(StatusCode::OK_200, res->status);
  15627. }
  15628. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15629. // so a host signed by a system CA verifies even though a custom CA is set
  15630. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15631. std::string cert;
  15632. read_file(SERVER_CERT2_FILE, cert);
  15633. SSLClient cli("google.com");
  15634. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15635. cli.enable_system_ca(true);
  15636. cli.enable_server_certificate_verification(true);
  15637. auto res = cli.Get("/");
  15638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15639. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15640. }
  15641. // The custom CA remains effective when combined with the system CA
  15642. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15643. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15644. ASSERT_TRUE(svr.is_valid());
  15645. svr.Get("/test", [&](const Request &, Response &res) {
  15646. res.set_content("test", "text/plain");
  15647. });
  15648. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15649. auto se = detail::scope_exit([&] {
  15650. svr.stop();
  15651. t.join();
  15652. ASSERT_FALSE(svr.is_running());
  15653. });
  15654. svr.wait_until_ready();
  15655. SSLClient cli("127.0.0.1", PORT);
  15656. std::string cert;
  15657. read_file(SERVER_CERT2_FILE, cert);
  15658. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15659. cli.enable_system_ca(true);
  15660. cli.enable_server_certificate_verification(true);
  15661. cli.set_connection_timeout(30);
  15662. auto res = cli.Get("/test");
  15663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15664. ASSERT_EQ(StatusCode::OK_200, res->status);
  15665. }
  15666. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15667. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15668. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15669. static CFDictionaryRef
  15670. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15671. const SecTrustSettingsResult *result) {
  15672. auto constraint =
  15673. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15674. &kCFTypeDictionaryValueCallBacks);
  15675. if (policy) {
  15676. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15677. }
  15678. if (policy_string) {
  15679. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15680. kCFStringEncodingUTF8);
  15681. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15682. CFRelease(str);
  15683. }
  15684. if (result) {
  15685. auto number_value = static_cast<SInt32>(*result);
  15686. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15687. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15688. CFRelease(number);
  15689. }
  15690. return constraint;
  15691. }
  15692. static SecTrustSettingsResult
  15693. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15694. auto trust_settings =
  15695. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15696. for (auto constraint : constraints) {
  15697. CFArrayAppendValue(trust_settings, constraint);
  15698. CFRelease(constraint);
  15699. }
  15700. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15701. CFRelease(trust_settings);
  15702. return result;
  15703. }
  15704. // The system CA loader takes a Keychain certificate as a trusted root only
  15705. // when its Trust Settings say so for SSL, not merely because it has some.
  15706. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15707. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15708. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15709. const auto deny = kSecTrustSettingsResultDeny;
  15710. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15711. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15712. auto x509_policy = SecPolicyCreateBasicX509();
  15713. // "Always Trust", which stores no constraint at all
  15714. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15715. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15716. ssl_trust_settings_result(
  15717. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15718. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15719. ssl_trust_settings_result(
  15720. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15721. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15722. ssl_trust_settings_result(
  15723. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15724. // "Never Trust", for everything or for SSL
  15725. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15726. ssl_trust_settings_result(
  15727. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15728. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15729. ssl_trust_settings_result(
  15730. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15731. // Trusted for another policy, for one host, or not at all
  15732. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15733. ssl_trust_settings_result(
  15734. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15735. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15736. ssl_trust_settings_result({make_usage_constraint(
  15737. ssl_policy, "www.example.com", &trust_root)}));
  15738. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15739. ssl_trust_settings_result(
  15740. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15741. // The first constraint that applies to SSL decides
  15742. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15743. ssl_trust_settings_result(
  15744. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15745. make_usage_constraint(nullptr, nullptr, &deny)}));
  15746. CFRelease(x509_policy);
  15747. CFRelease(ssl_policy);
  15748. }
  15749. #endif
  15750. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15751. // skip chain verification entirely (only the certificate identity was
  15752. // checked), so a server presenting an untrusted certificate with a matching
  15753. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15754. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15755. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15756. ASSERT_TRUE(svr.is_valid());
  15757. svr.Get("/test", [&](const Request &, Response &res) {
  15758. res.set_content("test", "text/plain");
  15759. });
  15760. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15761. auto se = detail::scope_exit([&] {
  15762. svr.stop();
  15763. t.join();
  15764. ASSERT_FALSE(svr.is_running());
  15765. });
  15766. svr.wait_until_ready();
  15767. SSLClient cli("127.0.0.1", PORT);
  15768. std::string cert;
  15769. // A trusted CA that did not sign the server certificate. The server cert
  15770. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15771. // this connection.
  15772. read_file(CLIENT_CA_CERT_FILE, cert);
  15773. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15774. cli.enable_server_certificate_verification(true);
  15775. cli.set_connection_timeout(30);
  15776. auto res = cli.Get("/test");
  15777. ASSERT_FALSE(res);
  15778. }
  15779. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15780. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15781. // CA that failed to come through fails verification instead of trusting them.
  15782. // (wolfSSL does not list the system CAs it loaded.)
  15783. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15784. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15785. ASSERT_TRUE(svr.is_valid());
  15786. auto port = svr.bind_to_any_port("127.0.0.1");
  15787. ASSERT_LT(0, port);
  15788. thread t = thread([&] { svr.listen_after_bind(); });
  15789. auto se = detail::scope_exit([&] {
  15790. svr.stop();
  15791. t.join();
  15792. ASSERT_FALSE(svr.is_running());
  15793. });
  15794. svr.wait_until_ready();
  15795. // The CAs a client trusts once its first request has loaded them
  15796. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15797. Client cli("https://127.0.0.1:" + std::to_string(port));
  15798. setup(cli);
  15799. cli.Get("/");
  15800. return tls::get_ca_names(cli.tls_context()).size();
  15801. };
  15802. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15803. EXPECT_EQ(0u,
  15804. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15805. }
  15806. #endif
  15807. // A TLS setting changed between requests applies to the next one, not just to
  15808. // the next connection
  15809. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15810. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15811. ASSERT_TRUE(svr.is_valid());
  15812. svr.Get("/", [](const Request &req, Response &res) {
  15813. res.set_content(std::to_string(req.remote_port), "text/plain");
  15814. });
  15815. auto port = svr.bind_to_any_port("127.0.0.1");
  15816. ASSERT_LT(0, port);
  15817. thread t = thread([&] { svr.listen_after_bind(); });
  15818. auto se = detail::scope_exit([&] {
  15819. svr.stop();
  15820. t.join();
  15821. ASSERT_FALSE(svr.is_running());
  15822. });
  15823. svr.wait_until_ready();
  15824. SSLClient cli("127.0.0.1", port);
  15825. cli.set_keep_alive(true);
  15826. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15827. cli.enable_server_certificate_verification(false);
  15828. // The port the request went out from, so a new one means a new connection
  15829. auto client_port = [&] {
  15830. auto res = cli.Get("/");
  15831. return res ? res->body : std::string();
  15832. };
  15833. auto last = client_port();
  15834. ASSERT_FALSE(last.empty());
  15835. // Setting a value it already has keeps the connection
  15836. cli.enable_server_certificate_verification(false);
  15837. cli.enable_server_hostname_verification(true);
  15838. EXPECT_EQ(last, client_port());
  15839. cli.enable_server_certificate_verification(true);
  15840. auto res = cli.Get("/");
  15841. EXPECT_FALSE(res);
  15842. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15843. std::string ca;
  15844. read_file(SERVER_CERT2_FILE, ca);
  15845. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15846. last = client_port();
  15847. ASSERT_FALSE(last.empty());
  15848. std::vector<std::function<void()>> setters = {
  15849. [&] { cli.enable_server_hostname_verification(false); },
  15850. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15851. [&] {
  15852. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15853. },
  15854. [&] {
  15855. cli.set_server_certificate_verifier(
  15856. [](const tls::VerifyContext &) { return true; });
  15857. },
  15858. [&] {
  15859. cli.set_session_verifier(
  15860. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15861. },
  15862. };
  15863. for (const auto &setter : setters) {
  15864. setter();
  15865. auto next = client_port();
  15866. ASSERT_FALSE(next.empty());
  15867. EXPECT_NE(last, next);
  15868. last = next;
  15869. }
  15870. cli.set_session_verifier(
  15871. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15872. auto handle = cli.open_stream("GET", "/");
  15873. EXPECT_FALSE(handle.is_valid());
  15874. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15875. }
  15876. // A PEM given to create_ca_store() needs no NUL after it
  15877. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15878. std::string pem;
  15879. read_file(SERVER_CERT2_FILE, pem);
  15880. auto buf = pem + "X";
  15881. auto store = tls::create_ca_store(buf.data(), pem.size());
  15882. EXPECT_TRUE(store != nullptr);
  15883. SSLClient cli("localhost");
  15884. cli.set_ca_cert_store(store);
  15885. }
  15886. // enable_system_ca(false) prevents system CA loading entirely
  15887. TEST(SSLClientTest, DisableSystemCa_Online) {
  15888. SSLClient cli("google.com");
  15889. cli.enable_system_ca(false);
  15890. cli.enable_server_certificate_verification(true);
  15891. auto res = cli.Get("/");
  15892. ASSERT_FALSE(res);
  15893. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15894. // itself when the CA chain is empty
  15895. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15896. res.error() == Error::SSLConnection);
  15897. }
  15898. // The universal Client forwards enable_system_ca()
  15899. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15900. std::string cert;
  15901. read_file(SERVER_CERT2_FILE, cert);
  15902. Client cli("https://google.com");
  15903. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15904. cli.enable_system_ca(true);
  15905. cli.enable_server_certificate_verification(true);
  15906. auto res = cli.Get("/");
  15907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15908. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15909. }
  15910. // The system CA policy must carry over to the client created internally for
  15911. // following a cross-host HTTPS redirect
  15912. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15913. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15914. ASSERT_TRUE(svr.is_valid());
  15915. svr.Get("/index", [&](const Request &, Response &res) {
  15916. res.set_redirect("https://www.google.com/");
  15917. });
  15918. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15919. auto se = detail::scope_exit([&] {
  15920. svr.stop();
  15921. t.join();
  15922. ASSERT_FALSE(svr.is_running());
  15923. });
  15924. svr.wait_until_ready();
  15925. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15926. std::string cert;
  15927. read_file(SERVER_CERT2_FILE, cert);
  15928. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15929. cli.enable_system_ca(true);
  15930. cli.enable_server_certificate_verification(true);
  15931. cli.set_follow_location(true);
  15932. cli.set_connection_timeout(30);
  15933. // Receiving any response proves the redirect client completed the TLS
  15934. // handshake with a system-CA-signed host
  15935. auto res = cli.Get("/index");
  15936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15937. }
  15938. TEST(MultipartFormDataTest, LargeData) {
  15939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15940. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15941. const ContentReader &content_reader) {
  15942. if (req.is_multipart_form_data()) {
  15943. std::vector<FormData> items;
  15944. content_reader(
  15945. [&](const FormData &file) {
  15946. items.push_back(file);
  15947. return true;
  15948. },
  15949. [&](const char *data, size_t data_length) {
  15950. items.back().content.append(data, data_length);
  15951. return true;
  15952. });
  15953. EXPECT_TRUE(std::string(items[0].name) == "document");
  15954. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15955. EXPECT_TRUE(items[0].filename == "2MB_data");
  15956. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15957. EXPECT_TRUE(items[1].name == "hello");
  15958. EXPECT_TRUE(items[1].content == "world");
  15959. EXPECT_TRUE(items[1].filename == "");
  15960. EXPECT_TRUE(items[1].content_type == "");
  15961. } else {
  15962. std::string body;
  15963. content_reader([&](const char *data, size_t data_length) {
  15964. body.append(data, data_length);
  15965. return true;
  15966. });
  15967. }
  15968. });
  15969. auto port = svr.bind_to_any_port(HOST);
  15970. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15971. auto se = detail::scope_exit([&] {
  15972. svr.stop();
  15973. t.join();
  15974. ASSERT_FALSE(svr.is_running());
  15975. });
  15976. svr.wait_until_ready();
  15977. {
  15978. std::string data(1024 * 1024 * 2, '.');
  15979. std::stringstream buffer;
  15980. buffer << data;
  15981. SSLClient cli(HOST, port);
  15982. cli.enable_server_certificate_verification(false);
  15983. UploadFormDataItems items{
  15984. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15985. {"hello", "world", "", ""},
  15986. };
  15987. auto res = cli.Post("/post", items);
  15988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15989. ASSERT_EQ(StatusCode::OK_200, res->status);
  15990. }
  15991. }
  15992. TEST(MultipartFormDataTest, DataProviderItems) {
  15993. std::random_device seed_gen;
  15994. std::mt19937 random(seed_gen());
  15995. std::string rand1;
  15996. rand1.resize(1000);
  15997. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15998. std::string rand2;
  15999. rand2.resize(3000);
  16000. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16002. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16003. const ContentReader &content_reader) {
  16004. ASSERT_FALSE(req.is_multipart_form_data());
  16005. std::string body;
  16006. content_reader([&](const char *data, size_t data_length) {
  16007. body.append(data, data_length);
  16008. return true;
  16009. });
  16010. EXPECT_EQ(body, "");
  16011. });
  16012. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16013. const ContentReader &content_reader) {
  16014. ASSERT_TRUE(req.is_multipart_form_data());
  16015. std::vector<FormData> items;
  16016. content_reader(
  16017. [&](const FormData &file) {
  16018. items.push_back(file);
  16019. return true;
  16020. },
  16021. [&](const char *data, size_t data_length) {
  16022. items.back().content.append(data, data_length);
  16023. return true;
  16024. });
  16025. ASSERT_TRUE(items.size() == 2);
  16026. EXPECT_EQ(std::string(items[0].name), "name1");
  16027. EXPECT_EQ(items[0].content, "Testing123");
  16028. EXPECT_EQ(items[0].filename, "filename1");
  16029. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16030. EXPECT_EQ(items[1].name, "name2");
  16031. EXPECT_EQ(items[1].content, "Testing456");
  16032. EXPECT_EQ(items[1].filename, "");
  16033. EXPECT_EQ(items[1].content_type, "");
  16034. });
  16035. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16036. const ContentReader &content_reader) {
  16037. ASSERT_TRUE(req.is_multipart_form_data());
  16038. std::vector<FormData> items;
  16039. content_reader(
  16040. [&](const FormData &file) {
  16041. items.push_back(file);
  16042. return true;
  16043. },
  16044. [&](const char *data, size_t data_length) {
  16045. items.back().content.append(data, data_length);
  16046. return true;
  16047. });
  16048. ASSERT_TRUE(items.size() == 2);
  16049. EXPECT_EQ(items[0].name, "name3");
  16050. EXPECT_EQ(items[0].content, rand1);
  16051. EXPECT_EQ(items[0].filename, "filename3");
  16052. EXPECT_EQ(items[0].content_type, "");
  16053. EXPECT_EQ(items[1].name, "name4");
  16054. EXPECT_EQ(items[1].content, rand2);
  16055. EXPECT_EQ(items[1].filename, "filename4");
  16056. EXPECT_EQ(items[1].content_type, "");
  16057. });
  16058. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16059. const ContentReader &content_reader) {
  16060. ASSERT_TRUE(req.is_multipart_form_data());
  16061. std::vector<FormData> items;
  16062. content_reader(
  16063. [&](const FormData &file) {
  16064. items.push_back(file);
  16065. return true;
  16066. },
  16067. [&](const char *data, size_t data_length) {
  16068. items.back().content.append(data, data_length);
  16069. return true;
  16070. });
  16071. ASSERT_TRUE(items.size() == 4);
  16072. EXPECT_EQ(std::string(items[0].name), "name1");
  16073. EXPECT_EQ(items[0].content, "Testing123");
  16074. EXPECT_EQ(items[0].filename, "filename1");
  16075. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16076. EXPECT_EQ(items[1].name, "name2");
  16077. EXPECT_EQ(items[1].content, "Testing456");
  16078. EXPECT_EQ(items[1].filename, "");
  16079. EXPECT_EQ(items[1].content_type, "");
  16080. EXPECT_EQ(items[2].name, "name3");
  16081. EXPECT_EQ(items[2].content, rand1);
  16082. EXPECT_EQ(items[2].filename, "filename3");
  16083. EXPECT_EQ(items[2].content_type, "");
  16084. EXPECT_EQ(items[3].name, "name4");
  16085. EXPECT_EQ(items[3].content, rand2);
  16086. EXPECT_EQ(items[3].filename, "filename4");
  16087. EXPECT_EQ(items[3].content_type, "");
  16088. });
  16089. auto port = svr.bind_to_any_port("localhost");
  16090. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16091. auto se = detail::scope_exit([&] {
  16092. svr.stop();
  16093. t.join();
  16094. ASSERT_FALSE(svr.is_running());
  16095. });
  16096. svr.wait_until_ready();
  16097. {
  16098. SSLClient cli("localhost", port);
  16099. cli.enable_server_certificate_verification(false);
  16100. UploadFormDataItems items{
  16101. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16102. {"name2", "Testing456", "", ""}, // not a file
  16103. };
  16104. {
  16105. auto res = cli.Post("/post-none", {}, {}, {});
  16106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16107. ASSERT_EQ(StatusCode::OK_200, res->status);
  16108. }
  16109. FormDataProviderItems providers;
  16110. {
  16111. auto res =
  16112. cli.Post("/post-items", {}, items, providers); // empty providers
  16113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16114. ASSERT_EQ(StatusCode::OK_200, res->status);
  16115. }
  16116. providers.push_back({"name3",
  16117. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16118. // test the offset is given correctly at each step
  16119. if (!offset)
  16120. sink.os.write(rand1.data(), 30);
  16121. else if (offset == 30)
  16122. sink.os.write(rand1.data() + 30, 300);
  16123. else if (offset == 330)
  16124. sink.os.write(rand1.data() + 330, 670);
  16125. else if (offset == rand1.size())
  16126. sink.done();
  16127. return true;
  16128. },
  16129. "filename3",
  16130. {}});
  16131. providers.push_back({"name4",
  16132. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16133. // test the offset is given correctly at each step
  16134. if (!offset)
  16135. sink.os.write(rand2.data(), 2000);
  16136. else if (offset == 2000)
  16137. sink.os.write(rand2.data() + 2000, 1);
  16138. else if (offset == 2001)
  16139. sink.os.write(rand2.data() + 2001, 999);
  16140. else if (offset == rand2.size())
  16141. sink.done();
  16142. return true;
  16143. },
  16144. "filename4",
  16145. {}});
  16146. {
  16147. auto res = cli.Post("/post-providers", {}, {}, providers);
  16148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16149. ASSERT_EQ(StatusCode::OK_200, res->status);
  16150. }
  16151. {
  16152. auto res = cli.Post("/post-both", {}, items, providers);
  16153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16154. ASSERT_EQ(StatusCode::OK_200, res->status);
  16155. }
  16156. }
  16157. }
  16158. TEST(MultipartFormDataTest, BadHeader) {
  16159. Server svr;
  16160. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16161. res.set_content("ok", "text/plain");
  16162. });
  16163. thread t = thread([&] { svr.listen(HOST, PORT); });
  16164. auto se = detail::scope_exit([&] {
  16165. svr.stop();
  16166. t.join();
  16167. ASSERT_FALSE(svr.is_running());
  16168. });
  16169. svr.wait_until_ready();
  16170. const std::string body =
  16171. "This is the preamble. It is to be ignored, though it\r\n"
  16172. "is a handy place for composition agents to include an\r\n"
  16173. "explanatory note to non-MIME conformant readers.\r\n"
  16174. "\r\n"
  16175. "\r\n"
  16176. "--simple boundary\r\n"
  16177. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16178. ": BAD...\r\n"
  16179. "\r\n"
  16180. "value1\r\n"
  16181. "--simple boundary\r\n"
  16182. "Content-Disposition: form-data; name=\"field2\"; "
  16183. "filename=\"example.txt\"\r\n"
  16184. "\r\n"
  16185. "value2\r\n"
  16186. "--simple boundary--\r\n"
  16187. "This is the epilogue. It is also to be ignored.\r\n";
  16188. std::string content_type =
  16189. R"(multipart/form-data; boundary="simple boundary")";
  16190. Client cli(HOST, PORT);
  16191. auto res = cli.Post("/post", body, content_type.c_str());
  16192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16193. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16194. }
  16195. TEST(MultipartFormDataTest, WithPreamble) {
  16196. Server svr;
  16197. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16198. res.set_content("ok", "text/plain");
  16199. });
  16200. thread t = thread([&] { svr.listen(HOST, PORT); });
  16201. auto se = detail::scope_exit([&] {
  16202. svr.stop();
  16203. t.join();
  16204. ASSERT_FALSE(svr.is_running());
  16205. });
  16206. svr.wait_until_ready();
  16207. const std::string body =
  16208. "This is the preamble. It is to be ignored, though it\r\n"
  16209. "is a handy place for composition agents to include an\r\n"
  16210. "explanatory note to non-MIME conformant readers.\r\n"
  16211. "\r\n"
  16212. "\r\n"
  16213. "--simple boundary\r\n"
  16214. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16215. "\r\n"
  16216. "value1\r\n"
  16217. "--simple boundary\r\n"
  16218. "Content-Disposition: form-data; name=\"field2\"; "
  16219. "filename=\"example.txt\"\r\n"
  16220. "\r\n"
  16221. "value2\r\n"
  16222. "--simple boundary--\r\n"
  16223. "This is the epilogue. It is also to be ignored.\r\n";
  16224. std::string content_type =
  16225. R"(multipart/form-data; boundary="simple boundary")";
  16226. Client cli(HOST, PORT);
  16227. auto res = cli.Post("/post", body, content_type.c_str());
  16228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16229. EXPECT_EQ(StatusCode::OK_200, res->status);
  16230. }
  16231. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16233. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16234. const ContentReader &content_reader) {
  16235. if (req.is_multipart_form_data()) {
  16236. std::vector<FormData> items;
  16237. content_reader(
  16238. [&](const FormData &file) {
  16239. items.push_back(file);
  16240. return true;
  16241. },
  16242. [&](const char *data, size_t data_length) {
  16243. items.back().content.append(data, data_length);
  16244. return true;
  16245. });
  16246. EXPECT_TRUE(std::string(items[0].name) == "document");
  16247. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16248. EXPECT_TRUE(items[0].filename == "2MB_data");
  16249. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16250. EXPECT_TRUE(items[1].name == "hello");
  16251. EXPECT_TRUE(items[1].content == "world");
  16252. EXPECT_TRUE(items[1].filename == "");
  16253. EXPECT_TRUE(items[1].content_type == "");
  16254. } else {
  16255. std::string body;
  16256. content_reader([&](const char *data, size_t data_length) {
  16257. body.append(data, data_length);
  16258. return true;
  16259. });
  16260. }
  16261. });
  16262. auto port = svr.bind_to_any_port("localhost");
  16263. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16264. auto se = detail::scope_exit([&] {
  16265. svr.stop();
  16266. t.join();
  16267. ASSERT_FALSE(svr.is_running());
  16268. });
  16269. svr.wait_until_ready();
  16270. {
  16271. std::string data(1024 * 1024 * 2, '.');
  16272. std::stringstream buffer;
  16273. buffer << data;
  16274. SSLClient cli("localhost", port);
  16275. cli.enable_server_certificate_verification(false);
  16276. UploadFormDataItems items{
  16277. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16278. {"hello", "world", "", ""},
  16279. };
  16280. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16282. ASSERT_EQ(StatusCode::OK_200, res->status);
  16283. }
  16284. }
  16285. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16286. std::string data(1024 * 1024 * 2, '&');
  16287. std::stringstream buffer;
  16288. buffer << data;
  16289. Client cli("https://localhost:8080");
  16290. UploadFormDataItems items{
  16291. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16292. {"hello", "world", "", ""},
  16293. };
  16294. for (const char &c : " \t\r\n") {
  16295. auto res =
  16296. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16297. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16298. ASSERT_FALSE(res);
  16299. }
  16300. }
  16301. TEST(MultipartFormDataTest, PutFormData) {
  16302. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16303. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16304. const ContentReader &content_reader) {
  16305. if (req.is_multipart_form_data()) {
  16306. std::vector<FormData> items;
  16307. content_reader(
  16308. [&](const FormData &file) {
  16309. items.push_back(file);
  16310. return true;
  16311. },
  16312. [&](const char *data, size_t data_length) {
  16313. items.back().content.append(data, data_length);
  16314. return true;
  16315. });
  16316. EXPECT_TRUE(std::string(items[0].name) == "document");
  16317. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16318. EXPECT_TRUE(items[0].filename == "2MB_data");
  16319. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16320. EXPECT_TRUE(items[1].name == "hello");
  16321. EXPECT_TRUE(items[1].content == "world");
  16322. EXPECT_TRUE(items[1].filename == "");
  16323. EXPECT_TRUE(items[1].content_type == "");
  16324. } else {
  16325. std::string body;
  16326. content_reader([&](const char *data, size_t data_length) {
  16327. body.append(data, data_length);
  16328. return true;
  16329. });
  16330. }
  16331. });
  16332. auto port = svr.bind_to_any_port("localhost");
  16333. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16334. auto se = detail::scope_exit([&] {
  16335. svr.stop();
  16336. t.join();
  16337. ASSERT_FALSE(svr.is_running());
  16338. });
  16339. svr.wait_until_ready();
  16340. {
  16341. std::string data(1024 * 1024 * 2, '&');
  16342. std::stringstream buffer;
  16343. buffer << data;
  16344. SSLClient cli("localhost", port);
  16345. cli.enable_server_certificate_verification(false);
  16346. UploadFormDataItems items{
  16347. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16348. {"hello", "world", "", ""},
  16349. };
  16350. auto res = cli.Put("/put", items);
  16351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16352. ASSERT_EQ(StatusCode::OK_200, res->status);
  16353. }
  16354. }
  16355. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16357. svr.Put("/put_customboundary",
  16358. [&](const Request &req, const Response & /*res*/,
  16359. const ContentReader &content_reader) {
  16360. if (req.is_multipart_form_data()) {
  16361. std::vector<FormData> items;
  16362. content_reader(
  16363. [&](const FormData &file) {
  16364. items.push_back(file);
  16365. return true;
  16366. },
  16367. [&](const char *data, size_t data_length) {
  16368. items.back().content.append(data, data_length);
  16369. return true;
  16370. });
  16371. EXPECT_TRUE(std::string(items[0].name) == "document");
  16372. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16373. EXPECT_TRUE(items[0].filename == "2MB_data");
  16374. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16375. EXPECT_TRUE(items[1].name == "hello");
  16376. EXPECT_TRUE(items[1].content == "world");
  16377. EXPECT_TRUE(items[1].filename == "");
  16378. EXPECT_TRUE(items[1].content_type == "");
  16379. } else {
  16380. std::string body;
  16381. content_reader([&](const char *data, size_t data_length) {
  16382. body.append(data, data_length);
  16383. return true;
  16384. });
  16385. }
  16386. });
  16387. auto port = svr.bind_to_any_port("localhost");
  16388. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16389. auto se = detail::scope_exit([&] {
  16390. svr.stop();
  16391. t.join();
  16392. ASSERT_FALSE(svr.is_running());
  16393. });
  16394. svr.wait_until_ready();
  16395. {
  16396. std::string data(1024 * 1024 * 2, '&');
  16397. std::stringstream buffer;
  16398. buffer << data;
  16399. SSLClient cli("localhost", port);
  16400. cli.enable_server_certificate_verification(false);
  16401. UploadFormDataItems items{
  16402. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16403. {"hello", "world", "", ""},
  16404. };
  16405. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16407. ASSERT_EQ(StatusCode::OK_200, res->status);
  16408. }
  16409. }
  16410. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16411. std::string data(1024 * 1024 * 2, '&');
  16412. std::stringstream buffer;
  16413. buffer << data;
  16414. Client cli("https://localhost:8080");
  16415. cli.enable_server_certificate_verification(false);
  16416. UploadFormDataItems items{
  16417. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16418. {"hello", "world", "", ""},
  16419. };
  16420. for (const char &c : " \t\r\n") {
  16421. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16422. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16423. ASSERT_FALSE(res);
  16424. }
  16425. }
  16426. TEST(MultipartFormDataTest, AlternateFilename) {
  16427. auto handled = false;
  16428. Server svr;
  16429. svr.Post("/test", [&](const Request &req, Response &res) {
  16430. ASSERT_EQ(2u, req.form.files.size());
  16431. ASSERT_EQ(1u, req.form.fields.size());
  16432. // Test files
  16433. const auto &file1 = req.form.get_file("file1");
  16434. ASSERT_EQ("file1", file1.name);
  16435. ASSERT_EQ("A.txt", file1.filename);
  16436. ASSERT_EQ("text/plain", file1.content_type);
  16437. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16438. const auto &file2 = req.form.get_file("file2");
  16439. ASSERT_EQ("file2", file2.name);
  16440. ASSERT_EQ("a.html", file2.filename);
  16441. ASSERT_EQ("text/html", file2.content_type);
  16442. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16443. file2.content);
  16444. // Test text field
  16445. const auto &text = req.form.get_field("text");
  16446. ASSERT_EQ("text default", text);
  16447. res.set_content("ok", "text/plain");
  16448. handled = true;
  16449. });
  16450. thread t = thread([&] { svr.listen(HOST, PORT); });
  16451. auto se = detail::scope_exit([&] {
  16452. svr.stop();
  16453. t.join();
  16454. ASSERT_FALSE(svr.is_running());
  16455. ASSERT_TRUE(handled);
  16456. });
  16457. svr.wait_until_ready();
  16458. auto req = "POST /test HTTP/1.1\r\n"
  16459. "Host: localhost\r\n"
  16460. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16461. "Content-Length: 399\r\n"
  16462. "\r\n"
  16463. "----------\r\n"
  16464. "Content-Disposition: form-data; name=\"text\"\r\n"
  16465. "\r\n"
  16466. "text default\r\n"
  16467. "----------\r\n"
  16468. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16469. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16470. "Content-Type: text/plain\r\n"
  16471. "\r\n"
  16472. "Content of a.txt.\r\n"
  16473. "\r\n"
  16474. "----------\r\n"
  16475. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16476. "\"a.html\"\r\n"
  16477. "Content-Type: text/html\r\n"
  16478. "\r\n"
  16479. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16480. "\r\n"
  16481. "------------\r\n";
  16482. ASSERT_TRUE(send_request(1, req));
  16483. }
  16484. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16485. auto handled = false;
  16486. Server svr;
  16487. svr.Post("/test", [&](const Request &req, Response &res) {
  16488. // Case-insensitive "utf-8''" prefix with a long value
  16489. const auto &file = req.form.get_file("file1");
  16490. ASSERT_EQ("file1", file.name);
  16491. // 8000 chars exercises both the Content-Disposition parser and the
  16492. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16493. // Prior to the fix, std::regex_match on this header would cause O(N)
  16494. // stack recursion in libstdc++, leading to SIGSEGV.
  16495. std::string expected_filename(8000, 'A');
  16496. ASSERT_EQ(expected_filename, file.filename);
  16497. res.set_content("ok", "text/plain");
  16498. handled = true;
  16499. });
  16500. thread t = thread([&] { svr.listen(HOST, PORT); });
  16501. auto se = detail::scope_exit([&] {
  16502. svr.stop();
  16503. t.join();
  16504. ASSERT_FALSE(svr.is_running());
  16505. ASSERT_TRUE(handled);
  16506. });
  16507. svr.wait_until_ready();
  16508. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16509. // Regression test for GHSA-qq6v-r583-3h69
  16510. std::string long_filename(8000, 'A');
  16511. std::string body = "----------\r\n"
  16512. "Content-Disposition: form-data; name=\"file1\"; "
  16513. "filename*=\"Utf-8''" +
  16514. long_filename +
  16515. "\"\r\n"
  16516. "\r\n"
  16517. "hello\r\n"
  16518. "------------\r\n";
  16519. auto req = "POST /test HTTP/1.1\r\n"
  16520. "Host: localhost\r\n"
  16521. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16522. "Content-Length: " +
  16523. std::to_string(body.size()) + "\r\n\r\n" + body;
  16524. ASSERT_TRUE(send_request(1, req));
  16525. }
  16526. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16527. auto handled = false;
  16528. Server svr;
  16529. svr.Post("/test", [&](const Request &req, Response &) {
  16530. ASSERT_EQ(2u, req.form.fields.size());
  16531. const auto &text1 = req.form.get_field("text1");
  16532. ASSERT_EQ("text1", text1);
  16533. const auto &text2 = req.form.get_field("text2");
  16534. ASSERT_EQ("text2", text2);
  16535. handled = true;
  16536. });
  16537. thread t = thread([&] { svr.listen(HOST, PORT); });
  16538. auto se = detail::scope_exit([&] {
  16539. svr.stop();
  16540. t.join();
  16541. ASSERT_FALSE(svr.is_running());
  16542. ASSERT_TRUE(handled);
  16543. });
  16544. svr.wait_until_ready();
  16545. auto req = "POST /test HTTP/1.1\r\n"
  16546. "Host: localhost\r\n"
  16547. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16548. "Content-Length: 146\r\n"
  16549. "\r\n----------\r\n"
  16550. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16551. "\r\n"
  16552. "text1"
  16553. "\r\n----------\r\n"
  16554. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16555. "\r\n"
  16556. "text2"
  16557. "\r\n------------";
  16558. std::string response;
  16559. ASSERT_TRUE(send_request(1, req, &response));
  16560. ASSERT_EQ("200", response.substr(9, 3));
  16561. }
  16562. TEST(MultipartFormDataTest, ContentLength) {
  16563. auto handled = false;
  16564. Server svr;
  16565. svr.Post("/test", [&](const Request &req, Response &) {
  16566. ASSERT_EQ(2u, req.form.fields.size());
  16567. const auto &text1 = req.form.get_field("text1");
  16568. ASSERT_EQ("text1", text1);
  16569. const auto &text2 = req.form.get_field("text2");
  16570. ASSERT_EQ("text2", text2);
  16571. handled = true;
  16572. });
  16573. thread t = thread([&] { svr.listen(HOST, PORT); });
  16574. auto se = detail::scope_exit([&] {
  16575. svr.stop();
  16576. t.join();
  16577. ASSERT_FALSE(svr.is_running());
  16578. ASSERT_TRUE(handled);
  16579. });
  16580. svr.wait_until_ready();
  16581. auto req = "POST /test HTTP/1.1\r\n"
  16582. "Host: localhost\r\n"
  16583. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16584. "Content-Length: 167\r\n"
  16585. "\r\n----------\r\n"
  16586. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16587. "Content-Length: 5\r\n"
  16588. "\r\n"
  16589. "text1"
  16590. "\r\n----------\r\n"
  16591. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16592. "\r\n"
  16593. "text2"
  16594. "\r\n------------\r\n";
  16595. std::string response;
  16596. ASSERT_TRUE(send_request(1, req, &response));
  16597. ASSERT_EQ("200", response.substr(9, 3));
  16598. }
  16599. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16600. auto handled = false;
  16601. Server svr;
  16602. svr.Post("/test", [&](const Request &req, Response &) {
  16603. ASSERT_EQ(2u, req.form.fields.size());
  16604. const auto &text1 = req.form.get_field("text1");
  16605. ASSERT_EQ("text1", text1);
  16606. // TODO: Add header access for text fields if needed
  16607. const auto &text2 = req.form.get_field("text2");
  16608. ASSERT_EQ("text2", text2);
  16609. // TODO: Header access for text fields needs to be implemented
  16610. // auto &headers = it->second.headers;
  16611. // ASSERT_EQ(3U, headers.size());
  16612. // auto custom_header = headers.find("x-whatever");
  16613. // ASSERT_TRUE(custom_header != headers.end());
  16614. // ASSERT_NE("customvalue", custom_header->second);
  16615. // ASSERT_EQ("CustomValue", custom_header->second);
  16616. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16617. handled = true;
  16618. });
  16619. thread t = thread([&] { svr.listen(HOST, PORT); });
  16620. auto se = detail::scope_exit([&] {
  16621. svr.stop();
  16622. t.join();
  16623. ASSERT_FALSE(svr.is_running());
  16624. ASSERT_TRUE(handled);
  16625. });
  16626. svr.wait_until_ready();
  16627. auto req = "POST /test HTTP/1.1\r\n"
  16628. "Host: localhost\r\n"
  16629. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16630. "Content-Length: 232\r\n"
  16631. "\r\n----------\r\n"
  16632. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16633. "Content-Length: 5\r\n"
  16634. "X-Test: 1\r\n"
  16635. "\r\n"
  16636. "text1"
  16637. "\r\n----------\r\n"
  16638. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16639. "Content-Type: text/plain\r\n"
  16640. "X-Whatever: CustomValue\r\n"
  16641. "\r\n"
  16642. "text2"
  16643. "\r\n------------\r\n"
  16644. "That should be disregarded. Not even read";
  16645. std::string response;
  16646. ASSERT_TRUE(send_request(1, req, &response));
  16647. ASSERT_EQ("200", response.substr(9, 3));
  16648. }
  16649. TEST(MultipartFormDataTest, LargeHeader) {
  16650. auto handled = false;
  16651. Server svr;
  16652. svr.Post("/test", [&](const Request &req, Response &) {
  16653. ASSERT_EQ(1u, req.form.fields.size());
  16654. const auto &text = req.form.get_field("name1");
  16655. ASSERT_EQ("text1", text);
  16656. handled = true;
  16657. });
  16658. thread t = thread([&] { svr.listen(HOST, PORT); });
  16659. auto se = detail::scope_exit([&] {
  16660. svr.stop();
  16661. t.join();
  16662. ASSERT_FALSE(svr.is_running());
  16663. ASSERT_TRUE(handled);
  16664. });
  16665. svr.wait_until_ready();
  16666. auto boundary = std::string("cpp-httplib-multipart-data");
  16667. std::string content = "--" + boundary +
  16668. "\r\n"
  16669. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16670. "\r\n"
  16671. "text1\r\n"
  16672. "--" +
  16673. boundary + "--\r\n";
  16674. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16675. "Host: localhost\r\n"
  16676. "Content-Type: multipart/form-data;boundary=" +
  16677. boundary +
  16678. "\r\n"
  16679. "Content-Length: " +
  16680. std::to_string(content.size()) +
  16681. "\r\n"
  16682. "Dummy-Header: ";
  16683. std::string header_suffix = "\r\n"
  16684. "\r\n";
  16685. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16686. size_t header_dummy_size =
  16687. read_buff_size -
  16688. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16689. auto header_dummy = std::string(header_dummy_size, '@');
  16690. auto req = header_prefix + header_dummy + header_suffix + content;
  16691. std::string response;
  16692. ASSERT_TRUE(send_request(1, req, &response));
  16693. ASSERT_EQ("200", response.substr(9, 3));
  16694. }
  16695. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16696. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16697. // (not chunked Transfer-Encoding) after the streaming refactor.
  16698. auto handled = false;
  16699. Server svr;
  16700. svr.Post("/upload", [&](const Request &req, Response &res) {
  16701. auto cl_it = req.headers.find("Content-Length");
  16702. EXPECT_TRUE(cl_it != req.headers.end());
  16703. auto te_it = req.headers.find("Transfer-Encoding");
  16704. EXPECT_TRUE(te_it == req.headers.end());
  16705. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16706. res.set_content("ok", "text/plain");
  16707. handled = true;
  16708. });
  16709. auto port = svr.bind_to_any_port(HOST);
  16710. auto t = thread([&] { svr.listen_after_bind(); });
  16711. auto se = detail::scope_exit([&] {
  16712. svr.stop();
  16713. t.join();
  16714. ASSERT_FALSE(svr.is_running());
  16715. ASSERT_TRUE(handled);
  16716. });
  16717. svr.wait_until_ready();
  16718. UploadFormDataItems items = {
  16719. {"field1", "hello", "", "text/plain"},
  16720. {"file1", "world", "test.txt", "application/octet-stream"},
  16721. };
  16722. Client cli(HOST, port);
  16723. auto res = cli.Post("/upload", {}, items);
  16724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16725. EXPECT_EQ(StatusCode::OK_200, res->status);
  16726. }
  16727. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16728. // Verify that make_multipart_content_provider coalesces many small segments
  16729. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16730. constexpr size_t kItemCount = 1000;
  16731. UploadFormDataItems items;
  16732. items.reserve(kItemCount);
  16733. for (size_t i = 0; i < kItemCount; i++) {
  16734. items.push_back(
  16735. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16736. }
  16737. const std::string boundary = "----test-boundary";
  16738. auto content_length = detail::get_multipart_content_length(items, boundary);
  16739. auto provider = detail::make_multipart_content_provider(items, boundary);
  16740. // Drive the provider the same way write_content_with_progress does
  16741. size_t write_count = 0;
  16742. size_t total_bytes = 0;
  16743. DataSink sink;
  16744. size_t offset = 0;
  16745. sink.write = [&](const char *d, size_t l) -> bool {
  16746. (void)d;
  16747. write_count++;
  16748. total_bytes += l;
  16749. offset += l;
  16750. return true;
  16751. };
  16752. sink.is_writable = []() -> bool { return true; };
  16753. while (offset < content_length) {
  16754. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16755. }
  16756. EXPECT_EQ(content_length, total_bytes);
  16757. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16758. // With buffering into 64KB blocks, write_count should be much smaller.
  16759. auto segment_count = 3 * kItemCount + 1;
  16760. EXPECT_LT(write_count, segment_count / 10);
  16761. }
  16762. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16763. // Integration test: send many UploadFormDataItems and verify the server
  16764. // receives all of them correctly (#2410).
  16765. constexpr size_t kItemCount = 500;
  16766. auto handled = false;
  16767. Server svr;
  16768. svr.Post("/upload", [&](const Request &req, Response &res) {
  16769. EXPECT_EQ(kItemCount, req.form.fields.size());
  16770. for (size_t i = 0; i < kItemCount; i++) {
  16771. auto key = "field" + std::to_string(i);
  16772. auto val = "value" + std::to_string(i);
  16773. auto it = req.form.fields.find(key);
  16774. if (it != req.form.fields.end()) {
  16775. EXPECT_EQ(val, it->second.content);
  16776. } else {
  16777. ADD_FAILURE() << "Missing field: " << key;
  16778. }
  16779. }
  16780. res.set_content("ok", "text/plain");
  16781. handled = true;
  16782. });
  16783. auto port = svr.bind_to_any_port(HOST);
  16784. auto t = thread([&] { svr.listen_after_bind(); });
  16785. auto se = detail::scope_exit([&] {
  16786. svr.stop();
  16787. t.join();
  16788. ASSERT_FALSE(svr.is_running());
  16789. ASSERT_TRUE(handled);
  16790. });
  16791. svr.wait_until_ready();
  16792. UploadFormDataItems items;
  16793. items.reserve(kItemCount);
  16794. for (size_t i = 0; i < kItemCount; i++) {
  16795. items.push_back(
  16796. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16797. }
  16798. Client cli(HOST, port);
  16799. auto res = cli.Post("/upload", items);
  16800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16801. EXPECT_EQ(StatusCode::OK_200, res->status);
  16802. }
  16803. TEST(MultipartFormDataTest, MakeFileProvider) {
  16804. // Verify make_file_provider sends a file's contents correctly.
  16805. const std::string file_content(4096, 'Z');
  16806. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16807. {
  16808. std::ofstream ofs(tmp_path, std::ios::binary);
  16809. ofs.write(file_content.data(),
  16810. static_cast<std::streamsize>(file_content.size()));
  16811. }
  16812. auto handled = false;
  16813. Server svr;
  16814. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16815. const ContentReader &content_reader) {
  16816. ASSERT_TRUE(req.is_multipart_form_data());
  16817. std::vector<FormData> items;
  16818. content_reader(
  16819. [&](const FormData &file) {
  16820. items.push_back(file);
  16821. return true;
  16822. },
  16823. [&](const char *data, size_t data_length) {
  16824. items.back().content.append(data, data_length);
  16825. return true;
  16826. });
  16827. ASSERT_EQ(1u, items.size());
  16828. EXPECT_EQ("myfile", items[0].name);
  16829. EXPECT_EQ("data.bin", items[0].filename);
  16830. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16831. EXPECT_EQ(file_content, items[0].content);
  16832. handled = true;
  16833. });
  16834. auto port = svr.bind_to_any_port(HOST);
  16835. auto t = thread([&] { svr.listen_after_bind(); });
  16836. auto se = detail::scope_exit([&] {
  16837. svr.stop();
  16838. t.join();
  16839. ASSERT_FALSE(svr.is_running());
  16840. ASSERT_TRUE(handled);
  16841. std::remove(tmp_path.c_str());
  16842. });
  16843. svr.wait_until_ready();
  16844. FormDataProviderItems providers;
  16845. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16846. "application/octet-stream"));
  16847. Client cli(HOST, port);
  16848. auto res = cli.Post("/upload", {}, {}, providers);
  16849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16850. EXPECT_EQ(StatusCode::OK_200, res->status);
  16851. }
  16852. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16853. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16854. // (100) headers is rejected with a 400 Bad Request response.
  16855. Server svr;
  16856. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16857. res.set_content("ok", "text/plain");
  16858. });
  16859. thread t = thread([&] { svr.listen(HOST, PORT); });
  16860. auto se = detail::scope_exit([&] {
  16861. svr.stop();
  16862. t.join();
  16863. ASSERT_FALSE(svr.is_running());
  16864. });
  16865. svr.wait_until_ready();
  16866. // Build a multipart part with 101 custom headers (exceeding
  16867. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16868. std::stringstream body;
  16869. body << "--simpleboundary\r\n"
  16870. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16871. for (int i = 0; i < 101; i++) {
  16872. body << "X-Custom-Header-" << i << ": value\r\n";
  16873. }
  16874. body << "\r\n"
  16875. << "value1\r\n"
  16876. << "--simpleboundary--\r\n";
  16877. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16878. Client cli(HOST, PORT);
  16879. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16881. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16882. }
  16883. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16884. // A body that never contains the declared boundary must not be accumulated
  16885. // while the parser waits for it. Buffering it would also make every read
  16886. // rescan everything seen so far, which is quadratic in the body size.
  16887. Server svr;
  16888. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16889. res.set_content("ok", "text/plain");
  16890. });
  16891. auto port = svr.bind_to_any_port(HOST);
  16892. thread t = thread([&] { svr.listen_after_bind(); });
  16893. auto se = detail::scope_exit([&] {
  16894. svr.stop();
  16895. t.join();
  16896. ASSERT_FALSE(svr.is_running());
  16897. });
  16898. svr.wait_until_ready();
  16899. Client cli(HOST, port);
  16900. cli.set_read_timeout(60, 0);
  16901. cli.set_write_timeout(60, 0);
  16902. // '-' is the worst case: it matches the first character of the boundary, so
  16903. // every position has to be checked against it.
  16904. auto post_dashes = [&](size_t size) {
  16905. const std::string body(size, '-');
  16906. auto start = std::chrono::steady_clock::now();
  16907. auto res =
  16908. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16909. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16910. std::chrono::steady_clock::now() - start)
  16911. .count();
  16912. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16913. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16914. return ms;
  16915. };
  16916. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16917. // Windows.
  16918. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16919. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16920. // Comparing the two sizes rather than checking an absolute duration keeps
  16921. // this meaningful across build types and CI load, both of which move the
  16922. // absolute numbers by more than an order of magnitude. Four times the bytes
  16923. // costs about four times the time when parsing is linear, and about sixteen
  16924. // times when the body is buffered and rescanned.
  16925. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16926. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16927. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16928. << "ms, which suggests the body is being buffered and rescanned";
  16929. }
  16930. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16931. // A boundary can only be followed by CRLF or by "--", so anything else is
  16932. // malformed no matter what comes next. The parser must say so right away
  16933. // instead of buffering the rest of the declared body.
  16934. Server svr;
  16935. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16936. res.set_content("ok", "text/plain");
  16937. });
  16938. auto port = svr.bind_to_any_port(HOST);
  16939. thread t = thread([&] { svr.listen_after_bind(); });
  16940. auto se = detail::scope_exit([&] {
  16941. svr.stop();
  16942. t.join();
  16943. ASSERT_FALSE(svr.is_running());
  16944. });
  16945. svr.wait_until_ready();
  16946. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16947. // buffers instead of failing would still be waiting for the remaining bytes.
  16948. const std::string body = "--zzzz\r\n"
  16949. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16950. "\r\n"
  16951. "text1"
  16952. "\r\n--zzzzXX";
  16953. const std::string req = "POST /post HTTP/1.1\r\n"
  16954. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16955. "Content-Length: 1048576\r\n"
  16956. "\r\n" +
  16957. body;
  16958. std::string response;
  16959. ASSERT_TRUE(send_request(3, req, &response, port));
  16960. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16961. EXPECT_EQ("400", response.substr(9, 3));
  16962. }
  16963. // Posts a multipart body split into two writes, so that the server sees the
  16964. // split at whatever offset the caller chose, and expects the single "text1"
  16965. // field to come through.
  16966. static void expect_split_multipart_ok(const std::string &body1,
  16967. const std::string &body2) {
  16968. auto handled = false;
  16969. Server svr;
  16970. svr.Post("/post", [&](const Request &req, Response &) {
  16971. EXPECT_EQ(1u, req.form.fields.size());
  16972. EXPECT_EQ("text1", req.form.get_field("text1"));
  16973. handled = true;
  16974. });
  16975. auto port = svr.bind_to_any_port(HOST);
  16976. thread t = thread([&] { svr.listen_after_bind(); });
  16977. auto se = detail::scope_exit([&] {
  16978. svr.stop();
  16979. t.join();
  16980. ASSERT_FALSE(svr.is_running());
  16981. ASSERT_TRUE(handled);
  16982. });
  16983. svr.wait_until_ready();
  16984. // "Connection: close" makes the server close once it has answered, so the
  16985. // response drain ends immediately instead of idling until the read timeout.
  16986. const std::string head =
  16987. "POST /post HTTP/1.1\r\n"
  16988. "Host: localhost\r\n"
  16989. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16990. "Connection: close\r\n"
  16991. "Content-Length: " +
  16992. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16993. std::string response;
  16994. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16995. ASSERT_GE(response.size(), 12u) << "no response";
  16996. EXPECT_EQ("200", response.substr(9, 3));
  16997. }
  16998. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16999. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17000. // ignored, including when it does not arrive in the same read as the
  17001. // close-delimiter itself.
  17002. expect_split_multipart_ok("--zzzz\r\n"
  17003. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17004. "\r\n"
  17005. "text1"
  17006. "\r\n--zzzz--",
  17007. "\r\nthis epilogue must be ignored\r\n");
  17008. }
  17009. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17010. // The initial boundary may be preceded by a preamble of any length and may
  17011. // straddle a read boundary. Discarding data while waiting for it must not
  17012. // throw away a partial boundary sitting at the end of the buffer.
  17013. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17014. "zz\r\n"
  17015. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17016. "\r\n"
  17017. "text1"
  17018. "\r\n--zzzz--\r\n");
  17019. }
  17020. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17021. // The received boundary was only checked for being non-empty, so it could be
  17022. // as long as a header is allowed to be. The parser scans the body for
  17023. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17024. // costs a nearly full comparison at nearly every position, making the
  17025. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17026. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17027. Server svr;
  17028. svr.Post("/post", [](const Request &req, Response &res) {
  17029. EXPECT_EQ(1u, req.form.fields.size());
  17030. EXPECT_EQ("text1", req.form.get_field("text1"));
  17031. res.set_content("ok", "text/plain");
  17032. });
  17033. auto port = svr.bind_to_any_port(HOST);
  17034. thread t = thread([&] { svr.listen_after_bind(); });
  17035. auto se = detail::scope_exit([&] {
  17036. svr.stop();
  17037. t.join();
  17038. ASSERT_FALSE(svr.is_running());
  17039. });
  17040. svr.wait_until_ready();
  17041. Client cli(HOST, port);
  17042. auto post_with_boundary_of_length = [&](size_t len) {
  17043. const std::string boundary(len, 'a');
  17044. const std::string body =
  17045. "--" + boundary +
  17046. "\r\n"
  17047. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17048. "\r\n"
  17049. "text1"
  17050. "\r\n--" +
  17051. boundary + "--\r\n";
  17052. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17053. };
  17054. auto res = post_with_boundary_of_length(70);
  17055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17056. EXPECT_EQ(StatusCode::OK_200, res->status);
  17057. res = post_with_boundary_of_length(71);
  17058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17059. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17060. }
  17061. TEST(MakeFileBodyTest, Basic) {
  17062. const std::string file_content(4096, 'Z');
  17063. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17064. {
  17065. std::ofstream ofs(tmp_path, std::ios::binary);
  17066. ofs.write(file_content.data(),
  17067. static_cast<std::streamsize>(file_content.size()));
  17068. }
  17069. auto handled = false;
  17070. Server svr;
  17071. svr.Post("/upload", [&](const Request &req, Response &res) {
  17072. EXPECT_EQ(file_content, req.body);
  17073. handled = true;
  17074. res.status = StatusCode::OK_200;
  17075. });
  17076. auto port = svr.bind_to_any_port(HOST);
  17077. auto t = thread([&] { svr.listen_after_bind(); });
  17078. auto se = detail::scope_exit([&] {
  17079. svr.stop();
  17080. t.join();
  17081. ASSERT_FALSE(svr.is_running());
  17082. ASSERT_TRUE(handled);
  17083. std::remove(tmp_path.c_str());
  17084. });
  17085. svr.wait_until_ready();
  17086. auto fb = make_file_body(tmp_path);
  17087. ASSERT_GT(fb.first, 0u);
  17088. Client cli(HOST, port);
  17089. auto res =
  17090. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17092. EXPECT_EQ(StatusCode::OK_200, res->status);
  17093. }
  17094. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17095. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17096. {
  17097. std::ofstream ofs(path, std::ios::binary);
  17098. const std::string content(100, 'A');
  17099. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17100. }
  17101. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17102. auto body = make_file_body(path);
  17103. ASSERT_EQ(100u, body.first);
  17104. ASSERT_TRUE(static_cast<bool>(body.second));
  17105. // Rewritten shorter after its length was measured - and, on a server, after
  17106. // that length has already gone out as Content-Length.
  17107. {
  17108. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17109. const std::string content(10, 'A');
  17110. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17111. }
  17112. std::string written;
  17113. DataSink sink;
  17114. sink.write = [&](const char *d, size_t l) {
  17115. written.append(d, l);
  17116. return true;
  17117. };
  17118. // The provider has to report failure. write_content_with_progress() advances
  17119. // its offset only by what was written, so a provider that returns true
  17120. // without completing the length it promised is called again straight away,
  17121. // and again.
  17122. EXPECT_FALSE(body.second(0, body.first, sink));
  17123. EXPECT_EQ(std::string(10, 'A'), written);
  17124. }
  17125. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17126. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17127. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17128. {
  17129. std::ofstream ofs(path, std::ios::binary);
  17130. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17131. }
  17132. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17133. auto body = make_file_body(path);
  17134. ASSERT_EQ(content.size(), body.first);
  17135. ASSERT_TRUE(static_cast<bool>(body.second));
  17136. std::string written;
  17137. DataSink sink;
  17138. sink.write = [&](const char *d, size_t l) {
  17139. written.append(d, l);
  17140. return true;
  17141. };
  17142. EXPECT_TRUE(body.second(0, body.first, sink));
  17143. EXPECT_EQ(content, written);
  17144. }
  17145. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17146. static constexpr unsigned int number_of_tasks{1000000};
  17147. std::atomic_uint count{0};
  17148. std::unique_ptr<TaskQueue> task_queue{
  17149. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17150. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17151. auto queued = task_queue->enqueue(
  17152. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17153. EXPECT_TRUE(queued);
  17154. }
  17155. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17156. task_queue->shutdown();
  17157. #else
  17158. EXPECT_NO_THROW(task_queue->shutdown());
  17159. #endif
  17160. EXPECT_EQ(number_of_tasks, count.load());
  17161. }
  17162. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17163. static constexpr unsigned int number_of_tasks{1000000};
  17164. static constexpr unsigned int qlimit{2};
  17165. unsigned int queued_count{0};
  17166. std::atomic_uint count{0};
  17167. std::unique_ptr<TaskQueue> task_queue{
  17168. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17169. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17170. if (task_queue->enqueue(
  17171. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17172. queued_count++;
  17173. }
  17174. }
  17175. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17176. task_queue->shutdown();
  17177. #else
  17178. EXPECT_NO_THROW(task_queue->shutdown());
  17179. #endif
  17180. EXPECT_EQ(queued_count, count.load());
  17181. EXPECT_TRUE(queued_count <= number_of_tasks);
  17182. EXPECT_TRUE(queued_count >= qlimit);
  17183. }
  17184. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17185. // Use a short idle timeout so a dynamic thread spawns, times out and
  17186. // exits during the test, and the pool keeps working afterwards.
  17187. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17188. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17189. /*idle_timeout_sec=*/1}};
  17190. std::atomic_uint count{0};
  17191. std::condition_variable cv;
  17192. std::mutex mtx;
  17193. bool release = false;
  17194. // Block the base thread so the second task spawns a dynamic thread.
  17195. EXPECT_TRUE(task_queue->enqueue([&] {
  17196. std::unique_lock<std::mutex> lock(mtx);
  17197. while (!release) {
  17198. cv.wait(lock);
  17199. }
  17200. count++;
  17201. }));
  17202. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17203. // Let the dynamic thread finish its task and exceed the idle timeout.
  17204. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17205. {
  17206. std::unique_lock<std::mutex> lock(mtx);
  17207. release = true;
  17208. }
  17209. cv.notify_all();
  17210. // The pool must still accept and run tasks after the dynamic thread exited.
  17211. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17212. task_queue->shutdown();
  17213. EXPECT_EQ(3u, count.load());
  17214. }
  17215. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17216. static constexpr size_t number_of_tasks{32};
  17217. std::unique_ptr<TaskQueue> task_queue{
  17218. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17219. // Let the base threads go idle so the burst below finds them waiting.
  17220. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17221. std::mutex mtx;
  17222. std::condition_variable cv;
  17223. size_t running = 0;
  17224. bool release = false;
  17225. for (size_t i = 0; i < number_of_tasks; i++) {
  17226. EXPECT_TRUE(task_queue->enqueue([&] {
  17227. std::unique_lock<std::mutex> lock(mtx);
  17228. running++;
  17229. cv.notify_all();
  17230. cv.wait(lock, [&] { return release; });
  17231. }));
  17232. }
  17233. {
  17234. std::unique_lock<std::mutex> lock(mtx);
  17235. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17236. [&] { return running == number_of_tasks; }));
  17237. release = true;
  17238. }
  17239. cv.notify_all();
  17240. task_queue->shutdown();
  17241. }
  17242. TEST(TaskQueueTest, MaxQueuedRequests) {
  17243. static constexpr unsigned int qlimit{3};
  17244. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17245. std::condition_variable sem_cv;
  17246. std::mutex sem_mtx;
  17247. int credits = 0;
  17248. bool queued;
  17249. /* Fill up the queue with tasks that will block until we give them credits to
  17250. * complete. */
  17251. for (unsigned int n = 0; n <= qlimit;) {
  17252. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17253. std::unique_lock<std::mutex> lock(sem_mtx);
  17254. while (credits <= 0) {
  17255. sem_cv.wait(lock);
  17256. }
  17257. /* Consume the credit and signal the test code if they are all gone. */
  17258. if (--credits == 0) { sem_cv.notify_one(); }
  17259. });
  17260. if (n < qlimit) {
  17261. /* The first qlimit enqueues must succeed. */
  17262. EXPECT_TRUE(queued);
  17263. } else {
  17264. /* The last one will succeed only when the worker thread
  17265. * starts and dequeues the first blocking task. Although
  17266. * not necessary for the correctness of this test, we sleep for
  17267. * a short while to avoid busy waiting. */
  17268. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17269. }
  17270. if (queued) { n++; }
  17271. }
  17272. /* Further enqueues must fail since the queue is full. */
  17273. for (auto i = 0; i < 4; i++) {
  17274. queued = task_queue->enqueue([] {});
  17275. EXPECT_FALSE(queued);
  17276. }
  17277. /* Give the credits to allow the previous tasks to complete. */
  17278. {
  17279. std::unique_lock<std::mutex> lock(sem_mtx);
  17280. credits += qlimit + 1;
  17281. }
  17282. sem_cv.notify_all();
  17283. /* Wait for all the credits to be consumed. */
  17284. {
  17285. std::unique_lock<std::mutex> lock(sem_mtx);
  17286. while (credits > 0) {
  17287. sem_cv.wait(lock);
  17288. }
  17289. }
  17290. /* Check that we are able again to enqueue at least qlimit tasks. */
  17291. for (unsigned int i = 0; i < qlimit; i++) {
  17292. queued = task_queue->enqueue([] {});
  17293. EXPECT_TRUE(queued);
  17294. }
  17295. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17296. task_queue->shutdown();
  17297. #else
  17298. EXPECT_NO_THROW(task_queue->shutdown());
  17299. #endif
  17300. }
  17301. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17302. Server svr;
  17303. std::string method;
  17304. std::string body;
  17305. auto has_content_length = false;
  17306. auto has_transfer_encoding = false;
  17307. std::atomic<int> bad_requests{0};
  17308. // Leftover body bytes get parsed as a malformed request and answered with
  17309. // 400
  17310. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17311. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17312. });
  17313. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17314. res.set_redirect("/down", StatusCode::SeeOther_303);
  17315. });
  17316. svr.Get("/down", [&](const Request &req, Response &res) {
  17317. method = req.method;
  17318. body = req.body;
  17319. has_content_length = req.has_header("Content-Length");
  17320. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17321. res.set_content("ok", "text/plain");
  17322. });
  17323. auto port = svr.bind_to_any_port(HOST);
  17324. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17325. auto se = detail::scope_exit([&] {
  17326. svr.stop();
  17327. thread.join();
  17328. ASSERT_FALSE(svr.is_running());
  17329. });
  17330. svr.wait_until_ready();
  17331. const std::string payload = "SECRET-BODY";
  17332. auto check = [&](Client &cli, const Result &res) {
  17333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17334. EXPECT_EQ(StatusCode::OK_200, res->status);
  17335. EXPECT_EQ("ok", res->body);
  17336. EXPECT_EQ("GET", method);
  17337. EXPECT_TRUE(body.empty());
  17338. EXPECT_FALSE(has_content_length);
  17339. EXPECT_FALSE(has_transfer_encoding);
  17340. // Nothing of the original body may be left on the connection
  17341. auto res2 = cli.Get("/down");
  17342. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17343. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17344. EXPECT_EQ("ok", res2->body);
  17345. EXPECT_EQ(0, bad_requests);
  17346. };
  17347. // With content length
  17348. {
  17349. Client cli(HOST, port);
  17350. cli.set_keep_alive(true);
  17351. cli.set_follow_location(true);
  17352. auto res = cli.Post(
  17353. "/up", payload.size(),
  17354. [&](size_t offset, size_t length, DataSink &sink) {
  17355. return sink.write(payload.data() + offset, length);
  17356. },
  17357. "text/plain");
  17358. check(cli, res);
  17359. }
  17360. // Without content length (chunked)
  17361. {
  17362. Client cli(HOST, port);
  17363. cli.set_keep_alive(true);
  17364. cli.set_follow_location(true);
  17365. auto res = cli.Post(
  17366. "/up",
  17367. [&](size_t /*offset*/, DataSink &sink) {
  17368. sink.write(payload.data(), payload.size());
  17369. sink.done();
  17370. return true;
  17371. },
  17372. "text/plain");
  17373. check(cli, res);
  17374. }
  17375. }
  17376. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17377. Server svr;
  17378. std::string target;
  17379. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17380. // Echo the still-encoded name back in the Location
  17381. const std::string prefix = "/start/";
  17382. res.status = StatusCode::Found_302;
  17383. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17384. });
  17385. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17386. target = req.target;
  17387. res.set_content("ok", "text/plain");
  17388. });
  17389. auto port = svr.bind_to_any_port(HOST);
  17390. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. thread.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. svr.wait_until_ready();
  17397. // Decoding the Location path would turn the first four into a path
  17398. // separator, a query delimiter, a fragment delimiter and a different
  17399. // percent-encoded octet. The rest must keep reaching the server as they are.
  17400. const std::vector<std::string> names = {
  17401. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17402. };
  17403. for (auto path_encode : {true, false}) {
  17404. Client cli(HOST, port);
  17405. cli.set_follow_location(true);
  17406. cli.set_path_encode(path_encode);
  17407. for (const auto &name : names) {
  17408. target.clear();
  17409. auto res = cli.Get("/start/" + name);
  17410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17411. EXPECT_EQ(StatusCode::OK_200, res->status);
  17412. EXPECT_EQ("/dest/" + name, target);
  17413. }
  17414. }
  17415. }
  17416. TEST(RedirectTest, NotModifiedIsReturned) {
  17417. Server svr;
  17418. svr.Get("/cached", [](const Request &, Response &res) {
  17419. res.status = StatusCode::NotModified_304;
  17420. });
  17421. auto port = svr.bind_to_any_port(HOST);
  17422. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17423. auto se = detail::scope_exit([&] {
  17424. svr.stop();
  17425. thread.join();
  17426. ASSERT_FALSE(svr.is_running());
  17427. });
  17428. svr.wait_until_ready();
  17429. Client cli(HOST, port);
  17430. cli.set_follow_location(true);
  17431. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17433. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17434. }
  17435. TEST(RedirectTest, NoLocationIsReturned) {
  17436. Server svr;
  17437. svr.Get("/no-location", [](const Request &, Response &res) {
  17438. res.status = StatusCode::Found_302;
  17439. res.set_content("no location", "text/plain");
  17440. });
  17441. auto port = svr.bind_to_any_port(HOST);
  17442. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17443. auto se = detail::scope_exit([&] {
  17444. svr.stop();
  17445. thread.join();
  17446. ASSERT_FALSE(svr.is_running());
  17447. });
  17448. svr.wait_until_ready();
  17449. Client cli(HOST, port);
  17450. cli.set_follow_location(true);
  17451. auto res = cli.Get("/no-location");
  17452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17453. EXPECT_EQ(StatusCode::Found_302, res->status);
  17454. EXPECT_EQ("no location", res->body);
  17455. // The callbacks see the body of the response that is returned
  17456. auto handler_called = false;
  17457. auto progress_called = false;
  17458. std::string body;
  17459. auto res2 = cli.Get(
  17460. "/no-location",
  17461. [&](const Response &) {
  17462. handler_called = true;
  17463. return true;
  17464. },
  17465. [&](const char *data, size_t data_length) {
  17466. body.append(data, data_length);
  17467. return true;
  17468. },
  17469. [&](size_t, size_t) {
  17470. progress_called = true;
  17471. return true;
  17472. });
  17473. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17474. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17475. EXPECT_TRUE(handler_called);
  17476. EXPECT_TRUE(progress_called);
  17477. EXPECT_EQ("no location", body);
  17478. }
  17479. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17480. Server svr;
  17481. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17482. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17483. });
  17484. svr.Get("/hello", [](const Request &req, Response &res) {
  17485. res.set_content(req.get_param_value("key"), "text/plain");
  17486. });
  17487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17488. auto se = detail::scope_exit([&] {
  17489. svr.stop();
  17490. thread.join();
  17491. ASSERT_FALSE(svr.is_running());
  17492. });
  17493. svr.wait_until_ready();
  17494. {
  17495. Client cli(HOST, PORT);
  17496. cli.set_follow_location(true);
  17497. auto res = cli.Get("/");
  17498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17499. EXPECT_EQ(StatusCode::OK_200, res->status);
  17500. EXPECT_EQ("val&key2=val2", res->body);
  17501. }
  17502. }
  17503. #endif
  17504. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17505. Server svr;
  17506. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17507. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17508. });
  17509. svr.Get("/hello", [](const Request &req, Response &res) {
  17510. res.set_content(req.get_param_value("key"), "text/plain");
  17511. });
  17512. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17513. auto se = detail::scope_exit([&] {
  17514. svr.stop();
  17515. thread.join();
  17516. ASSERT_FALSE(svr.is_running());
  17517. });
  17518. svr.wait_until_ready();
  17519. {
  17520. Client cli(HOST, PORT);
  17521. cli.set_follow_location(true);
  17522. auto res = cli.Get("/");
  17523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17524. EXPECT_EQ(StatusCode::OK_200, res->status);
  17525. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17526. }
  17527. }
  17528. TEST(RedirectTest, RedirectWithPlusInPath) {
  17529. Server svr;
  17530. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17531. res.set_redirect("/a+b");
  17532. });
  17533. // Route pattern uses regex; escape + as \\+
  17534. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17535. res.set_content(req.path, "text/plain");
  17536. });
  17537. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17538. auto se = detail::scope_exit([&] {
  17539. svr.stop();
  17540. thread.join();
  17541. ASSERT_FALSE(svr.is_running());
  17542. });
  17543. svr.wait_until_ready();
  17544. {
  17545. Client cli(HOST, PORT);
  17546. cli.set_follow_location(true);
  17547. auto res = cli.Get("/");
  17548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17549. EXPECT_EQ(StatusCode::OK_200, res->status);
  17550. EXPECT_EQ("/a+b", res->body);
  17551. }
  17552. }
  17553. TEST(RedirectTest, ResolveRelativeLocation) {
  17554. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17555. const std::vector<std::pair<std::string, std::string>> cases = {
  17556. {"g", "/b/c/g"},
  17557. {"./g", "/b/c/g"},
  17558. {"g/", "/b/c/g/"},
  17559. {"?y", "/b/c/d;p?y"},
  17560. {"g?y", "/b/c/g?y"},
  17561. {"#s", "/b/c/d;p?q#s"},
  17562. {"g#s", "/b/c/g#s"},
  17563. {"g?y#s", "/b/c/g?y#s"},
  17564. {";x", "/b/c/;x"},
  17565. {"g;x", "/b/c/g;x"},
  17566. {".", "/b/c/"},
  17567. {"./", "/b/c/"},
  17568. {"..", "/b/"},
  17569. {"../", "/b/"},
  17570. {"../g", "/b/g"},
  17571. {"../..", "/"},
  17572. {"../../", "/"},
  17573. {"../../g", "/g"},
  17574. {"../../../g", "/g"},
  17575. {"g.", "/b/c/g."},
  17576. {".g", "/b/c/.g"},
  17577. {"g..", "/b/c/g.."},
  17578. {"..g", "/b/c/..g"},
  17579. {"./../g", "/b/g"},
  17580. {"./g/.", "/b/c/g/"},
  17581. {"g/./h", "/b/c/g/h"},
  17582. {"g/../h", "/b/c/h"},
  17583. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17584. {"g;x=1/../y", "/b/c/y"},
  17585. {"g?y/./x", "/b/c/g?y/./x"},
  17586. {"g#s/../x", "/b/c/g#s/../x"},
  17587. // Not relative-path references, so left for parse_url.
  17588. {"/g", "/g"},
  17589. {"//g", "//g"},
  17590. {"http://g/x", "http://g/x"},
  17591. {"g:h", "g:h"},
  17592. };
  17593. for (const auto &c : cases) {
  17594. EXPECT_EQ(c.second,
  17595. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17596. << c.first;
  17597. }
  17598. // A result starting with "//" is still a path, not a network-path reference
  17599. EXPECT_EQ("/.//g",
  17600. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  17601. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  17602. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  17603. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  17604. }
  17605. TEST(RedirectTest, RemoveDotSegments) {
  17606. // RFC 3986 section 5.2.4
  17607. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17608. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17609. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17610. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17611. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17612. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17613. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17614. }
  17615. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17616. Server svr;
  17617. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17618. res.set_redirect("/dir/../target?x=1");
  17619. });
  17620. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17621. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17622. "/dir/./../target");
  17623. });
  17624. svr.Get("/target", [](const Request &req, Response &res) {
  17625. res.set_content(req.path, "text/plain");
  17626. });
  17627. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17628. auto se = detail::scope_exit([&] {
  17629. svr.stop();
  17630. th.join();
  17631. ASSERT_FALSE(svr.is_running());
  17632. });
  17633. svr.wait_until_ready();
  17634. Client cli("localhost", PORT);
  17635. cli.set_follow_location(true);
  17636. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17637. auto res = cli.Get(path);
  17638. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17639. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17640. EXPECT_EQ("/target", res->body) << path;
  17641. }
  17642. }
  17643. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17644. Server svr;
  17645. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17646. res.set_redirect(req.get_param_value("to"));
  17647. });
  17648. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17649. res.set_content(req.target, "text/plain");
  17650. });
  17651. svr.Get("/other", [](const Request &req, Response &res) {
  17652. res.set_content(req.target, "text/plain");
  17653. });
  17654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17655. auto se = detail::scope_exit([&] {
  17656. svr.stop();
  17657. thread.join();
  17658. ASSERT_FALSE(svr.is_running());
  17659. });
  17660. svr.wait_until_ready();
  17661. const std::vector<std::pair<std::string, std::string>> cases = {
  17662. {"next", "/dir/next"},
  17663. {"./next?x=1", "/dir/next?x=1"},
  17664. {"../other", "/other"},
  17665. };
  17666. for (const auto &c : cases) {
  17667. Client cli(HOST, PORT);
  17668. cli.set_follow_location(true);
  17669. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17670. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17671. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17672. EXPECT_EQ(c.second, res->body) << c.first;
  17673. }
  17674. }
  17675. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  17676. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  17677. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  17678. Server other;
  17679. std::atomic<int> other_hits{0};
  17680. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  17681. other_hits++;
  17682. res.set_content("other", "text/plain");
  17683. });
  17684. auto other_port = other.bind_to_any_port("127.0.0.1");
  17685. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  17686. Server svr;
  17687. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17688. res.set_redirect(req.get_param_value("to"));
  17689. });
  17690. svr.Get(".*", [](const Request &req, Response &res) {
  17691. res.set_content(req.path, "text/plain");
  17692. });
  17693. auto port = svr.bind_to_any_port(HOST);
  17694. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17695. auto se = detail::scope_exit([&] {
  17696. svr.stop();
  17697. thread.join();
  17698. other.stop();
  17699. other_thread.join();
  17700. ASSERT_FALSE(svr.is_running());
  17701. ASSERT_FALSE(other.is_running());
  17702. });
  17703. svr.wait_until_ready();
  17704. other.wait_until_ready();
  17705. auto authority = "127.0.0.1:" + std::to_string(other_port);
  17706. for (const auto &to :
  17707. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  17708. Client cli(HOST, port);
  17709. cli.set_follow_location(true);
  17710. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  17711. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  17712. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  17713. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  17714. }
  17715. EXPECT_EQ(0, other_hits.load());
  17716. }
  17717. #ifdef CPPHTTPLIB_SSL_ENABLED
  17718. TEST(RedirectTest, Issue2185_Online) {
  17719. SSLClient client("github.com");
  17720. client.set_follow_location(true);
  17721. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17722. "Coollab-Windows.zip");
  17723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17724. EXPECT_EQ(StatusCode::OK_200, res->status);
  17725. EXPECT_EQ(9920427U, res->body.size());
  17726. }
  17727. #endif
  17728. TEST(VulnerabilityTest, CRLFInjection) {
  17729. Server svr;
  17730. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17731. res.set_content("Hello 1", "text/plain");
  17732. });
  17733. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17734. res.set_content("Hello 2", "text/plain");
  17735. });
  17736. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17737. res.set_content("Hello 3", "text/plain");
  17738. });
  17739. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17740. res.set_content("Hello 4", "text/plain");
  17741. });
  17742. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17743. for (const auto &x : req.headers) {
  17744. auto key = x.first;
  17745. EXPECT_STRNE("evil", key.c_str());
  17746. }
  17747. });
  17748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17749. auto se = detail::scope_exit([&] {
  17750. svr.stop();
  17751. thread.join();
  17752. ASSERT_FALSE(svr.is_running());
  17753. });
  17754. svr.wait_until_ready();
  17755. {
  17756. Client cli(HOST, PORT);
  17757. cli.Post("/test1", "A=B",
  17758. "application/x-www-form-urlencoded\r\nevil: hello1");
  17759. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17760. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17761. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17762. }
  17763. }
  17764. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17765. auto server_thread = std::thread([] {
  17766. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17767. default_socket_options(srv);
  17768. sockaddr_in addr{};
  17769. addr.sin_family = AF_INET;
  17770. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17771. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17772. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17773. ::listen(srv, 1);
  17774. sockaddr_in cli_addr{};
  17775. socklen_t cli_len = sizeof(cli_addr);
  17776. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17777. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17778. std::string buf_all;
  17779. char buf[2048];
  17780. ssize_t n;
  17781. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17782. buf_all.append(buf, static_cast<size_t>(n));
  17783. size_t pos;
  17784. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17785. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17786. auto e = request_block.find("\r\n");
  17787. if (e != std::string::npos) {
  17788. auto request_line = request_block.substr(0, e);
  17789. std::string msg =
  17790. "CRLF injection detected in request line: '" + request_line + "'";
  17791. EXPECT_FALSE(true) << msg;
  17792. }
  17793. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17794. ::send(cli,
  17795. #ifdef _WIN32
  17796. static_cast<const char *>(resp.c_str()),
  17797. static_cast<int>(resp.size()),
  17798. #else
  17799. resp.c_str(), resp.size(),
  17800. #endif
  17801. 0);
  17802. buf_all.erase(0, pos + 4);
  17803. }
  17804. }
  17805. detail::close_socket(cli);
  17806. detail::close_socket(srv);
  17807. });
  17808. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17809. auto cli = Client("127.0.0.1", PORT + 1);
  17810. auto headers = Headers{
  17811. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17812. {"Connection", "keep-alive"}};
  17813. auto res = cli.Get("/hi", headers);
  17814. EXPECT_FALSE(res);
  17815. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17816. server_thread.join();
  17817. }
  17818. // A request rejected before any byte reaches the socket must fail right away
  17819. // instead of waiting for a response the server will never send.
  17820. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17821. // The kernel completes the TCP handshake from the listen backlog, so the
  17822. // client connects, but nothing ever reads, responds or closes.
  17823. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17824. default_socket_options(srv);
  17825. sockaddr_in addr{};
  17826. addr.sin_family = AF_INET;
  17827. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17828. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17829. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17830. ASSERT_EQ(0, ::listen(srv, 8));
  17831. auto cli = Client("127.0.0.1", PORT + 1);
  17832. cli.set_read_timeout(10, 0);
  17833. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17834. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17835. std::chrono::steady_clock::now() - start)
  17836. .count();
  17837. };
  17838. {
  17839. Request req;
  17840. req.method = "GE T";
  17841. req.path = "/";
  17842. auto start = std::chrono::steady_clock::now();
  17843. auto res = cli.send(req);
  17844. EXPECT_FALSE(res);
  17845. EXPECT_EQ(Error::Write, res.error());
  17846. EXPECT_LT(elapsed_ms(start), 1000);
  17847. }
  17848. {
  17849. auto start = std::chrono::steady_clock::now();
  17850. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17851. EXPECT_FALSE(res);
  17852. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17853. EXPECT_LT(elapsed_ms(start), 1000);
  17854. }
  17855. EXPECT_FALSE(cli.is_socket_open());
  17856. detail::close_socket(srv);
  17857. }
  17858. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17859. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17860. default_socket_options(srv);
  17861. sockaddr_in addr{};
  17862. addr.sin_family = AF_INET;
  17863. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17864. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17865. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17866. ASSERT_EQ(0, ::listen(srv, 1));
  17867. std::string received;
  17868. auto server_thread = std::thread([&] {
  17869. auto sock = ::accept(srv, nullptr, nullptr);
  17870. if (sock == INVALID_SOCKET) { return; }
  17871. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17872. char buf[2048];
  17873. ssize_t n;
  17874. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17875. received.append(buf, static_cast<size_t>(n));
  17876. }
  17877. detail::close_socket(sock);
  17878. });
  17879. {
  17880. auto cli = Client("127.0.0.1", PORT + 1);
  17881. // "Z" sorts after the default headers, so writing straight to the socket
  17882. // would have sent the request line and those headers before the rejection.
  17883. auto handle =
  17884. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17885. EXPECT_FALSE(handle.is_valid());
  17886. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17887. }
  17888. server_thread.join();
  17889. detail::close_socket(srv);
  17890. EXPECT_TRUE(received.empty()) << received;
  17891. }
  17892. TEST(PathParamsTest, StaticMatch) {
  17893. const auto pattern = "/users/all";
  17894. detail::PathParamsMatcher matcher(pattern);
  17895. Request request;
  17896. request.path = "/users/all";
  17897. ASSERT_TRUE(matcher.match(request));
  17898. std::unordered_map<std::string, std::string> expected_params = {};
  17899. EXPECT_EQ(request.path_params, expected_params);
  17900. }
  17901. TEST(PathParamsTest, StaticMismatch) {
  17902. const auto pattern = "/users/all";
  17903. detail::PathParamsMatcher matcher(pattern);
  17904. Request request;
  17905. request.path = "/users/1";
  17906. ASSERT_FALSE(matcher.match(request));
  17907. }
  17908. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17909. const auto pattern = "/users/:id/subscriptions";
  17910. detail::PathParamsMatcher matcher(pattern);
  17911. Request request;
  17912. request.path = "/users/42/subscriptions";
  17913. ASSERT_TRUE(matcher.match(request));
  17914. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17915. EXPECT_EQ(request.path_params, expected_params);
  17916. }
  17917. TEST(PathParamsTest, SingleParamInTheEnd) {
  17918. const auto pattern = "/users/:id";
  17919. detail::PathParamsMatcher matcher(pattern);
  17920. Request request;
  17921. request.path = "/users/24";
  17922. ASSERT_TRUE(matcher.match(request));
  17923. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17924. EXPECT_EQ(request.path_params, expected_params);
  17925. }
  17926. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17927. const auto pattern = "/users/:id/";
  17928. detail::PathParamsMatcher matcher(pattern);
  17929. Request request;
  17930. request.path = "/users/42/";
  17931. ASSERT_TRUE(matcher.match(request));
  17932. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17933. EXPECT_EQ(request.path_params, expected_params);
  17934. }
  17935. TEST(PathParamsTest, EmptyParam) {
  17936. const auto pattern = "/users/:id/";
  17937. detail::PathParamsMatcher matcher(pattern);
  17938. Request request;
  17939. request.path = "/users//";
  17940. ASSERT_TRUE(matcher.match(request));
  17941. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17942. EXPECT_EQ(request.path_params, expected_params);
  17943. }
  17944. TEST(PathParamsTest, FragmentMismatch) {
  17945. const auto pattern = "/users/:id/";
  17946. detail::PathParamsMatcher matcher(pattern);
  17947. Request request;
  17948. request.path = "/admins/24/";
  17949. ASSERT_FALSE(matcher.match(request));
  17950. }
  17951. TEST(PathParamsTest, ExtraFragments) {
  17952. const auto pattern = "/users/:id";
  17953. detail::PathParamsMatcher matcher(pattern);
  17954. Request request;
  17955. request.path = "/users/42/subscriptions";
  17956. ASSERT_FALSE(matcher.match(request));
  17957. }
  17958. TEST(PathParamsTest, MissingTrailingParam) {
  17959. const auto pattern = "/users/:id";
  17960. detail::PathParamsMatcher matcher(pattern);
  17961. Request request;
  17962. request.path = "/users";
  17963. ASSERT_FALSE(matcher.match(request));
  17964. }
  17965. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17966. const auto pattern = "/users/:id/subscriptions";
  17967. detail::PathParamsMatcher matcher(pattern);
  17968. Request request;
  17969. request.path = "/users/subscriptions";
  17970. ASSERT_FALSE(matcher.match(request));
  17971. }
  17972. TEST(PathParamsTest, MultipleParams) {
  17973. const auto pattern = "/users/:userid/subscriptions/:subid";
  17974. detail::PathParamsMatcher matcher(pattern);
  17975. Request request;
  17976. request.path = "/users/42/subscriptions/2";
  17977. ASSERT_TRUE(matcher.match(request));
  17978. std::unordered_map<std::string, std::string> expected_params = {
  17979. {"userid", "42"}, {"subid", "2"}};
  17980. EXPECT_EQ(request.path_params, expected_params);
  17981. }
  17982. TEST(PathParamsTest, SequenceOfParams) {
  17983. const auto pattern = "/values/:x/:y/:z";
  17984. detail::PathParamsMatcher matcher(pattern);
  17985. Request request;
  17986. request.path = "/values/1/2/3";
  17987. ASSERT_TRUE(matcher.match(request));
  17988. std::unordered_map<std::string, std::string> expected_params = {
  17989. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17990. EXPECT_EQ(request.path_params, expected_params);
  17991. }
  17992. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17993. const auto pattern = "/prefix:suffix";
  17994. detail::PathParamsMatcher matcher(pattern);
  17995. Request request;
  17996. request.path = "/prefix:suffix";
  17997. ASSERT_TRUE(matcher.match(request));
  17998. const std::unordered_map<std::string, std::string> expected_params = {};
  17999. EXPECT_EQ(request.path_params, expected_params);
  18000. }
  18001. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18002. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18003. // calling thread's stack on a long enough path for a quantified pattern;
  18004. // RegexMatcher must refuse to run regex matching on paths beyond
  18005. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18006. detail::RegexMatcher matcher("/files/(.*)");
  18007. Request within_limit;
  18008. within_limit.path = "/files/" + std::string(10, 'A');
  18009. EXPECT_TRUE(matcher.match(within_limit));
  18010. Request over_limit;
  18011. over_limit.path =
  18012. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18013. EXPECT_FALSE(matcher.match(over_limit));
  18014. }
  18015. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18016. Server svr;
  18017. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18018. res.set_content("ok", "text/plain");
  18019. });
  18020. auto port = svr.bind_to_any_port(HOST);
  18021. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18022. auto se = detail::scope_exit([&] {
  18023. svr.stop();
  18024. thread.join();
  18025. ASSERT_FALSE(svr.is_running());
  18026. });
  18027. svr.wait_until_ready();
  18028. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18029. // request URI limit; this used to be able to crash the process.
  18030. std::string path =
  18031. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18032. std::string req = "GET " + path +
  18033. " HTTP/1.1\r\n"
  18034. "Host: " +
  18035. std::string(HOST) + ":" + std::to_string(port) +
  18036. "\r\n"
  18037. "Connection: close\r\n"
  18038. "\r\n";
  18039. std::string response;
  18040. ASSERT_TRUE(send_request(5, req, &response, port));
  18041. EXPECT_NE(std::string::npos, response.find("404"));
  18042. }
  18043. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18044. Server svr;
  18045. auto handler = [](const Request & /*req*/, Response &res) {
  18046. res.set_content("hit", "text/plain");
  18047. };
  18048. // No regex metacharacter, so this one is compared literally
  18049. svr.Get("/literal/route", handler);
  18050. // '.' is a regex metacharacter, so this one must keep regex semantics
  18051. svr.Get("/a.c", handler);
  18052. auto port = svr.bind_to_any_port(HOST);
  18053. std::thread t([&]() { svr.listen_after_bind(); });
  18054. auto se = detail::scope_exit([&] {
  18055. svr.stop();
  18056. t.join();
  18057. ASSERT_FALSE(svr.is_running());
  18058. });
  18059. svr.wait_until_ready();
  18060. Client cli(HOST, port);
  18061. struct {
  18062. const char *path;
  18063. int status;
  18064. } cases[] = {
  18065. {"/literal/route", StatusCode::OK_200},
  18066. {"/literal/routes", StatusCode::NotFound_404},
  18067. {"/literal/rout", StatusCode::NotFound_404},
  18068. {"/abc", StatusCode::OK_200},
  18069. {"/a.c", StatusCode::OK_200},
  18070. };
  18071. for (const auto &x : cases) {
  18072. auto res = cli.Get(x.path);
  18073. ASSERT_TRUE(res) << x.path;
  18074. EXPECT_EQ(x.status, res->status) << x.path;
  18075. }
  18076. }
  18077. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18078. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18079. // from exhausting the stack, so it must only constrain routes that actually
  18080. // run a regular expression. A literal route is matched by comparison and
  18081. // stays usable at any length.
  18082. Server svr;
  18083. const std::string pattern =
  18084. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18085. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18086. res.set_content("hit", "text/plain");
  18087. });
  18088. auto port = svr.bind_to_any_port(HOST);
  18089. std::thread t([&]() { svr.listen_after_bind(); });
  18090. auto se = detail::scope_exit([&] {
  18091. svr.stop();
  18092. t.join();
  18093. ASSERT_FALSE(svr.is_running());
  18094. });
  18095. svr.wait_until_ready();
  18096. Client cli(HOST, port);
  18097. auto res = cli.Get(pattern);
  18098. ASSERT_TRUE(res);
  18099. EXPECT_EQ(StatusCode::OK_200, res->status);
  18100. }
  18101. TEST(ParseUrlTest, VariousPatterns) {
  18102. {
  18103. detail::UrlComponents uc;
  18104. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18105. EXPECT_EQ("http", uc.scheme);
  18106. EXPECT_EQ("example.com", uc.host);
  18107. EXPECT_EQ("8080", uc.port);
  18108. EXPECT_EQ("/path", uc.path);
  18109. EXPECT_EQ("?q=1", uc.query);
  18110. }
  18111. {
  18112. detail::UrlComponents uc;
  18113. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18114. EXPECT_EQ("https", uc.scheme);
  18115. EXPECT_EQ("example.com", uc.host);
  18116. EXPECT_TRUE(uc.port.empty());
  18117. EXPECT_EQ("/path", uc.path);
  18118. }
  18119. {
  18120. detail::UrlComponents uc;
  18121. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18122. EXPECT_EQ("::1", uc.host);
  18123. EXPECT_EQ("8080", uc.port);
  18124. EXPECT_EQ("/path", uc.path);
  18125. }
  18126. {
  18127. detail::UrlComponents uc;
  18128. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18129. }
  18130. {
  18131. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18132. // the path while the connection still targets the bracketed host.
  18133. detail::UrlComponents uc;
  18134. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18135. }
  18136. {
  18137. detail::UrlComponents uc;
  18138. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18139. }
  18140. {
  18141. detail::UrlComponents uc;
  18142. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18143. EXPECT_EQ("::1", uc.host);
  18144. EXPECT_TRUE(uc.port.empty());
  18145. EXPECT_EQ("/path", uc.path);
  18146. }
  18147. {
  18148. detail::UrlComponents uc;
  18149. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18150. EXPECT_TRUE(uc.scheme.empty());
  18151. EXPECT_EQ("example.com", uc.host);
  18152. EXPECT_EQ("/path", uc.path);
  18153. EXPECT_EQ("?q=1", uc.query);
  18154. }
  18155. {
  18156. detail::UrlComponents uc;
  18157. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18158. EXPECT_TRUE(uc.host.empty());
  18159. EXPECT_EQ("/path", uc.path);
  18160. EXPECT_EQ("?q=1", uc.query);
  18161. }
  18162. {
  18163. detail::UrlComponents uc;
  18164. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18165. EXPECT_EQ("example.com", uc.host);
  18166. EXPECT_EQ("8080", uc.port);
  18167. }
  18168. {
  18169. // Unix socket path — must not be parsed as host
  18170. detail::UrlComponents uc;
  18171. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18172. EXPECT_TRUE(uc.host.empty());
  18173. }
  18174. {
  18175. detail::UrlComponents uc;
  18176. ASSERT_TRUE(detail::parse_url("", uc));
  18177. EXPECT_TRUE(uc.host.empty());
  18178. EXPECT_TRUE(uc.path.empty());
  18179. }
  18180. {
  18181. detail::UrlComponents uc;
  18182. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18183. }
  18184. {
  18185. detail::UrlComponents uc;
  18186. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18187. }
  18188. {
  18189. // Accepted by parse_url; callers restrict to http/https
  18190. detail::UrlComponents uc;
  18191. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18192. EXPECT_EQ("ftp", uc.scheme);
  18193. }
  18194. {
  18195. detail::UrlComponents uc;
  18196. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18197. }
  18198. {
  18199. detail::UrlComponents uc;
  18200. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18201. }
  18202. }
  18203. TEST(ParseUrlTest, FragmentHandling) {
  18204. {
  18205. detail::UrlComponents uc;
  18206. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18207. EXPECT_EQ("/path", uc.path);
  18208. EXPECT_TRUE(uc.query.empty());
  18209. }
  18210. {
  18211. detail::UrlComponents uc;
  18212. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18213. EXPECT_TRUE(uc.path.empty());
  18214. EXPECT_TRUE(uc.query.empty());
  18215. }
  18216. }
  18217. TEST(ParseUrlTest, UserinfoHandling) {
  18218. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18219. // parsers would see evil.com as the host.
  18220. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18221. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18222. for (auto url : urls) {
  18223. detail::UrlComponents uc;
  18224. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18225. }
  18226. }
  18227. TEST(ParseUrlTest, IPv6EdgeCases) {
  18228. {
  18229. detail::UrlComponents uc;
  18230. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18231. EXPECT_TRUE(uc.scheme.empty());
  18232. EXPECT_EQ("::1", uc.host);
  18233. EXPECT_EQ("8080", uc.port);
  18234. }
  18235. {
  18236. // Zone ID '%25' is not in [a-fA-F0-9:]
  18237. detail::UrlComponents uc;
  18238. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18239. }
  18240. }
  18241. TEST(ParseUrlTest, SchemeEdgeCases) {
  18242. {
  18243. detail::UrlComponents uc;
  18244. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18245. }
  18246. {
  18247. detail::UrlComponents uc;
  18248. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18249. }
  18250. {
  18251. detail::UrlComponents uc;
  18252. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18253. }
  18254. }
  18255. TEST(ParseUrlTest, PortEdgeCases) {
  18256. {
  18257. detail::UrlComponents uc;
  18258. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18259. EXPECT_TRUE(uc.port.empty());
  18260. EXPECT_EQ("/path", uc.path);
  18261. }
  18262. {
  18263. // parse_url accepts any port string; validation is done by parse_port
  18264. detail::UrlComponents uc;
  18265. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18266. EXPECT_EQ("abc", uc.port);
  18267. }
  18268. }
  18269. TEST(ParseUrlTest, WebSocketPatterns) {
  18270. {
  18271. detail::UrlComponents uc;
  18272. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18273. EXPECT_EQ("ws", uc.scheme);
  18274. EXPECT_EQ("echo.example.com", uc.host);
  18275. EXPECT_EQ("8080", uc.port);
  18276. EXPECT_EQ("/ws", uc.path);
  18277. }
  18278. {
  18279. detail::UrlComponents uc;
  18280. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18281. EXPECT_EQ("wss", uc.scheme);
  18282. EXPECT_EQ("echo.example.com", uc.host);
  18283. EXPECT_TRUE(uc.port.empty());
  18284. EXPECT_EQ("/ws", uc.path);
  18285. }
  18286. }
  18287. TEST(ParseUrlTest, QueryOnly) {
  18288. detail::UrlComponents uc;
  18289. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18290. EXPECT_TRUE(uc.host.empty());
  18291. EXPECT_TRUE(uc.path.empty());
  18292. EXPECT_EQ("?q=1&r=2", uc.query);
  18293. }
  18294. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18295. detail::UrlComponents uc;
  18296. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18297. EXPECT_TRUE(uc.scheme.empty());
  18298. EXPECT_EQ("example.com", uc.host);
  18299. EXPECT_EQ("443", uc.port);
  18300. EXPECT_EQ("/path", uc.path);
  18301. }
  18302. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18303. // If ipv6 regex working, regex match codepath is taken.
  18304. // else port will default to 80 in Client impl
  18305. int clientImplMagicPort = 80;
  18306. int port = 4321;
  18307. // above ports must be different to avoid false negative
  18308. EXPECT_NE(clientImplMagicPort, port);
  18309. std::string ipV6TestURL = "http://[ff06::c3]";
  18310. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18311. CLIENT_PRIVATE_KEY_FILE);
  18312. EXPECT_EQ(cli.port(), port);
  18313. }
  18314. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18315. auto file_path = "./www/dir/index.html";
  18316. auto dir_path = "./www/dir";
  18317. detail::FileStat stat_file(file_path);
  18318. EXPECT_TRUE(stat_file.is_file());
  18319. EXPECT_FALSE(stat_file.is_dir());
  18320. detail::FileStat stat_dir(dir_path);
  18321. EXPECT_FALSE(stat_dir.is_file());
  18322. EXPECT_TRUE(stat_dir.is_dir());
  18323. }
  18324. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18325. // IPv4 with default HTTP port (80)
  18326. EXPECT_EQ("example.com",
  18327. detail::make_host_and_port_string("example.com", 80, false));
  18328. // IPv4 with default HTTPS port (443)
  18329. EXPECT_EQ("example.com",
  18330. detail::make_host_and_port_string("example.com", 443, true));
  18331. // IPv4 with non-default HTTP port
  18332. EXPECT_EQ("example.com:8080",
  18333. detail::make_host_and_port_string("example.com", 8080, false));
  18334. // IPv4 with non-default HTTPS port
  18335. EXPECT_EQ("example.com:8443",
  18336. detail::make_host_and_port_string("example.com", 8443, true));
  18337. // IPv6 with default HTTP port (80)
  18338. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18339. // IPv6 with default HTTPS port (443)
  18340. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18341. // IPv6 with non-default HTTP port
  18342. EXPECT_EQ("[::1]:8080",
  18343. detail::make_host_and_port_string("::1", 8080, false));
  18344. // IPv6 with non-default HTTPS port
  18345. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18346. // IPv6 full address with default port
  18347. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18348. detail::make_host_and_port_string(
  18349. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18350. // IPv6 full address with non-default port
  18351. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18352. detail::make_host_and_port_string(
  18353. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18354. // IPv6 localhost with non-default port
  18355. EXPECT_EQ("[::1]:3000",
  18356. detail::make_host_and_port_string("::1", 3000, false));
  18357. // IPv6 with zone ID (link-local address) with default port
  18358. EXPECT_EQ("[fe80::1%eth0]",
  18359. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18360. // IPv6 with zone ID (link-local address) with non-default port
  18361. EXPECT_EQ("[fe80::1%eth0]:8080",
  18362. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18363. // Edge case: Port 443 with is_ssl=false (should add port)
  18364. EXPECT_EQ("example.com:443",
  18365. detail::make_host_and_port_string("example.com", 443, false));
  18366. // Edge case: Port 80 with is_ssl=true (should add port)
  18367. EXPECT_EQ("example.com:80",
  18368. detail::make_host_and_port_string("example.com", 80, true));
  18369. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18370. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18371. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18372. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18373. // Security fix: Already bracketed IPv6 should not get double brackets
  18374. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18375. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18376. EXPECT_EQ("[::1]:8080",
  18377. detail::make_host_and_port_string("[::1]", 8080, false));
  18378. EXPECT_EQ("[2001:db8::1]:8080",
  18379. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18380. EXPECT_EQ("[fe80::1%eth0]",
  18381. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18382. EXPECT_EQ("[fe80::1%eth0]:8080",
  18383. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18384. // Edge case: Empty host (should return as-is)
  18385. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18386. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18387. // This is a known limitation but shouldn't crash
  18388. EXPECT_EQ("[host:name]",
  18389. detail::make_host_and_port_string("host:name", 80, false));
  18390. // Port number edge cases (no validation, but should not crash)
  18391. EXPECT_EQ("example.com:0",
  18392. detail::make_host_and_port_string("example.com", 0, false));
  18393. EXPECT_EQ("example.com:-1",
  18394. detail::make_host_and_port_string("example.com", -1, false));
  18395. EXPECT_EQ("example.com:65535",
  18396. detail::make_host_and_port_string("example.com", 65535, false));
  18397. EXPECT_EQ("example.com:65536",
  18398. detail::make_host_and_port_string("example.com", 65536, false));
  18399. }
  18400. namespace httplib {
  18401. namespace detail {
  18402. std::string
  18403. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18404. const std::string &host, int port);
  18405. } // namespace detail
  18406. } // namespace httplib
  18407. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18408. std::map<std::string, std::string> addr_map = {
  18409. {"ipv4.example", "192.0.2.10"},
  18410. {"ipv6.example", "2001:db8::1"},
  18411. {"name.example", "internal.example.lan"},
  18412. {"empty.example", ""}};
  18413. EXPECT_EQ("192.0.2.10:443",
  18414. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18415. EXPECT_EQ("[2001:db8::1]:443",
  18416. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18417. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18418. addr_map, "name.example", 8443));
  18419. // An empty or absent mapping keeps the hostname as the target
  18420. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18421. addr_map, "empty.example", 443));
  18422. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18423. addr_map, "other.example", 443));
  18424. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18425. }
  18426. #ifdef CPPHTTPLIB_SSL_ENABLED
  18427. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18428. httplib::SSLClient cli("roblox.com", 443);
  18429. cli.set_follow_location(true);
  18430. auto res = cli.Get("/");
  18431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18432. EXPECT_EQ(StatusCode::OK_200, res->status);
  18433. }
  18434. #endif
  18435. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18436. Server svr;
  18437. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18438. EXPECT_EQ(res.status, 400);
  18439. });
  18440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18441. auto se = detail::scope_exit([&] {
  18442. svr.stop();
  18443. thread.join();
  18444. ASSERT_FALSE(svr.is_running());
  18445. });
  18446. svr.wait_until_ready();
  18447. Client cli(HOST, PORT);
  18448. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18449. }
  18450. TEST(InvalidHeaderCharsTest, is_field_name) {
  18451. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18452. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18453. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18454. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18455. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18456. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18457. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18458. EXPECT_FALSE(detail::fields::is_field_name(""));
  18459. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18460. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18461. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18462. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18463. }
  18464. TEST(InvalidHeaderCharsTest, is_field_value) {
  18465. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18466. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18467. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18468. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18469. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18470. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18471. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18472. EXPECT_TRUE(detail::fields::is_field_value(""));
  18473. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18474. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18475. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18476. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18477. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18478. }
  18479. TEST(InvalidHeaderCharsTest, OnServer) {
  18480. Server svr;
  18481. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18482. std::string header = "Not Set";
  18483. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18484. res.set_header(header, "value");
  18485. res.set_content("Page Content Page Content", "text/plain");
  18486. });
  18487. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18488. std::string header = "Not Set";
  18489. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18490. res.set_header("X-Test", header);
  18491. res.set_content("Page Content Page Content", "text/plain");
  18492. });
  18493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18494. auto se = detail::scope_exit([&] {
  18495. svr.stop();
  18496. thread.join();
  18497. ASSERT_FALSE(svr.is_running());
  18498. });
  18499. svr.wait_until_ready();
  18500. Client cli(HOST, PORT);
  18501. {
  18502. auto res = cli.Get(
  18503. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18505. EXPECT_EQ("Page Content Page Content", res->body);
  18506. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18507. }
  18508. {
  18509. auto res = cli.Get(
  18510. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18512. EXPECT_EQ("Page Content Page Content", res->body);
  18513. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18514. }
  18515. }
  18516. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18517. auto handled = false;
  18518. Server svr;
  18519. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18520. thread t = thread([&] { svr.listen(HOST, PORT); });
  18521. auto se = detail::scope_exit([&] {
  18522. svr.stop();
  18523. t.join();
  18524. ASSERT_FALSE(svr.is_running());
  18525. ASSERT_FALSE(handled);
  18526. });
  18527. svr.wait_until_ready();
  18528. auto req = "POST /test HTTP/1.1\r\n"
  18529. "Content-Length: x\r\n"
  18530. "\r\n";
  18531. std::string response;
  18532. ASSERT_TRUE(send_request(1, req, &response));
  18533. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18534. response.substr(0, response.find("\r\n")));
  18535. }
  18536. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18537. // case-insensitive, and a server that receives a 100-continue expectation in
  18538. // an HTTP/1.0 request MUST ignore it.
  18539. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18540. std::string response;
  18541. ASSERT_TRUE(send_request(1, req, &response, port));
  18542. *got_100 = response.find("100 Continue") != std::string::npos;
  18543. }
  18544. class ExpectTokenTest : public ::testing::Test {
  18545. protected:
  18546. void SetUp() override {
  18547. svr_.Post("/p", [](const Request &, Response &res) {
  18548. res.set_content("ok", "text/plain");
  18549. });
  18550. port_ = svr_.bind_to_any_port(HOST);
  18551. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18552. svr_.wait_until_ready();
  18553. }
  18554. void TearDown() override {
  18555. svr_.stop();
  18556. if (thread_.joinable()) { thread_.join(); }
  18557. }
  18558. std::string request(const char *version, const char *expect_value) const {
  18559. return std::string("POST /p ") + version +
  18560. "\r\n"
  18561. "Host: localhost\r\n"
  18562. "Content-Length: 2\r\n"
  18563. "Connection: close\r\n"
  18564. "Expect: " +
  18565. expect_value +
  18566. "\r\n"
  18567. "\r\n"
  18568. "hi";
  18569. }
  18570. Server svr_;
  18571. int port_ = 0;
  18572. thread thread_;
  18573. };
  18574. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18575. bool got_100 = false;
  18576. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18577. EXPECT_TRUE(got_100);
  18578. }
  18579. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18580. bool got_100 = true;
  18581. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18582. EXPECT_FALSE(got_100);
  18583. }
  18584. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18585. bool got_100 = false;
  18586. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18587. EXPECT_TRUE(got_100);
  18588. }
  18589. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18590. bool got_100 = false;
  18591. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18592. EXPECT_TRUE(got_100);
  18593. }
  18594. // `100 Continue` is sent only when the server starts reading the body, so a
  18595. // request rejected before that never invites the client to send it. The
  18596. // requests below carry the expectation but withhold the body, as a client
  18597. // waiting for `100 Continue` would.
  18598. // A POST that expects `100 Continue` and withholds its two-byte body.
  18599. static std::string expect_headers_only(const std::string &path) {
  18600. return "POST " + path +
  18601. " HTTP/1.1\r\n"
  18602. "Host: localhost\r\n"
  18603. "Content-Length: 2\r\n"
  18604. "Expect: 100-continue\r\n"
  18605. "\r\n";
  18606. }
  18607. class ExpectLazyContinueTest : public ::testing::Test {
  18608. protected:
  18609. void SetUp() override {
  18610. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18611. if (req.path == "/pre-routing") {
  18612. res.status = StatusCode::Unauthorized_401;
  18613. return Server::HandlerResponse::Handled;
  18614. }
  18615. return Server::HandlerResponse::Unhandled;
  18616. });
  18617. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18618. if (req.matched_route == "/pre-request") {
  18619. res.status = StatusCode::Forbidden_403;
  18620. return Server::HandlerResponse::Handled;
  18621. }
  18622. return Server::HandlerResponse::Unhandled;
  18623. });
  18624. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18625. res.set_content("ok", "text/plain");
  18626. });
  18627. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18628. res.set_content("ok", "text/plain");
  18629. });
  18630. svr_.Post("/reader-used", [](const Request &, Response &res,
  18631. const ContentReader &content_reader) {
  18632. std::string body;
  18633. content_reader([&](const char *data, size_t len) {
  18634. body.append(data, len);
  18635. return true;
  18636. });
  18637. res.set_content(body, "text/plain");
  18638. });
  18639. svr_.Post("/reader-unused",
  18640. [](const Request &, Response &res, const ContentReader &) {
  18641. res.set_content("ignored", "text/plain");
  18642. });
  18643. port_ = svr_.bind_to_any_port(HOST);
  18644. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18645. svr_.wait_until_ready();
  18646. }
  18647. void TearDown() override {
  18648. svr_.stop();
  18649. if (thread_.joinable()) { thread_.join(); }
  18650. }
  18651. // Sends `req` and reads until the server closes the connection. Returns
  18652. // false if the read had to wait for the client-side timeout instead.
  18653. bool send_until_closed(const std::string &req, std::string *resp) const {
  18654. auto start = std::chrono::steady_clock::now();
  18655. if (!send_request(3, req, resp, port_)) { return false; }
  18656. auto elapsed = std::chrono::steady_clock::now() - start;
  18657. return elapsed < std::chrono::seconds(2);
  18658. }
  18659. // The final response comes without `100 Continue`, and the server closes
  18660. // the connection since the body may or may not follow.
  18661. void expect_final_without_interim(const std::string &path,
  18662. const char *status_line) const {
  18663. std::string resp;
  18664. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18665. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18666. EXPECT_EQ(0u, resp.find(status_line));
  18667. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18668. }
  18669. Server svr_;
  18670. int port_ = 0;
  18671. thread thread_;
  18672. };
  18673. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18674. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18675. }
  18676. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18677. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18678. }
  18679. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18680. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18681. }
  18682. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18683. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18684. }
  18685. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18686. // The body follows once `100 Continue` has had time to arrive.
  18687. auto req = expect_headers_only("/reader-used");
  18688. req.insert(req.size() - 2, "Connection: close\r\n");
  18689. std::string resp;
  18690. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18691. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18692. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18693. EXPECT_NE(std::string::npos, resp.find("hi"));
  18694. }
  18695. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18696. // Large enough for the client to add `Expect: 100-continue` itself.
  18697. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18698. std::atomic<bool> body_sent{false};
  18699. Client cli(HOST, port_);
  18700. auto res = cli.Post(
  18701. "/pre-request", length,
  18702. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18703. body_sent = true;
  18704. std::string chunk(len, 'x');
  18705. sink.write(chunk.data(), chunk.size());
  18706. return true;
  18707. },
  18708. "application/octet-stream");
  18709. ASSERT_TRUE(res);
  18710. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18711. EXPECT_FALSE(body_sent);
  18712. }
  18713. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18714. Server svr;
  18715. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18716. return StatusCode::ExpectationFailed_417;
  18717. });
  18718. svr.Post("/p", [](const Request &, Response &res) {
  18719. res.set_content("ok", "text/plain");
  18720. });
  18721. auto port = svr.bind_to_any_port(HOST);
  18722. thread t = thread([&] { svr.listen_after_bind(); });
  18723. auto se = detail::scope_exit([&] {
  18724. svr.stop();
  18725. t.join();
  18726. });
  18727. svr.wait_until_ready();
  18728. std::string resp;
  18729. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18730. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18731. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18732. // Exactly one response: the route handler must not run after the 417.
  18733. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18734. }
  18735. #ifndef _WIN32
  18736. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18737. static constexpr char reject[] = "Unauthorized";
  18738. static constexpr char accept[] = "Upload accepted";
  18739. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18740. Server svr;
  18741. svr.set_expect_100_continue_handler(
  18742. [](const Request & /*req*/, Response &res) {
  18743. res.status = StatusCode::Unauthorized_401;
  18744. res.set_content(reject, "text/plain");
  18745. return res.status;
  18746. });
  18747. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18748. res.set_content(accept, "text/plain");
  18749. });
  18750. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18751. auto se = detail::scope_exit([&] {
  18752. svr.stop();
  18753. thread.join();
  18754. ASSERT_FALSE(svr.is_running());
  18755. });
  18756. svr.wait_until_ready();
  18757. {
  18758. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18759. curl_easy_init(), &curl_easy_cleanup};
  18760. ASSERT_NE(curl, nullptr);
  18761. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18762. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18763. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18764. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18765. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18766. &curl_slist_free_all};
  18767. ASSERT_NE(list, nullptr);
  18768. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18769. struct read_data {
  18770. uint64_t read_size;
  18771. uint64_t total_size;
  18772. } data = {0, total_size};
  18773. using read_callback_t =
  18774. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18775. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18776. void *userdata) -> size_t {
  18777. read_data *d = (read_data *)userdata;
  18778. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18779. std::fill_n(ptr, size * nmemb, 'A');
  18780. d->read_size += size * nmemb;
  18781. return size * nmemb;
  18782. };
  18783. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18784. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18785. std::vector<char> buffer;
  18786. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18787. using write_callback_t =
  18788. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18789. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18790. void *userdata) -> size_t {
  18791. std::vector<char> *buf = (std::vector<char> *)userdata;
  18792. buf->reserve(buf->size() + size * nmemb + 1);
  18793. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18794. return size * nmemb;
  18795. };
  18796. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18797. {
  18798. const auto res = curl_easy_perform(curl.get());
  18799. ASSERT_EQ(res, CURLE_OK);
  18800. }
  18801. {
  18802. auto response_code = long{};
  18803. const auto res =
  18804. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18805. ASSERT_EQ(res, CURLE_OK);
  18806. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18807. }
  18808. {
  18809. auto dl = curl_off_t{};
  18810. const auto res =
  18811. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18812. ASSERT_EQ(res, CURLE_OK);
  18813. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18814. }
  18815. {
  18816. buffer.push_back('\0');
  18817. ASSERT_STRCASEEQ(buffer.data(), reject);
  18818. }
  18819. }
  18820. }
  18821. #endif
  18822. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18823. // Regression test for #2458.
  18824. //
  18825. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18826. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18827. // ticket can make the client socket spuriously readable during the
  18828. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18829. // the client withholds the body and then blocks reading a response that never
  18830. // comes, failing with `Failed to read connection`.
  18831. //
  18832. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18833. // within the timeout. This raw OpenSSL server deliberately never sends
  18834. // `100 Continue`; the client must still deliver the body and receive 200.
  18835. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18836. signal(SIGPIPE, SIG_IGN);
  18837. const auto port = PORT + 4;
  18838. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18839. ASSERT_NE(srv, INVALID_SOCKET);
  18840. int opt = 1;
  18841. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18842. sockaddr_in addr{};
  18843. addr.sin_family = AF_INET;
  18844. addr.sin_port = htons(static_cast<uint16_t>(port));
  18845. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18846. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18847. ASSERT_EQ(0, ::listen(srv, 1));
  18848. std::atomic<size_t> server_body_bytes{0};
  18849. auto server_thread = std::thread([&] {
  18850. sockaddr_in cli_addr{};
  18851. socklen_t cli_len = sizeof(cli_addr);
  18852. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18853. if (cli == INVALID_SOCKET) { return; }
  18854. // Bound the lifetime of the server side so a buggy client (which never
  18855. // sends the body) cannot make this thread block forever on join.
  18856. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18857. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18858. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18859. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18860. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18861. SSL *ssl = SSL_new(ctx);
  18862. SSL_set_fd(ssl, static_cast<int>(cli));
  18863. if (SSL_accept(ssl) > 0) {
  18864. // Read the request headers. Reading here also flushes the TLS 1.3
  18865. // session tickets to the client. Deliberately do NOT send
  18866. // `100 Continue`.
  18867. std::string buf;
  18868. char tmp[1024];
  18869. while (buf.find("\r\n\r\n") == std::string::npos) {
  18870. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18871. if (n <= 0) { break; }
  18872. buf.append(tmp, static_cast<size_t>(n));
  18873. }
  18874. // A correct client sends the body now; count what arrives.
  18875. auto pos = buf.find("\r\n\r\n");
  18876. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18877. while (body < 4096) {
  18878. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18879. if (n <= 0) { break; }
  18880. body += static_cast<size_t>(n);
  18881. }
  18882. server_body_bytes = body;
  18883. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18884. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18885. SSL_shutdown(ssl);
  18886. }
  18887. SSL_free(ssl);
  18888. detail::close_socket(cli);
  18889. SSL_CTX_free(ctx);
  18890. });
  18891. auto se = detail::scope_exit([&] {
  18892. server_thread.join();
  18893. detail::close_socket(srv);
  18894. });
  18895. SSLClient cli("127.0.0.1", port);
  18896. cli.enable_server_certificate_verification(false);
  18897. cli.set_connection_timeout(5, 0);
  18898. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18899. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18900. std::string body(4096, 'A');
  18901. auto res = cli.Put("/api/test", body, "application/json");
  18902. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18903. EXPECT_EQ(StatusCode::OK_200, res->status);
  18904. EXPECT_EQ(body.size(), server_body_bytes.load());
  18905. }
  18906. #endif
  18907. template <typename S, typename C>
  18908. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18909. svr.Get("/stream", [&](const Request &, Response &res) {
  18910. auto data = new std::string("01234567890123456789");
  18911. res.set_content_provider(
  18912. data->size(), "text/plain",
  18913. [&, data](size_t offset, size_t length, DataSink &sink) {
  18914. const size_t DATA_CHUNK_SIZE = 4;
  18915. const auto &d = *data;
  18916. std::this_thread::sleep_for(std::chrono::seconds(1));
  18917. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18918. return true;
  18919. },
  18920. [data](bool success) {
  18921. EXPECT_FALSE(success);
  18922. delete data;
  18923. });
  18924. });
  18925. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18926. auto i = new size_t(0);
  18927. res.set_content_provider(
  18928. "text/plain",
  18929. [i](size_t, DataSink &sink) {
  18930. if (*i < 5) {
  18931. std::this_thread::sleep_for(std::chrono::seconds(1));
  18932. sink.write("abcd", 4);
  18933. (*i)++;
  18934. } else {
  18935. sink.done();
  18936. }
  18937. return true;
  18938. },
  18939. [i](bool success) {
  18940. EXPECT_FALSE(success);
  18941. delete i;
  18942. });
  18943. });
  18944. svr.Get("/chunked", [&](const Request &, Response &res) {
  18945. auto i = new size_t(0);
  18946. res.set_chunked_content_provider(
  18947. "text/plain",
  18948. [i](size_t, DataSink &sink) {
  18949. if (*i < 5) {
  18950. std::this_thread::sleep_for(std::chrono::seconds(1));
  18951. sink.os << "abcd";
  18952. (*i)++;
  18953. } else {
  18954. sink.done();
  18955. }
  18956. return true;
  18957. },
  18958. [i](bool success) {
  18959. EXPECT_FALSE(success);
  18960. delete i;
  18961. });
  18962. });
  18963. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18964. auto se = detail::scope_exit([&] {
  18965. svr.stop();
  18966. listen_thread.join();
  18967. ASSERT_FALSE(svr.is_running());
  18968. });
  18969. svr.wait_until_ready();
  18970. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18971. {
  18972. auto start = std::chrono::steady_clock::now();
  18973. auto res = cli.Get("/stream");
  18974. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18975. std::chrono::steady_clock::now() - start)
  18976. .count();
  18977. ASSERT_FALSE(res);
  18978. EXPECT_EQ(Error::Read, res.error());
  18979. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18980. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18981. }
  18982. {
  18983. auto start = std::chrono::steady_clock::now();
  18984. auto res = cli.Get("/stream_without_length");
  18985. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18986. std::chrono::steady_clock::now() - start)
  18987. .count();
  18988. ASSERT_FALSE(res);
  18989. EXPECT_EQ(Error::Read, res.error());
  18990. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18991. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18992. }
  18993. {
  18994. auto start = std::chrono::steady_clock::now();
  18995. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18996. EXPECT_EQ("abcd", string(data, data_length));
  18997. return true;
  18998. });
  18999. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19000. std::chrono::steady_clock::now() - start)
  19001. .count();
  19002. ASSERT_FALSE(res);
  19003. EXPECT_EQ(Error::Read, res.error());
  19004. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19005. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19006. }
  19007. }
  19008. TEST(MaxTimeoutTest, ContentStream) {
  19009. time_t timeout = 2000;
  19010. time_t threshold = 200;
  19011. Server svr;
  19012. Client cli("localhost", PORT);
  19013. max_timeout_test(svr, cli, timeout, threshold);
  19014. }
  19015. #ifdef CPPHTTPLIB_SSL_ENABLED
  19016. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19017. time_t timeout = 2000;
  19018. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19019. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19020. SSLClient cli("localhost", PORT);
  19021. cli.enable_server_certificate_verification(false);
  19022. max_timeout_test(svr, cli, timeout, threshold);
  19023. }
  19024. #endif
  19025. class EventDispatcher {
  19026. public:
  19027. EventDispatcher() {}
  19028. bool wait_event(DataSink *sink) {
  19029. unique_lock<mutex> lk(m_);
  19030. int id = id_;
  19031. // Wait with timeout to prevent hanging if client disconnects
  19032. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19033. [&] { return cid_ == id; })) {
  19034. return false; // Timeout occurred
  19035. }
  19036. sink->write(message_.data(), message_.size());
  19037. return true;
  19038. }
  19039. void send_event(const string &message) {
  19040. lock_guard<mutex> lk(m_);
  19041. cid_ = id_++;
  19042. message_ = message;
  19043. cv_.notify_all();
  19044. }
  19045. private:
  19046. mutex m_;
  19047. condition_variable cv_;
  19048. atomic_int id_{0};
  19049. atomic_int cid_{-1};
  19050. string message_;
  19051. };
  19052. TEST(ClientInThreadTest, Issue2068) {
  19053. EventDispatcher ed;
  19054. Server svr;
  19055. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19056. res.set_chunked_content_provider("text/event-stream",
  19057. [&](size_t /*offset*/, DataSink &sink) {
  19058. return ed.wait_event(&sink);
  19059. });
  19060. });
  19061. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19062. svr.wait_until_ready();
  19063. thread event_thread([&] {
  19064. int id = 0;
  19065. while (svr.is_running()) {
  19066. this_thread::sleep_for(chrono::milliseconds(500));
  19067. std::stringstream ss;
  19068. ss << "data: " << id << "\n\n";
  19069. ed.send_event(ss.str());
  19070. id++;
  19071. }
  19072. });
  19073. auto se = detail::scope_exit([&] {
  19074. svr.stop();
  19075. listen_thread.join();
  19076. event_thread.join();
  19077. ASSERT_FALSE(svr.is_running());
  19078. });
  19079. {
  19080. auto client = detail::make_unique<Client>(HOST, PORT);
  19081. client->set_read_timeout(std::chrono::minutes(10));
  19082. std::atomic<bool> stop{false};
  19083. std::thread t([&] {
  19084. client->Get("/event1",
  19085. [&](const char *, size_t) -> bool { return !stop; });
  19086. });
  19087. std::this_thread::sleep_for(std::chrono::seconds(2));
  19088. stop = true;
  19089. client->stop();
  19090. t.join();
  19091. // Reset client after thread has finished
  19092. client.reset();
  19093. }
  19094. }
  19095. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19096. auto handled = false;
  19097. Server svr;
  19098. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19100. auto se = detail::scope_exit([&] {
  19101. svr.stop();
  19102. t.join();
  19103. ASSERT_FALSE(svr.is_running());
  19104. ASSERT_FALSE(handled);
  19105. });
  19106. svr.wait_until_ready();
  19107. // Two Content-Length headers with different values — must be rejected
  19108. auto req = "POST /test HTTP/1.1\r\n"
  19109. "Content-Length: 5\r\n"
  19110. "Content-Length: 10\r\n"
  19111. "\r\n"
  19112. "hello";
  19113. std::string response;
  19114. ASSERT_TRUE(send_request(1, req, &response));
  19115. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19116. response.substr(0, response.find("\r\n")));
  19117. }
  19118. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19119. auto handled = false;
  19120. Server svr;
  19121. svr.Post("/test", [&](const Request &, Response &res) {
  19122. handled = true;
  19123. res.set_content("ok", "text/plain");
  19124. });
  19125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19126. auto se = detail::scope_exit([&] {
  19127. svr.stop();
  19128. t.join();
  19129. ASSERT_FALSE(svr.is_running());
  19130. ASSERT_TRUE(handled);
  19131. });
  19132. svr.wait_until_ready();
  19133. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19134. auto req = "POST /test HTTP/1.1\r\n"
  19135. "Host: localhost\r\n"
  19136. "Content-Length: 5\r\n"
  19137. "Content-Length: 5\r\n"
  19138. "\r\n"
  19139. "hello";
  19140. std::string response;
  19141. ASSERT_TRUE(send_request(1, req, &response));
  19142. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19143. }
  19144. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19145. Server svr;
  19146. svr.Get("/test", [](const Request &, Response &res) {
  19147. res.set_content("ok", "text/plain");
  19148. });
  19149. auto port = svr.bind_to_any_port(HOST);
  19150. thread t = thread([&] { svr.listen_after_bind(); });
  19151. auto se = detail::scope_exit([&] {
  19152. svr.stop();
  19153. t.join();
  19154. ASSERT_FALSE(svr.is_running());
  19155. });
  19156. svr.wait_until_ready();
  19157. auto status_line = [&](const std::string &host_lines) {
  19158. std::string res;
  19159. send_request(
  19160. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19161. &res, port);
  19162. return res.substr(0, res.find("\r\n"));
  19163. };
  19164. const char *accepted[] = {
  19165. "Host: localhost\r\n",
  19166. "Host: a.example:8080\r\n",
  19167. "Host: my_service\r\n",
  19168. "Host: [::1]:8080\r\n",
  19169. "Host: [fe80::1%25eth0]\r\n",
  19170. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19171. };
  19172. for (auto host_lines : accepted) {
  19173. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19174. }
  19175. const char *rejected[] = {
  19176. "Host: a.example\r\nHost: b.example\r\n",
  19177. "Host: a.example\r\nHost: a.example\r\n",
  19178. "Host: a@b.example\r\n",
  19179. "Host: a.example/b\r\n",
  19180. "Host: a.example\\b\r\n",
  19181. "Host: a.example?b\r\n",
  19182. "Host: a.example#b\r\n",
  19183. "Host: a.example b.example\r\n",
  19184. };
  19185. for (auto host_lines : rejected) {
  19186. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19187. << host_lines;
  19188. }
  19189. }
  19190. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19191. Server svr;
  19192. svr.Get("/", [](const Request &req, Response &res) {
  19193. EXPECT_EQ(2U, req.trailers.size());
  19194. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19195. // Denied
  19196. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19197. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19198. // Accepted
  19199. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19200. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19201. EXPECT_TRUE(req.has_trailer("X-World"));
  19202. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  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. const std::string req = "GET / HTTP/1.1\r\n"
  19213. "Transfer-Encoding: chunked\r\n"
  19214. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19215. "\r\n"
  19216. "0\r\n"
  19217. "Content-Length: 10\r\n"
  19218. "Host: internal.local\r\n"
  19219. "Content-Type: malicious/content\r\n"
  19220. "Cookie: any\r\n"
  19221. "Set-Cookie: any\r\n"
  19222. "X-Forwarded-For: attacker.com\r\n"
  19223. "X-Real-Ip: 1.1.1.1\r\n"
  19224. "X-Hello: hello\r\n"
  19225. "X-World: world\r\n"
  19226. "\r\n";
  19227. std::string res;
  19228. ASSERT_TRUE(send_request(1, req, &res));
  19229. }
  19230. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19231. // several field lines, and the combined value is what has to be parsed. A
  19232. // Trailer field split across lines therefore declares every name it lists;
  19233. // reading only the first line silently drops the trailers the later lines
  19234. // declare. The prohibited-trailer filter still applies to every line.
  19235. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19236. Server svr;
  19237. size_t observed_trailer_count = 0;
  19238. std::string observed_hello;
  19239. std::string observed_world;
  19240. bool observed_content_length = true;
  19241. svr.Get("/", [&](const Request &req, Response &res) {
  19242. observed_trailer_count = req.trailers.size();
  19243. observed_hello = req.get_trailer_value("X-Hello");
  19244. observed_world = req.get_trailer_value("X-World");
  19245. observed_content_length = req.has_trailer("Content-Length");
  19246. res.set_content("ok", "text/plain");
  19247. });
  19248. auto port = svr.bind_to_any_port(HOST);
  19249. thread t = thread([&]() { svr.listen_after_bind(); });
  19250. auto se = detail::scope_exit([&] {
  19251. svr.stop();
  19252. t.join();
  19253. ASSERT_FALSE(svr.is_running());
  19254. });
  19255. svr.wait_until_ready();
  19256. const std::string req = "GET / HTTP/1.1\r\n"
  19257. "Host: localhost\r\n"
  19258. "Transfer-Encoding: chunked\r\n"
  19259. "Trailer: X-Hello\r\n"
  19260. "Trailer: X-World, Content-Length\r\n"
  19261. "\r\n"
  19262. "0\r\n"
  19263. "X-Hello: hello\r\n"
  19264. "X-World: world\r\n"
  19265. "Content-Length: 10\r\n"
  19266. "\r\n";
  19267. std::string res;
  19268. ASSERT_TRUE(send_request(1, req, &res, port));
  19269. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19270. // Accepted: both field lines contribute to the declared set
  19271. EXPECT_EQ(2U, observed_trailer_count);
  19272. EXPECT_EQ(observed_hello, "hello");
  19273. EXPECT_EQ(observed_world, "world");
  19274. // Denied: a prohibited name stays prohibited on a later field line
  19275. EXPECT_FALSE(observed_content_length);
  19276. }
  19277. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19278. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19279. // unbounded run of fields that are never declared, because the counter would
  19280. // only advance for declared fields.
  19281. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19282. Server svr;
  19283. bool handler_called = false;
  19284. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19285. handler_called = true;
  19286. res.set_content("ok", "text/plain");
  19287. });
  19288. auto port = svr.bind_to_any_port(HOST);
  19289. thread t = thread([&]() { svr.listen_after_bind(); });
  19290. auto se = detail::scope_exit([&] {
  19291. svr.stop();
  19292. t.join();
  19293. ASSERT_FALSE(svr.is_running());
  19294. });
  19295. svr.wait_until_ready();
  19296. // Declare nothing, then send far more undeclared trailer fields than the
  19297. // header-count limit. Parsing must stop and reject the request rather than
  19298. // read every line.
  19299. std::string req = "GET / HTTP/1.1\r\n"
  19300. "Transfer-Encoding: chunked\r\n"
  19301. "\r\n"
  19302. "0\r\n";
  19303. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19304. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19305. }
  19306. req += "\r\n";
  19307. std::string res;
  19308. ASSERT_TRUE(send_request(1, req, &res, port));
  19309. // The request is rejected before the handler runs.
  19310. EXPECT_FALSE(handler_called);
  19311. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19312. }
  19313. // The set of declared trailer names is capped so a peer cannot grow it without
  19314. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19315. // declared past the cap is not honored, even if the field is actually sent.
  19316. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19317. Server svr;
  19318. // One name inside the cap and one past it, so the test tracks the cap rather
  19319. // than a fixed count.
  19320. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19321. const std::string within_cap_name = "X-T-0";
  19322. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19323. bool observed_within_cap = false;
  19324. bool observed_past_cap = false;
  19325. svr.Get("/", [&](const Request &req, Response &res) {
  19326. observed_within_cap = req.has_trailer(within_cap_name);
  19327. observed_past_cap = req.has_trailer(past_cap_name);
  19328. res.set_content("ok", "text/plain");
  19329. });
  19330. auto port = svr.bind_to_any_port(HOST);
  19331. thread t = thread([&]() { svr.listen_after_bind(); });
  19332. auto se = detail::scope_exit([&] {
  19333. svr.stop();
  19334. t.join();
  19335. ASSERT_FALSE(svr.is_running());
  19336. });
  19337. svr.wait_until_ready();
  19338. // Declare more trailer names than the cap in a single Trailer field, then
  19339. // actually send the first (within the cap) and the last (past it).
  19340. std::string trailer_decl = "Trailer: ";
  19341. for (int i = 0; i < declared_count; i++) {
  19342. if (i != 0) { trailer_decl += ", "; }
  19343. trailer_decl += "X-T-" + std::to_string(i);
  19344. }
  19345. trailer_decl += "\r\n";
  19346. const std::string req = "GET / HTTP/1.1\r\n"
  19347. "Host: localhost\r\n"
  19348. "Transfer-Encoding: chunked\r\n" +
  19349. trailer_decl +
  19350. "\r\n"
  19351. "0\r\n" +
  19352. within_cap_name + ": a\r\n" + past_cap_name +
  19353. ": b\r\n"
  19354. "\r\n";
  19355. std::string res;
  19356. ASSERT_TRUE(send_request(1, req, &res, port));
  19357. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19358. // A name within the cap is honored; one declared past the cap is dropped.
  19359. EXPECT_TRUE(observed_within_cap);
  19360. EXPECT_FALSE(observed_past_cap);
  19361. }
  19362. // A direct client that is not listed in trusted_proxies must not be able to
  19363. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19364. // the peer address on the actual TCP connection determines whether the
  19365. // header is honored.
  19366. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19367. Server svr;
  19368. // Deliberately does NOT include the loopback address the test client
  19369. // actually connects from, so the direct connection is not a trusted proxy.
  19370. svr.set_trusted_proxies({"203.0.113.66"});
  19371. std::string observed_remote_addr;
  19372. svr.Get("/ip", [&](const Request &req, Response &res) {
  19373. observed_remote_addr = req.remote_addr;
  19374. res.set_content("ok", "text/plain");
  19375. });
  19376. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19377. auto se = detail::scope_exit([&] {
  19378. svr.stop();
  19379. t.join();
  19380. ASSERT_FALSE(svr.is_running());
  19381. });
  19382. svr.wait_until_ready();
  19383. Client cli(HOST, PORT);
  19384. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19386. EXPECT_EQ(StatusCode::OK_200, res->status);
  19387. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19388. // ignored entirely and the real connection-level address retained.
  19389. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19390. observed_remote_addr == "127.0.0.1");
  19391. }
  19392. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19393. Server svr;
  19394. std::string observed_remote_addr;
  19395. std::string observed_xff;
  19396. svr.Get("/ip", [&](const Request &req, Response &res) {
  19397. observed_remote_addr = req.remote_addr;
  19398. observed_xff = req.get_header_value("X-Forwarded-For");
  19399. res.set_content("ok", "text/plain");
  19400. });
  19401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19402. auto se = detail::scope_exit([&] {
  19403. svr.stop();
  19404. t.join();
  19405. ASSERT_FALSE(svr.is_running());
  19406. });
  19407. svr.wait_until_ready();
  19408. Client cli(HOST, PORT);
  19409. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19411. EXPECT_EQ(StatusCode::OK_200, res->status);
  19412. EXPECT_EQ(observed_xff, "203.0.113.66");
  19413. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19414. observed_remote_addr == "127.0.0.1");
  19415. }
  19416. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19417. Server svr;
  19418. svr.set_trusted_proxies({"203.0.113.66"});
  19419. std::string observed_remote_addr;
  19420. std::string observed_xff;
  19421. svr.Get("/ip", [&](const Request &req, Response &res) {
  19422. observed_remote_addr = req.remote_addr;
  19423. observed_xff = req.get_header_value("X-Forwarded-For");
  19424. res.set_content("ok", "text/plain");
  19425. });
  19426. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19427. auto se = detail::scope_exit([&] {
  19428. svr.stop();
  19429. t.join();
  19430. ASSERT_FALSE(svr.is_running());
  19431. });
  19432. svr.wait_until_ready();
  19433. Client cli(HOST, PORT);
  19434. auto res = cli.Get("/ip");
  19435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19436. EXPECT_EQ(StatusCode::OK_200, res->status);
  19437. EXPECT_EQ(observed_xff, "");
  19438. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19439. observed_remote_addr == "127.0.0.1");
  19440. }
  19441. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19442. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19443. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19444. Server svr;
  19445. svr.set_trusted_proxies({"127.0.0.1"});
  19446. svr.Get("/ip", [](const Request &req, Response &res) {
  19447. res.set_content(req.remote_addr, "text/plain");
  19448. });
  19449. auto port = svr.bind_to_any_port("::");
  19450. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19451. thread t = thread([&] { svr.listen_after_bind(); });
  19452. auto se = detail::scope_exit([&] {
  19453. svr.stop();
  19454. t.join();
  19455. ASSERT_FALSE(svr.is_running());
  19456. });
  19457. svr.wait_until_ready();
  19458. Client cli("127.0.0.1", port);
  19459. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19461. EXPECT_EQ("198.51.100.23", res->body);
  19462. }
  19463. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19464. Server svr;
  19465. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19466. svr.Get("/ip", [](const Request &req, Response &res) {
  19467. res.set_content(req.remote_addr, "text/plain");
  19468. });
  19469. auto port = svr.bind_to_any_port(HOST);
  19470. ASSERT_GT(port, 0);
  19471. thread t = thread([&] { svr.listen_after_bind(); });
  19472. auto se = detail::scope_exit([&] {
  19473. svr.stop();
  19474. t.join();
  19475. ASSERT_FALSE(svr.is_running());
  19476. });
  19477. svr.wait_until_ready();
  19478. Client cli(HOST, port);
  19479. auto res = cli.Get(
  19480. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19482. EXPECT_EQ("198.51.100.23", res->body);
  19483. }
  19484. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19485. Server svr;
  19486. // Include the loopback address the test client actually connects from, so
  19487. // the direct connection itself is recognized as the trusted proxy hop.
  19488. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19489. std::string observed_remote_addr;
  19490. std::string observed_xff;
  19491. svr.Get("/ip", [&](const Request &req, Response &res) {
  19492. observed_remote_addr = req.remote_addr;
  19493. observed_xff = req.get_header_value("X-Forwarded-For");
  19494. res.set_content("ok", "text/plain");
  19495. });
  19496. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19497. auto se = detail::scope_exit([&] {
  19498. svr.stop();
  19499. t.join();
  19500. ASSERT_FALSE(svr.is_running());
  19501. });
  19502. svr.wait_until_ready();
  19503. Client cli(HOST, PORT);
  19504. auto res = cli.Get(
  19505. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19507. EXPECT_EQ(StatusCode::OK_200, res->status);
  19508. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19509. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19510. }
  19511. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19512. Server svr;
  19513. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19514. std::string observed_remote_addr;
  19515. std::string observed_xff;
  19516. svr.Get("/ip", [&](const Request &req, Response &res) {
  19517. observed_remote_addr = req.remote_addr;
  19518. observed_xff = req.get_header_value("X-Forwarded-For");
  19519. res.set_content("ok", "text/plain");
  19520. });
  19521. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19522. auto se = detail::scope_exit([&] {
  19523. svr.stop();
  19524. t.join();
  19525. ASSERT_FALSE(svr.is_running());
  19526. });
  19527. svr.wait_until_ready();
  19528. Client cli(HOST, PORT);
  19529. auto res = cli.Get(
  19530. "/ip",
  19531. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19533. EXPECT_EQ(StatusCode::OK_200, res->status);
  19534. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19535. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19536. }
  19537. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19538. Server svr;
  19539. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19540. std::string observed_remote_addr;
  19541. std::string observed_xff;
  19542. svr.Get("/ip", [&](const Request &req, Response &res) {
  19543. observed_remote_addr = req.remote_addr;
  19544. observed_xff = req.get_header_value("X-Forwarded-For");
  19545. res.set_content("ok", "text/plain");
  19546. });
  19547. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19548. auto se = detail::scope_exit([&] {
  19549. svr.stop();
  19550. t.join();
  19551. ASSERT_FALSE(svr.is_running());
  19552. });
  19553. svr.wait_until_ready();
  19554. Client cli(HOST, PORT);
  19555. auto res = cli.Get(
  19556. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19558. EXPECT_EQ(StatusCode::OK_200, res->status);
  19559. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19560. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19561. // and must not be selected.
  19562. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19563. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19564. }
  19565. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19566. Server svr;
  19567. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19568. std::string observed_remote_addr;
  19569. svr.Get("/ip", [&](const Request &req, Response &res) {
  19570. observed_remote_addr = req.remote_addr;
  19571. res.set_content("ok", "text/plain");
  19572. });
  19573. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19574. auto se = detail::scope_exit([&] {
  19575. svr.stop();
  19576. t.join();
  19577. ASSERT_FALSE(svr.is_running());
  19578. });
  19579. svr.wait_until_ready();
  19580. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19581. // a forged address and the trusted proxy's own address; the forged value must
  19582. // not win over the address the trusted proxy actually recorded.
  19583. Client cli(HOST, PORT);
  19584. auto res = cli.Get(
  19585. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19587. EXPECT_EQ(StatusCode::OK_200, res->status);
  19588. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19589. }
  19590. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19591. Server svr;
  19592. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19593. std::string observed_remote_addr;
  19594. std::string observed_xff;
  19595. svr.Get("/ip", [&](const Request &req, Response &res) {
  19596. observed_remote_addr = req.remote_addr;
  19597. observed_xff = req.get_header_value("X-Forwarded-For");
  19598. res.set_content("ok", "text/plain");
  19599. });
  19600. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19601. auto se = detail::scope_exit([&] {
  19602. svr.stop();
  19603. t.join();
  19604. ASSERT_FALSE(svr.is_running());
  19605. });
  19606. svr.wait_until_ready();
  19607. Client cli(HOST, PORT);
  19608. auto res = cli.Get(
  19609. "/ip",
  19610. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19612. EXPECT_EQ(StatusCode::OK_200, res->status);
  19613. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19614. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19615. }
  19616. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19617. Server svr;
  19618. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19619. std::string observed_remote_addr;
  19620. std::string observed_xff;
  19621. svr.Get("/ip", [&](const Request &req, Response &res) {
  19622. observed_remote_addr = req.remote_addr;
  19623. observed_xff = req.get_header_value("X-Forwarded-For");
  19624. res.set_content("ok", "text/plain");
  19625. });
  19626. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19627. auto se = detail::scope_exit([&] {
  19628. svr.stop();
  19629. t.join();
  19630. ASSERT_FALSE(svr.is_running());
  19631. });
  19632. svr.wait_until_ready();
  19633. std::string raw_req =
  19634. "GET /ip HTTP/1.1\r\n"
  19635. "Host: localhost\r\n"
  19636. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19637. "Connection: close\r\n"
  19638. "\r\n";
  19639. std::string out;
  19640. ASSERT_TRUE(send_request(5, raw_req, &out));
  19641. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19642. // Header parser trims surrounding whitespace of the header value
  19643. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19644. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19645. }
  19646. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19647. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19648. // their own X-Forwarded-For as a separate field line rather than extending the
  19649. // one the client sent, so every occurrence has to be taken into account.
  19650. // Reading only the first one hands back the address the client chose.
  19651. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19652. Server svr;
  19653. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19654. std::string observed_remote_addr;
  19655. size_t observed_xff_count = 0;
  19656. svr.Get("/ip", [&](const Request &req, Response &res) {
  19657. observed_remote_addr = req.remote_addr;
  19658. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19659. res.set_content("ok", "text/plain");
  19660. });
  19661. auto port = svr.bind_to_any_port(HOST);
  19662. thread t = thread([&]() { svr.listen_after_bind(); });
  19663. auto se = detail::scope_exit([&] {
  19664. svr.stop();
  19665. t.join();
  19666. ASSERT_FALSE(svr.is_running());
  19667. });
  19668. svr.wait_until_ready();
  19669. // The client supplies the first field line; the trusted proxy appends the
  19670. // address it observed as a second one.
  19671. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19672. "Host: localhost\r\n"
  19673. "X-Forwarded-For: 1.2.3.4\r\n"
  19674. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19675. "Connection: close\r\n"
  19676. "\r\n";
  19677. std::string out;
  19678. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19679. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19680. EXPECT_EQ(observed_xff_count, 2U);
  19681. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19682. // The same chain spread over one field line per hop derives the same client
  19683. // address, i.e. the split and the comma-joined representations agree.
  19684. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19685. "Host: localhost\r\n"
  19686. "X-Forwarded-For: 1.2.3.4\r\n"
  19687. "X-Forwarded-For: 198.51.100.23\r\n"
  19688. "X-Forwarded-For: 192.0.2.45\r\n"
  19689. "Connection: close\r\n"
  19690. "\r\n";
  19691. out.clear();
  19692. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19693. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19694. EXPECT_EQ(observed_xff_count, 3U);
  19695. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19696. }
  19697. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19698. // crash the server (it used to call front() on an empty vector inside
  19699. // get_client_ip). The connection-level remote address must be retained instead.
  19700. static void run_malformed_xff_test(const std::string &xff_value) {
  19701. Server svr;
  19702. svr.set_trusted_proxies({"192.0.2.45"});
  19703. std::string observed_remote_addr;
  19704. svr.Get("/ip", [&](const Request &req, Response &res) {
  19705. observed_remote_addr = req.remote_addr;
  19706. res.set_content("ok", "text/plain");
  19707. });
  19708. int port = 0;
  19709. thread t = thread([&]() {
  19710. port = svr.bind_to_any_port(HOST);
  19711. svr.listen_after_bind();
  19712. });
  19713. auto se = detail::scope_exit([&] {
  19714. svr.stop();
  19715. t.join();
  19716. ASSERT_FALSE(svr.is_running());
  19717. });
  19718. svr.wait_until_ready();
  19719. Client cli(HOST, port);
  19720. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19722. EXPECT_EQ(StatusCode::OK_200, res->status);
  19723. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19724. observed_remote_addr == "127.0.0.1");
  19725. }
  19726. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19727. run_malformed_xff_test("");
  19728. }
  19729. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19730. run_malformed_xff_test(",");
  19731. }
  19732. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19733. run_malformed_xff_test(", , ,");
  19734. }
  19735. // The same rule applies to Accept: a request whose acceptable types are spread
  19736. // over several field lines must be negotiated against all of them.
  19737. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19738. // case-insensitive connection options. Comparing the whole field value against
  19739. // one option misses a client that sends several of them, and misses every
  19740. // casing but the one written in the comparison.
  19741. //
  19742. // Sends req, reads the response, then reuses the same socket for a second
  19743. // request to find out whether the server kept the connection.
  19744. static void probe_connection_reuse(int port, const std::string &req,
  19745. bool *announced_close, bool *reusable) {
  19746. auto error = Error::Success;
  19747. auto sock = detail::create_client_socket(
  19748. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19749. /*connection_timeout_sec=*/5, 0,
  19750. /*read_timeout_sec=*/1, 0,
  19751. /*write_timeout_sec=*/5, 0, std::string(), error);
  19752. ASSERT_NE(sock, INVALID_SOCKET);
  19753. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19754. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19755. "Host: localhost\r\n"
  19756. "Connection: close\r\n"
  19757. "\r\n";
  19758. std::string first_response;
  19759. std::string second_response;
  19760. detail::process_client_socket(
  19761. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19762. [&](Stream &strm) {
  19763. if (strm.write(req.data(), req.size()) !=
  19764. static_cast<ssize_t>(req.size())) {
  19765. return false;
  19766. }
  19767. char buf[512];
  19768. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19769. // Headers plus the two-byte body of the handler below
  19770. while (reader.getline()) {
  19771. first_response += reader.ptr();
  19772. if (first_response.find("ok") != std::string::npos) { break; }
  19773. }
  19774. if (strm.write(second.data(), second.size()) !=
  19775. static_cast<ssize_t>(second.size())) {
  19776. return true;
  19777. }
  19778. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19779. while (reader2.getline()) {
  19780. second_response += reader2.ptr();
  19781. if (second_response.find("ok") != std::string::npos) { break; }
  19782. }
  19783. return true;
  19784. });
  19785. *announced_close =
  19786. first_response.find("Connection: close") != std::string::npos;
  19787. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19788. }
  19789. class ConnectionTokenTest : public ::testing::Test {
  19790. protected:
  19791. void SetUp() override {
  19792. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19793. res.set_content("ok", "text/plain");
  19794. });
  19795. port_ = svr_.bind_to_any_port(HOST);
  19796. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19797. svr_.wait_until_ready();
  19798. }
  19799. void TearDown() override {
  19800. svr_.stop();
  19801. if (thread_.joinable()) { thread_.join(); }
  19802. }
  19803. Server svr_;
  19804. int port_ = 0;
  19805. thread thread_;
  19806. };
  19807. // "close" alongside another option still closes the connection, and the
  19808. // response says so rather than leaving the peer to discover it.
  19809. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19810. bool announced_close = false;
  19811. bool reusable = true;
  19812. probe_connection_reuse(port_,
  19813. "GET /keepalive HTTP/1.1\r\n"
  19814. "Host: localhost\r\n"
  19815. "Connection: keep-alive, close\r\n"
  19816. "\r\n",
  19817. &announced_close, &reusable);
  19818. EXPECT_TRUE(announced_close);
  19819. EXPECT_FALSE(reusable);
  19820. }
  19821. // "close" split over two field lines is the same list, so it is honored too.
  19822. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19823. bool announced_close = false;
  19824. bool reusable = true;
  19825. probe_connection_reuse(port_,
  19826. "GET /keepalive HTTP/1.1\r\n"
  19827. "Host: localhost\r\n"
  19828. "Connection: keep-alive\r\n"
  19829. "Connection: close\r\n"
  19830. "\r\n",
  19831. &announced_close, &reusable);
  19832. EXPECT_TRUE(announced_close);
  19833. EXPECT_FALSE(reusable);
  19834. }
  19835. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19836. // keep-alive in the spelling everyone actually sends keeps its connection.
  19837. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19838. bool announced_close = false;
  19839. bool reusable = false;
  19840. probe_connection_reuse(port_,
  19841. "GET /keepalive HTTP/1.0\r\n"
  19842. "Host: localhost\r\n"
  19843. "Connection: keep-alive\r\n"
  19844. "\r\n",
  19845. &announced_close, &reusable);
  19846. EXPECT_FALSE(announced_close);
  19847. EXPECT_TRUE(reusable);
  19848. }
  19849. // A token the value merely contains is not the token itself.
  19850. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19851. bool announced_close = false;
  19852. bool reusable = false;
  19853. probe_connection_reuse(port_,
  19854. "GET /keepalive HTTP/1.1\r\n"
  19855. "Host: localhost\r\n"
  19856. "Connection: notclose\r\n"
  19857. "\r\n",
  19858. &announced_close, &reusable);
  19859. EXPECT_FALSE(announced_close);
  19860. EXPECT_TRUE(reusable);
  19861. }
  19862. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19863. Server svr;
  19864. std::vector<std::string> observed_types;
  19865. svr.Get("/", [&](const Request &req, Response &res) {
  19866. observed_types = req.accept_content_types;
  19867. res.set_content("ok", "text/plain");
  19868. });
  19869. auto port = svr.bind_to_any_port(HOST);
  19870. thread t = thread([&]() { svr.listen_after_bind(); });
  19871. auto se = detail::scope_exit([&] {
  19872. svr.stop();
  19873. t.join();
  19874. ASSERT_FALSE(svr.is_running());
  19875. });
  19876. svr.wait_until_ready();
  19877. Client cli(HOST, port);
  19878. Headers headers;
  19879. headers.emplace("Accept", "text/plain;q=0.5");
  19880. headers.emplace("Accept", "application/json");
  19881. auto res = cli.Get("/", headers);
  19882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19883. EXPECT_EQ(StatusCode::OK_200, res->status);
  19884. // Sorted by q-value, so the second field line's type comes first
  19885. ASSERT_EQ(2U, observed_types.size());
  19886. EXPECT_EQ("application/json", observed_types[0]);
  19887. EXPECT_EQ("text/plain", observed_types[1]);
  19888. }
  19889. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19890. // empty field line must not contribute a bare comma to the combined value.
  19891. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19892. Server svr;
  19893. std::vector<std::string> observed_types;
  19894. svr.Get("/", [&](const Request &req, Response &res) {
  19895. observed_types = req.accept_content_types;
  19896. res.set_content("ok", "text/plain");
  19897. });
  19898. auto port = svr.bind_to_any_port(HOST);
  19899. thread t = thread([&]() { svr.listen_after_bind(); });
  19900. auto se = detail::scope_exit([&] {
  19901. svr.stop();
  19902. t.join();
  19903. ASSERT_FALSE(svr.is_running());
  19904. });
  19905. svr.wait_until_ready();
  19906. // Empty first field line, then a real one
  19907. std::string raw_req = "GET / HTTP/1.1\r\n"
  19908. "Host: localhost\r\n"
  19909. "Accept:\r\n"
  19910. "Accept: application/json\r\n"
  19911. "Connection: close\r\n"
  19912. "\r\n";
  19913. std::string out;
  19914. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19915. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19916. ASSERT_EQ(1U, observed_types.size());
  19917. EXPECT_EQ("application/json", observed_types[0]);
  19918. }
  19919. // The skip in get_combined_header_value() is what keeps an empty field line
  19920. // from contributing a bare comma. Only a trailing empty field line exercises
  19921. // it: a leading one is already covered by the "combined is still empty" check,
  19922. // and parse_accept_header() now ignores the empty element either way, so the
  19923. // request-level test above can no longer tell the two apart.
  19924. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19925. Headers headers;
  19926. headers.emplace("Accept", "text/html");
  19927. headers.emplace("Accept", "");
  19928. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19929. headers.clear();
  19930. headers.emplace("Accept", "");
  19931. headers.emplace("Accept", "application/json");
  19932. EXPECT_EQ("application/json",
  19933. detail::get_combined_header_value(headers, "Accept"));
  19934. }
  19935. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19936. // An encoding offered on a later Accept-Encoding field line is still offered.
  19937. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19938. Server svr;
  19939. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19940. res.set_content(std::string(1024, 'x'), "text/plain");
  19941. });
  19942. auto port = svr.bind_to_any_port(HOST);
  19943. thread t = thread([&]() { svr.listen_after_bind(); });
  19944. auto se = detail::scope_exit([&] {
  19945. svr.stop();
  19946. t.join();
  19947. ASSERT_FALSE(svr.is_running());
  19948. });
  19949. svr.wait_until_ready();
  19950. Client cli(HOST, port);
  19951. cli.set_decompress(false);
  19952. Headers headers;
  19953. headers.emplace("Accept-Encoding", "identity");
  19954. headers.emplace("Accept-Encoding", "gzip");
  19955. auto res = cli.Get("/", headers);
  19956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19957. EXPECT_EQ(StatusCode::OK_200, res->status);
  19958. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19959. }
  19960. #endif
  19961. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19962. // Transfer-Encoding is not its body.
  19963. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19964. Server svr;
  19965. svr.set_payload_max_length(8);
  19966. svr.Post("/test", [](const Request &, Response &res) {
  19967. res.set_content("ok", "text/plain");
  19968. });
  19969. auto port = svr.bind_to_any_port(HOST);
  19970. ASSERT_GT(port, 0);
  19971. thread t = thread([&] { svr.listen_after_bind(); });
  19972. auto se = detail::scope_exit([&] {
  19973. svr.stop();
  19974. t.join();
  19975. ASSERT_FALSE(svr.is_running());
  19976. });
  19977. svr.wait_until_ready();
  19978. std::string resp;
  19979. ASSERT_TRUE(send_request(1,
  19980. "POST /test HTTP/1.1\r\n"
  19981. "Host: localhost\r\n"
  19982. "Connection: close\r\n"
  19983. "\r\n" +
  19984. std::string(16, 'X'),
  19985. &resp, port));
  19986. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19987. }
  19988. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19989. Server svr;
  19990. svr.Post("/post", [&](const Request &req, Response &res) {
  19991. res.set_content(req.body, "text/plain");
  19992. });
  19993. svr.Put("/put", [&](const Request &req, Response &res) {
  19994. res.set_content(req.body, "text/plain");
  19995. });
  19996. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19997. res.set_content(req.body, "text/plain");
  19998. });
  19999. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20000. res.set_content(req.body, "text/plain");
  20001. });
  20002. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20003. auto se = detail::scope_exit([&] {
  20004. svr.stop();
  20005. t.join();
  20006. ASSERT_FALSE(svr.is_running());
  20007. });
  20008. svr.wait_until_ready();
  20009. std::string resp;
  20010. // POST without Content-Length
  20011. ASSERT_TRUE(send_request(5,
  20012. "POST /post HTTP/1.1\r\n"
  20013. "Host: localhost\r\n"
  20014. "Connection: close\r\n"
  20015. "\r\n",
  20016. &resp));
  20017. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20018. // PUT without Content-Length
  20019. resp.clear();
  20020. ASSERT_TRUE(send_request(5,
  20021. "PUT /put HTTP/1.1\r\n"
  20022. "Host: localhost\r\n"
  20023. "Connection: close\r\n"
  20024. "\r\n",
  20025. &resp));
  20026. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20027. // PATCH without Content-Length
  20028. resp.clear();
  20029. ASSERT_TRUE(send_request(5,
  20030. "PATCH /patch HTTP/1.1\r\n"
  20031. "Host: localhost\r\n"
  20032. "Connection: close\r\n"
  20033. "\r\n",
  20034. &resp));
  20035. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20036. // DELETE without Content-Length
  20037. resp.clear();
  20038. ASSERT_TRUE(send_request(5,
  20039. "DELETE /delete HTTP/1.1\r\n"
  20040. "Host: localhost\r\n"
  20041. "Connection: close\r\n"
  20042. "\r\n",
  20043. &resp));
  20044. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20045. }
  20046. //==============================================================================
  20047. // open_stream() Tests
  20048. //==============================================================================
  20049. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20050. std::string result;
  20051. char buf[8192];
  20052. ssize_t n;
  20053. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20054. result.append(buf, static_cast<size_t>(n));
  20055. }
  20056. return result;
  20057. }
  20058. // Mock stream for unit tests
  20059. class MockStream : public Stream {
  20060. public:
  20061. std::string data;
  20062. size_t pos = 0;
  20063. ssize_t error_after = -1; // -1 = no error
  20064. explicit MockStream(const std::string &d, ssize_t err = -1)
  20065. : data(d), error_after(err) {}
  20066. bool is_readable() const override { return true; }
  20067. bool wait_readable() const override { return true; }
  20068. bool wait_writable() const override { return true; }
  20069. ssize_t read(char *ptr, size_t size) override {
  20070. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20071. if (pos >= data.size()) return 0;
  20072. size_t limit =
  20073. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20074. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20075. std::memcpy(ptr, data.data() + pos, to_read);
  20076. pos += to_read;
  20077. return static_cast<ssize_t>(to_read);
  20078. }
  20079. ssize_t write(const char *, size_t) override { return -1; }
  20080. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20081. ip = "127.0.0.1";
  20082. port = 0;
  20083. }
  20084. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20085. ip = "127.0.0.1";
  20086. port = 0;
  20087. }
  20088. socket_t socket() const override { return INVALID_SOCKET; }
  20089. time_t duration() const override { return 0; }
  20090. };
  20091. TEST(StreamHandleTest, Basic) {
  20092. ClientImpl::StreamHandle handle;
  20093. EXPECT_FALSE(handle.is_valid());
  20094. handle.response = detail::make_unique<Response>();
  20095. handle.error = Error::Connection;
  20096. EXPECT_FALSE(handle.is_valid());
  20097. handle.error = Error::Success;
  20098. EXPECT_TRUE(handle.is_valid());
  20099. }
  20100. TEST(BodyReaderTest, Basic) {
  20101. MockStream stream("Hello, World!");
  20102. detail::BodyReader reader;
  20103. reader.stream = &stream;
  20104. reader.content_length = 13;
  20105. char buf[32];
  20106. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20107. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20108. EXPECT_TRUE(reader.eof);
  20109. }
  20110. TEST(BodyReaderTest, NoStream) {
  20111. detail::BodyReader reader;
  20112. char buf[32];
  20113. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20114. EXPECT_EQ(Error::Connection, reader.last_error);
  20115. }
  20116. TEST(BodyReaderTest, Error) {
  20117. MockStream stream("Hello, World!", 5);
  20118. detail::BodyReader reader;
  20119. reader.stream = &stream;
  20120. reader.content_length = 13;
  20121. char buf[32];
  20122. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20123. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20124. EXPECT_EQ(Error::Read, reader.last_error);
  20125. }
  20126. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20127. // Mock-based StreamHandle tests relying on private internals are removed.
  20128. class OpenStreamTest : public ::testing::Test {
  20129. protected:
  20130. void SetUp() override {
  20131. svr_.Get("/hello", [](const Request &, Response &res) {
  20132. res.set_content("Hello World!", "text/plain");
  20133. });
  20134. svr_.Get("/large", [](const Request &, Response &res) {
  20135. res.set_content(std::string(10000, 'X'), "text/plain");
  20136. });
  20137. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20138. res.set_content("Hello World!", "image/jpeg");
  20139. res.set_header("Content-Encoding", "UTF-8");
  20140. });
  20141. svr_.Get("/chunked", [](const Request &, Response &res) {
  20142. res.set_chunked_content_provider("text/plain",
  20143. [](size_t offset, DataSink &sink) {
  20144. if (offset < 15) {
  20145. sink.write("chunk", 5);
  20146. return true;
  20147. }
  20148. sink.done();
  20149. return true;
  20150. });
  20151. });
  20152. svr_.Get("/compressible", [](const Request &, Response &res) {
  20153. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20154. DataSink &sink) {
  20155. if (offset < 100 * 1024) {
  20156. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20157. sink.write(chunk.data(), chunk.size());
  20158. return true;
  20159. }
  20160. sink.done();
  20161. return true;
  20162. });
  20163. });
  20164. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20165. [](const Request & /*req*/, Response &res) {
  20166. auto i = new int(0);
  20167. res.set_header("Trailer", "Content-Length, X-Allowed");
  20168. res.set_chunked_content_provider(
  20169. "text/plain",
  20170. [i](size_t /*offset*/, DataSink &sink) {
  20171. switch (*i) {
  20172. case 0: sink.os << "123"; break;
  20173. case 1: sink.os << "456"; break;
  20174. case 2: sink.os << "789"; break;
  20175. case 3: {
  20176. sink.done_with_trailer(
  20177. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20178. } break;
  20179. }
  20180. (*i)++;
  20181. return true;
  20182. },
  20183. [i](bool success) {
  20184. EXPECT_TRUE(success);
  20185. delete i;
  20186. });
  20187. });
  20188. // Echo headers endpoint for header-related tests
  20189. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20190. std::string body;
  20191. for (const auto &h : req.headers) {
  20192. body.append(h.first);
  20193. body.push_back(':');
  20194. body.append(h.second);
  20195. body.push_back('\n');
  20196. }
  20197. res.set_content(body, "text/plain");
  20198. });
  20199. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20200. std::string body;
  20201. for (const auto &h : req.headers) {
  20202. body.append(h.first);
  20203. body.push_back(':');
  20204. body.append(h.second);
  20205. body.push_back('\n');
  20206. }
  20207. res.set_content(body, "text/plain");
  20208. });
  20209. port_ = svr_.bind_to_any_port("127.0.0.1");
  20210. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20211. svr_.wait_until_ready();
  20212. }
  20213. void TearDown() override {
  20214. svr_.stop();
  20215. if (thread_.joinable()) thread_.join();
  20216. }
  20217. Server svr_;
  20218. std::thread thread_;
  20219. int port_ = 0;
  20220. };
  20221. TEST_F(OpenStreamTest, Basic) {
  20222. Client cli("127.0.0.1", port_);
  20223. auto handle = cli.open_stream("GET", "/hello");
  20224. EXPECT_TRUE(handle.is_valid());
  20225. EXPECT_EQ("Hello World!", read_all(handle));
  20226. }
  20227. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20228. Client cli("127.0.0.1", port_);
  20229. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20230. ASSERT_TRUE(handle.is_valid());
  20231. EXPECT_EQ("Hello World!", read_all(handle));
  20232. }
  20233. TEST_F(OpenStreamTest, SmallBuffer) {
  20234. Client cli("127.0.0.1", port_);
  20235. auto handle = cli.open_stream("GET", "/hello");
  20236. std::string result;
  20237. char buf[4];
  20238. ssize_t n;
  20239. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20240. result.append(buf, static_cast<size_t>(n));
  20241. EXPECT_EQ("Hello World!", result);
  20242. }
  20243. TEST_F(OpenStreamTest, DefaultHeaders) {
  20244. Client cli("127.0.0.1", port_);
  20245. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20246. {
  20247. auto handle = cli.open_stream("GET", "/echo-headers");
  20248. ASSERT_TRUE(handle.is_valid());
  20249. auto body = read_all(handle);
  20250. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20251. std::string::npos);
  20252. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20253. std::string::npos);
  20254. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20255. }
  20256. // open_stream POST with body and no explicit content_type should NOT add
  20257. // text/plain Content-Type (behavior differs from non-streaming path), but
  20258. // should include Content-Length
  20259. {
  20260. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20261. ASSERT_TRUE(handle.is_valid());
  20262. auto body = read_all(handle);
  20263. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20264. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20265. }
  20266. // open_stream POST with explicit Content-Type should preserve it
  20267. {
  20268. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20269. {{"Content-Type", "application/custom"}},
  20270. "{}", "application/custom");
  20271. ASSERT_TRUE(handle.is_valid());
  20272. auto body = read_all(handle);
  20273. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20274. }
  20275. // User-specified User-Agent must not be overwritten for stream API
  20276. {
  20277. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20278. {{"User-Agent", "MyAgent/1.2"}});
  20279. ASSERT_TRUE(handle.is_valid());
  20280. auto body = read_all(handle);
  20281. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20282. }
  20283. }
  20284. TEST_F(OpenStreamTest, Large) {
  20285. Client cli("127.0.0.1", port_);
  20286. auto handle = cli.open_stream("GET", "/large");
  20287. EXPECT_EQ(10000u, read_all(handle).size());
  20288. }
  20289. TEST_F(OpenStreamTest, ConnectionError) {
  20290. Client cli("127.0.0.1", 9999);
  20291. auto handle = cli.open_stream("GET", "/hello");
  20292. EXPECT_FALSE(handle.is_valid());
  20293. }
  20294. TEST_F(OpenStreamTest, Chunked) {
  20295. Client cli("127.0.0.1", port_);
  20296. auto handle = cli.open_stream("GET", "/chunked");
  20297. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20298. "Transfer-Encoding") == "chunked");
  20299. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20300. }
  20301. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20302. Client cli("127.0.0.1", port_);
  20303. auto handle =
  20304. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20305. ASSERT_TRUE(handle.is_valid());
  20306. // Consume body to allow trailers to be received/parsed
  20307. auto body = read_all(handle);
  20308. // Explicitly parse trailers (ensure trailers are available for assertion)
  20309. handle.parse_trailers_if_needed();
  20310. EXPECT_EQ(std::string("123456789"), body);
  20311. // The response should include a Trailer header declaring both names
  20312. ASSERT_TRUE(handle.response);
  20313. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20314. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20315. handle.response->get_header_value("Trailer"));
  20316. // Prohibited trailer must not be present
  20317. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20318. // Allowed trailer should be present
  20319. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20320. EXPECT_EQ(std::string("yes"),
  20321. handle.response->get_trailer_value("X-Allowed"));
  20322. // Verify trailers are NOT present as regular headers
  20323. EXPECT_EQ(std::string(""),
  20324. handle.response->get_header_value("Content-Length"));
  20325. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20326. }
  20327. // Accepts one connection on an OS-assigned port, which it hands over through
  20328. // port_promise, reads the request head and sends back response. after_send,
  20329. // if given, runs on the connection before it is closed.
  20330. static std::thread
  20331. serve_single_response(std::promise<int> &port_promise,
  20332. const std::string &response,
  20333. std::function<void(socket_t)> after_send = nullptr) {
  20334. return std::thread([&port_promise, response, after_send] {
  20335. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20336. default_socket_options(srv);
  20337. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20338. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20339. sockaddr_in addr{};
  20340. addr.sin_family = AF_INET;
  20341. addr.sin_port = htons(0); // Let OS assign a free port
  20342. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20343. int opt = 1;
  20344. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20345. #ifdef _WIN32
  20346. reinterpret_cast<const char *>(&opt),
  20347. #else
  20348. &opt,
  20349. #endif
  20350. sizeof(opt));
  20351. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20352. ::listen(srv, 1) != 0) {
  20353. port_promise.set_value(-1);
  20354. detail::close_socket(srv);
  20355. return;
  20356. }
  20357. socklen_t addr_len = sizeof(addr);
  20358. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20359. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20360. sockaddr_in cli_addr{};
  20361. socklen_t cli_len = sizeof(cli_addr);
  20362. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20363. if (cli != INVALID_SOCKET) {
  20364. // Read the complete HTTP request (until the blank line that terminates
  20365. // headers) before sending the response. If the server closes the socket
  20366. // while the client's request data is still unread in the kernel receive
  20367. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20368. // connection on both sides: it discards the client's receive buffer
  20369. // (which already holds our response) and causes any in-progress write on
  20370. // the client to fail with ECONNRESET. Reading all request data first
  20371. // ensures close() emits a graceful FIN.
  20372. {
  20373. char rbuf[256];
  20374. std::string req;
  20375. while (req.find("\r\n\r\n") == std::string::npos) {
  20376. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20377. if (n <= 0) { break; }
  20378. req.append(rbuf, static_cast<size_t>(n));
  20379. }
  20380. }
  20381. ::send(cli,
  20382. #ifdef _WIN32
  20383. static_cast<const char *>(response.c_str()),
  20384. static_cast<int>(response.size()),
  20385. #else
  20386. response.c_str(), response.size(),
  20387. #endif
  20388. 0);
  20389. if (after_send) { after_send(cli); }
  20390. detail::close_socket(cli);
  20391. }
  20392. detail::close_socket(srv);
  20393. });
  20394. }
  20395. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20396. #ifndef _WIN32
  20397. signal(SIGPIPE, SIG_IGN);
  20398. #endif
  20399. std::promise<int> port_promise;
  20400. auto port_future = port_promise.get_future();
  20401. auto server_thread =
  20402. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20403. "Content-Type: text/plain\r\n"
  20404. "Content-Length: not-a-number\r\n"
  20405. "Connection: close\r\n"
  20406. "\r\n"
  20407. "hello");
  20408. auto port = port_future.get();
  20409. ASSERT_GT(port, 0);
  20410. Client cli("127.0.0.1", port);
  20411. auto handle = cli.open_stream("GET", "/");
  20412. EXPECT_FALSE(handle.is_valid());
  20413. server_thread.join();
  20414. }
  20415. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20416. #ifndef _WIN32
  20417. signal(SIGPIPE, SIG_IGN);
  20418. #endif
  20419. std::promise<int> port_promise;
  20420. auto port_future = port_promise.get_future();
  20421. auto server_thread = serve_single_response(
  20422. port_promise, "HTTP/1.1 200 OK\r\n"
  20423. "Content-Type: text/plain\r\n"
  20424. "Content-Length: 99999999999999999999999999\r\n"
  20425. "Connection: close\r\n"
  20426. "\r\n"
  20427. "hello");
  20428. auto port = port_future.get();
  20429. ASSERT_GT(port, 0);
  20430. // Historically std::stoull would throw std::out_of_range here and crash
  20431. // the process, then parsing silently clamped to a bogus framing length and
  20432. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20433. // so the stream fails to open, matching the not-a-number case above. The
  20434. // process still must NOT terminate.
  20435. Client cli("127.0.0.1", port);
  20436. auto handle = cli.open_stream("GET", "/");
  20437. EXPECT_FALSE(handle.is_valid());
  20438. server_thread.join();
  20439. }
  20440. #ifndef _WIN32
  20441. // As above for the body of a streamed request: a send() cut short by the write
  20442. // timeout must not leave the rest of the body unsent.
  20443. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20444. signal(SIGPIPE, SIG_IGN);
  20445. Server svr;
  20446. svr.set_socket_options([](socket_t sock) {
  20447. int size = 8192;
  20448. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20449. reinterpret_cast<const char *>(&size), sizeof(size));
  20450. });
  20451. svr.Post("/size", [](const Request &, Response &res,
  20452. const ContentReader &content_reader) {
  20453. // Outlast the client's write timeout before reading the body.
  20454. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20455. size_t received = 0;
  20456. content_reader([&](const char *, size_t len) {
  20457. received += len;
  20458. return true;
  20459. });
  20460. res.set_content(std::to_string(received), "text/plain");
  20461. });
  20462. auto port = svr.bind_to_any_port(HOST);
  20463. std::thread t([&]() { svr.listen_after_bind(); });
  20464. auto se = detail::scope_exit([&] {
  20465. svr.stop();
  20466. t.join();
  20467. });
  20468. svr.wait_until_ready();
  20469. Client cli(HOST, port);
  20470. cli.set_write_timeout(0, 500000);
  20471. cli.set_socket_options([](socket_t sock) {
  20472. int size = 8192;
  20473. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20474. reinterpret_cast<const char *>(&size), sizeof(size));
  20475. });
  20476. const std::string body(4 * 1024 * 1024, 'A');
  20477. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20478. "application/octet-stream");
  20479. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20480. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20481. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20482. }
  20483. #endif
  20484. // Serves `response` to the single request `fn` makes with a fresh client.
  20485. template <typename Fn>
  20486. static void with_single_response(const std::string &response, Fn fn) {
  20487. #ifndef _WIN32
  20488. signal(SIGPIPE, SIG_IGN);
  20489. #endif
  20490. std::promise<int> port_promise;
  20491. auto port_future = port_promise.get_future();
  20492. auto server_thread = serve_single_response(port_promise, response);
  20493. auto se = detail::scope_exit([&] { server_thread.join(); });
  20494. auto port = port_future.get();
  20495. ASSERT_GT(port, 0);
  20496. Client cli("127.0.0.1", port);
  20497. fn(cli);
  20498. }
  20499. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20500. // too, also in a build without the decoder for the advertised coding.
  20501. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20502. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20503. const auto response = "HTTP/1.1 200 OK\r\n"
  20504. "Content-Encoding: gzip\r\n"
  20505. "Content-Length: " +
  20506. std::to_string(gzipped.size()) +
  20507. "\r\n"
  20508. "Connection: close\r\n\r\n" +
  20509. gzipped;
  20510. with_single_response(response, [&](Client &cli) {
  20511. cli.set_decompress(false);
  20512. auto handle = cli.open_stream("GET", "/");
  20513. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20514. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20515. EXPECT_EQ(gzipped, read_all(handle));
  20516. EXPECT_FALSE(handle.has_read_error());
  20517. });
  20518. with_single_response(response, [&](Client &cli) {
  20519. cli.set_decompress(false);
  20520. auto res = stream::Get(cli, "/", 7);
  20521. ASSERT_TRUE(res) << to_string(res.error());
  20522. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20523. EXPECT_EQ(gzipped, res.read_all());
  20524. EXPECT_FALSE(res.has_read_error());
  20525. });
  20526. }
  20527. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20528. // Neither Content-Length nor chunked: the body ends at the close
  20529. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20530. "Connection: close\r\n"
  20531. "\r\n"
  20532. "hello";
  20533. with_single_response(close_delimited, [](Client &cli) {
  20534. auto handle = cli.open_stream("GET", "/");
  20535. ASSERT_TRUE(handle.is_valid());
  20536. EXPECT_EQ("hello", read_all(handle));
  20537. EXPECT_FALSE(handle.has_read_error());
  20538. });
  20539. // A close before the end of the Content-Length is still an error
  20540. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20541. "Content-Length: 10\r\n"
  20542. "\r\n"
  20543. "hello";
  20544. with_single_response(short_content_length, [](Client &cli) {
  20545. auto handle = cli.open_stream("GET", "/");
  20546. ASSERT_TRUE(handle.is_valid());
  20547. read_all(handle);
  20548. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20549. });
  20550. // So is a close before the last chunk
  20551. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20552. "Transfer-Encoding: chunked\r\n"
  20553. "\r\n"
  20554. "5\r\nhello\r\n";
  20555. with_single_response(short_chunked, [](Client &cli) {
  20556. auto handle = cli.open_stream("GET", "/");
  20557. ASSERT_TRUE(handle.is_valid());
  20558. read_all(handle);
  20559. EXPECT_TRUE(handle.has_read_error());
  20560. });
  20561. }
  20562. #ifdef CPPHTTPLIB_SSL_ENABLED
  20563. // Serves `response` to one request, then closes with or without a close_notify
  20564. template <typename Fn>
  20565. static void with_single_tls_response(const std::string &response,
  20566. bool close_notify, Fn fn) {
  20567. #ifndef _WIN32
  20568. signal(SIGPIPE, SIG_IGN);
  20569. #endif
  20570. std::promise<int> port_promise;
  20571. auto port_future = port_promise.get_future();
  20572. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20573. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20574. default_socket_options(srv);
  20575. sockaddr_in addr{};
  20576. addr.sin_family = AF_INET;
  20577. addr.sin_port = htons(0);
  20578. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20579. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20580. ::listen(srv, 1) != 0) {
  20581. port_promise.set_value(-1);
  20582. detail::close_socket(srv);
  20583. return;
  20584. }
  20585. socklen_t addr_len = sizeof(addr);
  20586. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20587. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20588. auto cli = ::accept(srv, nullptr, nullptr);
  20589. if (cli != INVALID_SOCKET) {
  20590. auto ctx = tls::create_server_context();
  20591. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20592. nullptr);
  20593. auto session = tls::create_session(ctx, cli);
  20594. tls::TlsError err;
  20595. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20596. // The request head first, so that closing the socket sends a FIN
  20597. // rather than an RST for the unread bytes.
  20598. std::string req;
  20599. char buf[256];
  20600. while (req.find("\r\n\r\n") == std::string::npos) {
  20601. auto n = tls::read(session, buf, sizeof(buf), err);
  20602. if (n <= 0) { break; }
  20603. req.append(buf, static_cast<size_t>(n));
  20604. }
  20605. size_t sent = 0;
  20606. while (sent < response.size()) {
  20607. auto n = tls::write(session, response.data() + sent,
  20608. response.size() - sent, err);
  20609. if (n <= 0) { break; }
  20610. sent += static_cast<size_t>(n);
  20611. }
  20612. if (close_notify) { tls::shutdown(session, true); }
  20613. }
  20614. tls::free_session(session);
  20615. detail::close_socket(cli);
  20616. tls::free_context(ctx);
  20617. }
  20618. detail::close_socket(srv);
  20619. });
  20620. auto se = detail::scope_exit([&] { server_thread.join(); });
  20621. auto port = port_future.get();
  20622. ASSERT_GT(port, 0);
  20623. SSLClient cli("127.0.0.1", port);
  20624. cli.enable_server_certificate_verification(false);
  20625. fn(cli);
  20626. }
  20627. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20628. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20629. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20630. "Connection: close\r\n"
  20631. "\r\n"
  20632. "hello";
  20633. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20634. auto res = cli.Get("/");
  20635. ASSERT_TRUE(res) << to_string(res.error());
  20636. EXPECT_EQ("hello", res->body);
  20637. });
  20638. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20639. auto res = cli.Get("/");
  20640. ASSERT_FALSE(res);
  20641. EXPECT_EQ(Error::Read, res.error());
  20642. });
  20643. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20644. auto handle = cli.open_stream("GET", "/");
  20645. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20646. read_all(handle);
  20647. EXPECT_TRUE(handle.has_read_error());
  20648. });
  20649. // A framed body ends where its framing says, with or without the alert
  20650. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20651. "Content-Length: 5\r\n"
  20652. "Connection: close\r\n"
  20653. "\r\n"
  20654. "hello";
  20655. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20656. auto res = cli.Get("/");
  20657. ASSERT_TRUE(res) << to_string(res.error());
  20658. EXPECT_EQ("hello", res->body);
  20659. });
  20660. }
  20661. #endif
  20662. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20663. const char *responses[] = {
  20664. "HTTP/1.1 103 Early Hints\r\n"
  20665. "Link: </style.css>; rel=preload\r\n"
  20666. "\r\n"
  20667. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20668. "HTTP/1.1 100 Continue\r\n"
  20669. "X-Note: interim\r\n"
  20670. "\r\n"
  20671. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20672. };
  20673. for (auto response : responses) {
  20674. with_single_response(response, [](Client &cli) {
  20675. auto res = cli.Get("/");
  20676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20677. EXPECT_EQ(StatusCode::OK_200, res->status);
  20678. EXPECT_EQ("ok", res->body);
  20679. });
  20680. }
  20681. }
  20682. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20683. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20684. const std::string final_response =
  20685. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20686. std::string interims;
  20687. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20688. interims += interim;
  20689. }
  20690. with_single_response(interims + final_response, [](Client &cli) {
  20691. auto res = cli.Get("/");
  20692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20693. EXPECT_EQ("ok", res->body);
  20694. });
  20695. with_single_response(interims + interim + final_response, [](Client &cli) {
  20696. auto res = cli.Get("/");
  20697. ASSERT_FALSE(res);
  20698. EXPECT_EQ(Error::Read, res.error());
  20699. });
  20700. }
  20701. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20702. #ifndef _WIN32
  20703. signal(SIGPIPE, SIG_IGN);
  20704. #endif
  20705. // The server answers the head without asking for the body. Bytes it then
  20706. // reads on the connection would be taken for the body the request declared.
  20707. auto closed_by_client = false;
  20708. std::promise<int> port_promise;
  20709. auto server_thread = serve_single_response(
  20710. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20711. [&](socket_t sock) {
  20712. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20713. char buf[256];
  20714. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20715. });
  20716. Client cli("127.0.0.1", port_promise.get_future().get());
  20717. cli.set_keep_alive(true);
  20718. cli.set_read_timeout(1, 0);
  20719. // Long enough for the client to send Expect: 100-continue.
  20720. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20722. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20723. cli.Get("/second");
  20724. server_thread.join();
  20725. EXPECT_TRUE(closed_by_client);
  20726. }
  20727. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20728. // Long enough for the client to send Expect: 100-continue
  20729. with_single_response(
  20730. "HTTP/1.1 103 Early Hints\r\n"
  20731. "Link: </style.css>; rel=preload\r\n"
  20732. "\r\n"
  20733. "HTTP/1.1 401 Unauthorized\r\n"
  20734. "Content-Length: 0\r\n\r\n",
  20735. [](Client &cli) {
  20736. cli.set_read_timeout(2, 0);
  20737. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20739. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20740. });
  20741. }
  20742. #ifdef CPPHTTPLIB_SSL_ENABLED
  20743. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20744. #ifndef _WIN32
  20745. signal(SIGPIPE, SIG_IGN);
  20746. #endif
  20747. auto reused = false;
  20748. std::promise<int> port_promise;
  20749. auto server_thread = serve_single_response(
  20750. port_promise,
  20751. "HTTP/1.1 401 Unauthorized\r\n"
  20752. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20753. "Content-Length: 0\r\n\r\n",
  20754. [&](socket_t sock) {
  20755. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20756. char buf[256];
  20757. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20758. });
  20759. Client cli("127.0.0.1", port_promise.get_future().get());
  20760. cli.set_keep_alive(true);
  20761. cli.set_digest_auth("user", "pass");
  20762. cli.set_read_timeout(1, 0);
  20763. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20764. server_thread.join();
  20765. EXPECT_FALSE(reused);
  20766. }
  20767. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20768. // Any other answer to CONNECT would read as the origin's response.
  20769. struct {
  20770. const char *response;
  20771. bool passed_on;
  20772. } cases[] = {
  20773. {"HTTP/1.1 201 Created\r\n"
  20774. "Set-Cookie: session=from-proxy\r\n"
  20775. "Content-Length: 0\r\n\r\n",
  20776. false},
  20777. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20778. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20779. "Content-Length: 0\r\n\r\n",
  20780. true},
  20781. };
  20782. for (const auto &c : cases) {
  20783. std::promise<int> port_promise;
  20784. auto server_thread = serve_single_response(port_promise, c.response);
  20785. SSLClient cli("example.com", 443);
  20786. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20787. auto res = cli.Get("/");
  20788. server_thread.join();
  20789. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20790. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20791. if (res) {
  20792. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20793. }
  20794. }
  20795. }
  20796. #endif
  20797. // Records the client's error logger calls as "error METHOD path", or
  20798. // "error null" for a call without a request
  20799. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20800. return [&log](const Error &err, const Request *req) {
  20801. log.push_back(to_string(err) + " " +
  20802. (req ? req->method + " " + req->path : "null"));
  20803. };
  20804. }
  20805. // A failed request is reported once, with the request the caller made
  20806. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20807. Server svr;
  20808. svr.Get("/big", [](const Request &, Response &res) {
  20809. res.set_content(std::string(100000, 'b'), "text/plain");
  20810. });
  20811. auto port = svr.bind_to_any_port(HOST);
  20812. std::thread t([&]() { svr.listen_after_bind(); });
  20813. auto se = detail::scope_exit([&] {
  20814. svr.stop();
  20815. t.join();
  20816. });
  20817. svr.wait_until_ready();
  20818. Client cli(HOST, port);
  20819. std::vector<std::string> log;
  20820. cli.set_error_logger(record_errors(log));
  20821. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20822. cli.Get("/big", [](const char *, size_t) { return false; });
  20823. EXPECT_EQ(expected, log);
  20824. log.clear();
  20825. cli.Get("/big", [](size_t, size_t) { return false; });
  20826. EXPECT_EQ(expected, log);
  20827. }
  20828. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20829. // Fails while the body is read
  20830. auto broken = [](const Request &, Response &res) {
  20831. res.set_content_provider(10, "text/plain",
  20832. [](size_t, size_t, DataSink &) { return false; });
  20833. };
  20834. Server other;
  20835. other.Get("/broken", broken);
  20836. auto other_port = other.bind_to_any_port(HOST);
  20837. std::thread other_t([&]() { other.listen_after_bind(); });
  20838. auto other_se = detail::scope_exit([&] {
  20839. other.stop();
  20840. other_t.join();
  20841. });
  20842. other.wait_until_ready();
  20843. Server svr;
  20844. svr.Get("/broken", broken);
  20845. svr.Get("/same-origin",
  20846. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20847. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20848. res.set_redirect("http://" + std::string(HOST) + ":" +
  20849. std::to_string(other_port) + "/broken");
  20850. });
  20851. auto port = svr.bind_to_any_port(HOST);
  20852. std::thread t([&]() { svr.listen_after_bind(); });
  20853. auto se = detail::scope_exit([&] {
  20854. svr.stop();
  20855. t.join();
  20856. });
  20857. svr.wait_until_ready();
  20858. Client cli(HOST, port);
  20859. cli.set_follow_location(true);
  20860. std::vector<std::string> log;
  20861. cli.set_error_logger(record_errors(log));
  20862. for (auto path : {"/same-origin", "/cross-origin"}) {
  20863. log.clear();
  20864. auto res = cli.Get(path);
  20865. ASSERT_FALSE(res);
  20866. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20867. log);
  20868. }
  20869. }
  20870. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20871. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20872. std::vector<std::string> log;
  20873. cli.set_error_logger(record_errors(log));
  20874. auto handle = cli.open_stream("GET", "/x");
  20875. EXPECT_FALSE(handle.is_valid());
  20876. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20877. log);
  20878. });
  20879. }
  20880. #ifdef CPPHTTPLIB_SSL_ENABLED
  20881. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20882. // Not a TLS server, so the handshake fails. It waits for a request line in
  20883. // the handshake bytes, so a short read timeout lets it close quickly.
  20884. Server svr;
  20885. svr.set_read_timeout(0, 100000);
  20886. svr.Get("/x", [](const Request &, Response &res) {
  20887. res.set_content("x", "text/plain");
  20888. });
  20889. auto port = svr.bind_to_any_port(HOST);
  20890. std::thread t([&]() { svr.listen_after_bind(); });
  20891. auto se = detail::scope_exit([&] {
  20892. svr.stop();
  20893. t.join();
  20894. });
  20895. svr.wait_until_ready();
  20896. std::vector<std::string> log;
  20897. SSLClient cli(HOST, port);
  20898. cli.enable_server_certificate_verification(false);
  20899. cli.set_error_logger(record_errors(log));
  20900. auto res = cli.Get("/x");
  20901. ASSERT_FALSE(res);
  20902. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20903. log.clear();
  20904. auto handle = cli.open_stream("GET", "/x");
  20905. EXPECT_FALSE(handle.is_valid());
  20906. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20907. log.clear();
  20908. SSLClient no_ca(HOST, port);
  20909. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20910. no_ca.set_error_logger(record_errors(log));
  20911. res = no_ca.Get("/x");
  20912. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20913. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20914. }
  20915. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20916. #ifndef _WIN32
  20917. signal(SIGPIPE, SIG_IGN);
  20918. #endif
  20919. // Refused, answered with a challenge, or closed without an answer
  20920. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20921. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20922. "Content-Length: 0\r\n\r\n",
  20923. ""}) {
  20924. std::promise<int> port_promise;
  20925. auto server_thread = serve_single_response(port_promise, response);
  20926. SSLClient cli("example.com", 443);
  20927. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20928. std::vector<std::string> log;
  20929. cli.set_error_logger(record_errors(log));
  20930. auto res = cli.Get("/");
  20931. server_thread.join();
  20932. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20933. << response;
  20934. }
  20935. }
  20936. #endif
  20937. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20938. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20939. // the chunked coding and drop Content-Length, so a front-end that trusts
  20940. // Content-Length would disagree about where the body ends (response
  20941. // smuggling). The client must reject such a response.
  20942. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20943. for (const char *te : {"chunked", "gzip, chunked"}) {
  20944. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20945. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20946. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20947. "5\r\nhello\r\n0\r\n\r\n";
  20948. with_single_response(response, [&](Client &cli) {
  20949. auto res = cli.Get("/");
  20950. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20951. EXPECT_EQ(Error::Read, res.error()) << te;
  20952. });
  20953. with_single_response(response, [&](Client &cli) {
  20954. auto handle = cli.open_stream("GET", "/");
  20955. EXPECT_FALSE(handle.is_valid()) << te;
  20956. EXPECT_EQ(Error::Read, handle.error) << te;
  20957. });
  20958. }
  20959. }
  20960. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20961. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20962. // closing the connection (unlike a request, which must be rejected).
  20963. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20964. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20965. "Transfer-Encoding: chunked\r\n"
  20966. "Connection: close\r\n"
  20967. "\r\n"
  20968. "5\r\nhello\r\n0\r\n\r\n",
  20969. "HTTP/1.1 200 OK\r\n"
  20970. "Transfer-Encoding: gzip\r\n"
  20971. "Connection: close\r\n"
  20972. "\r\n"
  20973. "hello"}) {
  20974. with_single_response(response, [&](Client &cli) {
  20975. auto res = cli.Get("/");
  20976. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20977. EXPECT_EQ("hello", res->body);
  20978. });
  20979. with_single_response(response, [&](Client &cli) {
  20980. auto handle = cli.open_stream("GET", "/");
  20981. ASSERT_TRUE(handle.is_valid()) << response;
  20982. EXPECT_EQ("hello", read_all(handle));
  20983. });
  20984. }
  20985. }
  20986. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20987. // framing headers describe nothing to read and must not be rejected.
  20988. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20989. const std::string framing = "Content-Length: 5\r\n"
  20990. "Transfer-Encoding: chunked\r\n"
  20991. "Connection: close\r\n"
  20992. "\r\n";
  20993. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20994. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20995. });
  20996. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20997. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20998. });
  20999. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21000. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21001. with_single_response(response, [&](Client &cli) {
  21002. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21003. });
  21004. with_single_response(response, [&](Client &cli) {
  21005. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21006. });
  21007. }
  21008. }
  21009. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21010. // header section, so a stream opened on one has nothing to read, whatever
  21011. // framing or coding headers it carries.
  21012. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21013. struct Case {
  21014. const char *method;
  21015. const char *status;
  21016. };
  21017. // A reader of the declared body reports an early close when nothing
  21018. // follows, and hands back what does.
  21019. struct Framing {
  21020. const char *headers;
  21021. const char *after;
  21022. };
  21023. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21024. Case{"GET", "304 Not Modified"}}) {
  21025. for (const auto &f :
  21026. {Framing{"Content-Length: 5\r\n", ""},
  21027. Framing{"Content-Length: 5\r\n", "hello"},
  21028. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21029. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21030. // Not decoded, so a build without Brotli opens it too
  21031. Framing{"Content-Encoding: br\r\n", ""}}) {
  21032. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21033. "Connection: close\r\n"
  21034. "\r\n" +
  21035. f.after;
  21036. with_single_response(response, [&](Client &cli) {
  21037. auto handle = cli.open_stream(c.method, "/");
  21038. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21039. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21040. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21041. });
  21042. }
  21043. }
  21044. }
  21045. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21046. // response, is faulty framing, so the connection is not reused after it.
  21047. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21048. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21049. "Content-Length: 0\r\n"
  21050. "Transfer-Encoding: chunked\r\n"
  21051. "\r\n"
  21052. "5\r\nhello\r\n0\r\n\r\n",
  21053. "HTTP/1.0 200 Connection established\r\n"
  21054. "Connection: keep-alive\r\n"
  21055. "Transfer-Encoding: chunked\r\n"
  21056. "\r\n"
  21057. "5\r\nhello\r\n0\r\n\r\n"}) {
  21058. with_single_response(response, [&](Client &cli) {
  21059. cli.set_keep_alive(true);
  21060. auto res = cli.Get("/");
  21061. ASSERT_TRUE(res) << response;
  21062. EXPECT_EQ("hello", res->body);
  21063. EXPECT_FALSE(cli.is_socket_open()) << response;
  21064. });
  21065. }
  21066. }
  21067. // A payload max length of 0 means no limit, however the body is framed.
  21068. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21069. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21070. "Transfer-Encoding: chunked\r\n"
  21071. "\r\n"
  21072. "5\r\nhello\r\n0\r\n\r\n",
  21073. "HTTP/1.1 200 OK\r\n"
  21074. "Connection: close\r\n"
  21075. "\r\n"
  21076. "hello"}) {
  21077. with_single_response(response, [&](Client &cli) {
  21078. cli.set_payload_max_length(0);
  21079. auto res = cli.Get("/");
  21080. ASSERT_TRUE(res) << response;
  21081. EXPECT_EQ("hello", res->body) << response;
  21082. });
  21083. }
  21084. }
  21085. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21086. Server svr;
  21087. svr.set_payload_max_length(0);
  21088. svr.Post("/echo", [](const Request &req, Response &res) {
  21089. res.set_content(req.body, "text/plain");
  21090. });
  21091. auto port = svr.bind_to_any_port(HOST);
  21092. thread t = thread([&] { svr.listen_after_bind(); });
  21093. auto se = detail::scope_exit([&] {
  21094. svr.stop();
  21095. t.join();
  21096. ASSERT_FALSE(svr.is_running());
  21097. });
  21098. svr.wait_until_ready();
  21099. Client cli(HOST, port);
  21100. auto res = cli.Post(
  21101. "/echo",
  21102. [](size_t /*offset*/, DataSink &sink) {
  21103. sink.write("hello", 5);
  21104. sink.done();
  21105. return true;
  21106. },
  21107. "text/plain");
  21108. ASSERT_TRUE(res);
  21109. EXPECT_EQ(StatusCode::OK_200, res->status);
  21110. EXPECT_EQ("hello", res->body);
  21111. }
  21112. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21113. TEST_F(OpenStreamTest, Gzip) {
  21114. Client cli("127.0.0.1", port_);
  21115. auto handle = cli.open_stream("GET", "/compressible", {},
  21116. {{"Accept-Encoding", "gzip"}});
  21117. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21118. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21119. }
  21120. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21121. Client cli("127.0.0.1", port_);
  21122. auto handle =
  21123. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21124. {{"Accept-Encoding", "gzip"}});
  21125. ASSERT_TRUE(handle.is_valid());
  21126. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21127. EXPECT_EQ("123456789", read_all(handle));
  21128. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21129. }
  21130. #endif
  21131. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21132. TEST_F(OpenStreamTest, Brotli) {
  21133. Client cli("127.0.0.1", port_);
  21134. auto handle =
  21135. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21136. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21137. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21138. }
  21139. #endif
  21140. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21141. TEST_F(OpenStreamTest, Zstd) {
  21142. Client cli("127.0.0.1", port_);
  21143. auto handle = cli.open_stream("GET", "/compressible", {},
  21144. {{"Accept-Encoding", "zstd"}});
  21145. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21146. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21147. }
  21148. #endif
  21149. #ifdef CPPHTTPLIB_SSL_ENABLED
  21150. class SSLOpenStreamTest : public ::testing::Test {
  21151. protected:
  21152. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21153. void SetUp() override {
  21154. svr_.Get("/hello", [](const Request &, Response &res) {
  21155. res.set_content("Hello SSL World!", "text/plain");
  21156. });
  21157. svr_.Get("/chunked", [](const Request &, Response &res) {
  21158. res.set_chunked_content_provider("text/plain",
  21159. [](size_t offset, DataSink &sink) {
  21160. if (offset < 15) {
  21161. sink.write("chunk", 5);
  21162. return true;
  21163. }
  21164. sink.done();
  21165. return true;
  21166. });
  21167. });
  21168. svr_.Post("/echo", [](const Request &req, Response &res) {
  21169. res.set_content(req.body, req.get_header_value("Content-Type"));
  21170. });
  21171. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21172. std::string body = req.body;
  21173. res.set_chunked_content_provider(
  21174. "text/plain", [body](size_t offset, DataSink &sink) {
  21175. if (offset < body.size()) {
  21176. sink.write(body.data() + offset, body.size() - offset);
  21177. }
  21178. sink.done();
  21179. return true;
  21180. });
  21181. });
  21182. port_ = svr_.bind_to_any_port("127.0.0.1");
  21183. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21184. svr_.wait_until_ready();
  21185. }
  21186. void TearDown() override {
  21187. svr_.stop();
  21188. if (thread_.joinable()) thread_.join();
  21189. }
  21190. SSLServer svr_;
  21191. std::thread thread_;
  21192. int port_ = 0;
  21193. };
  21194. TEST_F(SSLOpenStreamTest, Basic) {
  21195. SSLClient cli("127.0.0.1", port_);
  21196. cli.enable_server_certificate_verification(false);
  21197. auto handle = cli.open_stream("GET", "/hello");
  21198. ASSERT_TRUE(handle.is_valid());
  21199. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21200. }
  21201. TEST_F(SSLOpenStreamTest, Chunked) {
  21202. SSLClient cli("127.0.0.1", port_);
  21203. cli.enable_server_certificate_verification(false);
  21204. auto handle = cli.open_stream("GET", "/chunked");
  21205. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21206. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21207. "Transfer-Encoding") == "chunked");
  21208. auto body = read_all(handle);
  21209. EXPECT_EQ("chunkchunkchunk", body);
  21210. }
  21211. TEST_F(SSLOpenStreamTest, Post) {
  21212. SSLClient cli("127.0.0.1", port_);
  21213. cli.enable_server_certificate_verification(false);
  21214. auto handle =
  21215. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21216. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21217. EXPECT_EQ(200, handle.response->status);
  21218. auto body = read_all(handle);
  21219. EXPECT_EQ("Hello SSL POST", body);
  21220. }
  21221. TEST_F(SSLOpenStreamTest, PostChunked) {
  21222. SSLClient cli("127.0.0.1", port_);
  21223. cli.enable_server_certificate_verification(false);
  21224. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21225. "Chunked SSL Data", "text/plain");
  21226. ASSERT_TRUE(handle.is_valid());
  21227. EXPECT_EQ(200, handle.response->status);
  21228. auto body = read_all(handle);
  21229. EXPECT_EQ("Chunked SSL Data", body);
  21230. }
  21231. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21232. // Content-Length is terminated by the server closing the connection. When the
  21233. // SSL peer sends a close_notify after the body, the client must treat it as a
  21234. // clean EOF and return a successful response rather than an error.
  21235. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21237. ASSERT_TRUE(svr.is_valid());
  21238. svr.set_keep_alive_max_count(1);
  21239. const std::string expected_body = "Hello from connection-close response!";
  21240. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21241. res.set_content_provider("text/plain",
  21242. [&](size_t offset, DataSink &sink) -> bool {
  21243. if (offset < expected_body.size()) {
  21244. sink.write(expected_body.data() + offset,
  21245. expected_body.size() - offset);
  21246. }
  21247. sink.done();
  21248. return true;
  21249. });
  21250. });
  21251. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21252. auto se = detail::scope_exit([&] {
  21253. svr.stop();
  21254. listen_thread.join();
  21255. ASSERT_FALSE(svr.is_running());
  21256. });
  21257. svr.wait_until_ready();
  21258. SSLClient cli(HOST, PORT);
  21259. cli.enable_server_certificate_verification(false);
  21260. auto res = cli.Get("/no-content-length");
  21261. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21262. EXPECT_EQ(StatusCode::OK_200, res->status);
  21263. EXPECT_EQ(expected_body, res->body);
  21264. }
  21265. // Without Content-Length, the full buffer size reaches tls::read().
  21266. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21267. if (sizeof(size_t) <= sizeof(int)) {
  21268. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21269. }
  21270. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21271. ASSERT_TRUE(svr.is_valid());
  21272. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21273. res.set_content_provider("text/plain",
  21274. [&](size_t offset, DataSink &sink) -> bool {
  21275. if (offset == 0) { sink.write("Hello", 5); }
  21276. sink.done();
  21277. return true;
  21278. });
  21279. });
  21280. auto port = svr.bind_to_any_port(HOST);
  21281. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21282. auto se = detail::scope_exit([&] {
  21283. svr.stop();
  21284. listen_thread.join();
  21285. });
  21286. svr.wait_until_ready();
  21287. SSLClient cli(HOST, port);
  21288. cli.enable_server_certificate_verification(false);
  21289. auto handle = cli.open_stream("GET", "/no-content-length");
  21290. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21291. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21292. std::unique_ptr<char[]> buf(new char[len]);
  21293. std::string body;
  21294. ssize_t n;
  21295. while ((n = handle.read(buf.get(), len)) > 0) {
  21296. body.append(buf.get(), static_cast<size_t>(n));
  21297. }
  21298. EXPECT_EQ(0, n);
  21299. EXPECT_EQ("Hello", body);
  21300. }
  21301. #endif // CPPHTTPLIB_SSL_ENABLED
  21302. //==============================================================================
  21303. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21304. // results for various scenarios.
  21305. //==============================================================================
  21306. TEST(ParityTest, GetVsOpenStream) {
  21307. Server svr;
  21308. const std::string path = "/parity";
  21309. const std::string content = "Parity test content: hello world";
  21310. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21311. res.set_content(content, "text/plain");
  21312. });
  21313. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21314. auto se = detail::scope_exit([&] {
  21315. svr.stop();
  21316. t.join();
  21317. ASSERT_FALSE(svr.is_running());
  21318. });
  21319. svr.wait_until_ready();
  21320. Client cli(HOST, PORT);
  21321. // Non-stream path
  21322. auto r1 = cli.Get(path);
  21323. ASSERT_TRUE(r1);
  21324. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21325. // Stream path
  21326. auto h = cli.open_stream("GET", path);
  21327. ASSERT_TRUE(h.is_valid());
  21328. EXPECT_EQ(r1->body, read_all(h));
  21329. }
  21330. // Helper to compress data with provided compressor type T
  21331. template <typename Compressor>
  21332. static std::string compress_payload_for_parity(const std::string &in) {
  21333. std::string out;
  21334. Compressor compressor;
  21335. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21336. [&](const char *data, size_t n) {
  21337. out.append(data, n);
  21338. return true;
  21339. });
  21340. EXPECT_TRUE(ok);
  21341. return out;
  21342. }
  21343. // Helper function for compression parity tests
  21344. template <typename Compressor>
  21345. static void test_compression_parity(const std::string &original,
  21346. const std::string &path,
  21347. const std::string &encoding) {
  21348. const std::string compressed =
  21349. compress_payload_for_parity<Compressor>(original);
  21350. Server svr;
  21351. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21352. res.set_content(compressed, "application/octet-stream");
  21353. res.set_header("Content-Encoding", encoding);
  21354. });
  21355. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21356. auto se = detail::scope_exit([&] {
  21357. svr.stop();
  21358. t.join();
  21359. ASSERT_FALSE(svr.is_running());
  21360. });
  21361. svr.wait_until_ready();
  21362. Client cli(HOST, PORT);
  21363. // Non-streaming
  21364. {
  21365. auto res = cli.Get(path);
  21366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21367. EXPECT_EQ(StatusCode::OK_200, res->status);
  21368. EXPECT_EQ(original, res->body);
  21369. }
  21370. // Streaming
  21371. {
  21372. auto h = cli.open_stream("GET", path);
  21373. ASSERT_TRUE(h.is_valid());
  21374. EXPECT_EQ(original, read_all(h));
  21375. }
  21376. }
  21377. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21378. TEST(ParityTest, Gzip) {
  21379. test_compression_parity<detail::gzip_compressor>(
  21380. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21381. }
  21382. #endif
  21383. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21384. TEST(ParityTest, Brotli) {
  21385. test_compression_parity<detail::brotli_compressor>(
  21386. "Hello, brotli parity test payload", "/parity-br", "br");
  21387. }
  21388. #endif
  21389. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21390. TEST(ParityTest, Zstd) {
  21391. test_compression_parity<detail::zstd_compressor>(
  21392. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21393. }
  21394. #endif
  21395. //==============================================================================
  21396. // New Stream API Tests
  21397. //==============================================================================
  21398. inline std::string read_body(httplib::stream::Result &result) {
  21399. std::string body;
  21400. while (result.next()) {
  21401. body.append(result.data(), result.size());
  21402. }
  21403. return body;
  21404. }
  21405. TEST(ClientConnectionTest, Basic) {
  21406. httplib::ClientConnection conn;
  21407. EXPECT_FALSE(conn.is_open());
  21408. conn.sock = 1;
  21409. EXPECT_TRUE(conn.is_open());
  21410. httplib::ClientConnection conn2(std::move(conn));
  21411. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21412. conn2.sock = INVALID_SOCKET;
  21413. }
  21414. // Unified test server for all stream::* tests
  21415. class StreamApiTest : public ::testing::Test {
  21416. protected:
  21417. void SetUp() override {
  21418. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21419. res.set_content("Hello World!", "text/plain");
  21420. });
  21421. svr_.Get("/echo-params",
  21422. [](const httplib::Request &req, httplib::Response &res) {
  21423. std::string r;
  21424. for (const auto &p : req.params) {
  21425. if (!r.empty()) r += "&";
  21426. r += p.first + "=" + p.second;
  21427. }
  21428. res.set_content(r, "text/plain");
  21429. });
  21430. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21431. res.set_content(req.body, req.get_header_value("Content-Type"));
  21432. });
  21433. svr_.Post("/echo-headers",
  21434. [](const httplib::Request &req, httplib::Response &res) {
  21435. std::string r;
  21436. for (const auto &h : req.headers)
  21437. r += h.first + ": " + h.second + "\n";
  21438. res.set_content(r, "text/plain");
  21439. });
  21440. svr_.Post("/echo-params",
  21441. [](const httplib::Request &req, httplib::Response &res) {
  21442. std::string r = "params:";
  21443. for (const auto &p : req.params)
  21444. r += p.first + "=" + p.second + ";";
  21445. res.set_content(r + " body:" + req.body, "text/plain");
  21446. });
  21447. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21448. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21449. });
  21450. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21451. res.set_content("PUT:" + req.body, "text/plain");
  21452. });
  21453. svr_.Patch("/echo",
  21454. [](const httplib::Request &req, httplib::Response &res) {
  21455. res.set_content("PATCH:" + req.body, "text/plain");
  21456. });
  21457. svr_.Delete(
  21458. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21459. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21460. "text/plain");
  21461. });
  21462. svr_.Get("/head-test",
  21463. [](const httplib::Request &, httplib::Response &res) {
  21464. res.set_content("body for HEAD", "text/plain");
  21465. });
  21466. svr_.Options("/options",
  21467. [](const httplib::Request &, httplib::Response &res) {
  21468. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21469. });
  21470. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21471. svr_.wait_until_ready();
  21472. }
  21473. void TearDown() override {
  21474. svr_.stop();
  21475. if (thread_.joinable()) thread_.join();
  21476. }
  21477. httplib::Server svr_;
  21478. std::thread thread_;
  21479. };
  21480. // stream::Get tests
  21481. TEST_F(StreamApiTest, GetBasic) {
  21482. httplib::Client cli(HOST, PORT);
  21483. auto result = httplib::stream::Get(cli, "/hello");
  21484. ASSERT_TRUE(result.is_valid());
  21485. EXPECT_EQ(200, result.status());
  21486. EXPECT_EQ("Hello World!", read_body(result));
  21487. }
  21488. TEST_F(StreamApiTest, GetWithParams) {
  21489. httplib::Client cli(HOST, PORT);
  21490. httplib::Params params{{"foo", "bar"}};
  21491. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21492. ASSERT_TRUE(result.is_valid());
  21493. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21494. }
  21495. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21496. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21497. httplib::Client cli(HOST, PORT);
  21498. cli.set_payload_max_length(0);
  21499. auto result = httplib::stream::Get(cli, "/hello");
  21500. ASSERT_TRUE(result.is_valid());
  21501. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21502. EXPECT_EQ("Hello World!", read_body(result));
  21503. }
  21504. #endif
  21505. TEST_F(StreamApiTest, GetConnectionError) {
  21506. httplib::Client cli(HOST, 9999);
  21507. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21508. }
  21509. TEST_F(StreamApiTest, Get404) {
  21510. httplib::Client cli(HOST, PORT);
  21511. auto result = httplib::stream::Get(cli, "/nonexistent");
  21512. EXPECT_TRUE(result.is_valid());
  21513. EXPECT_EQ(404, result.status());
  21514. }
  21515. // stream::Post tests
  21516. TEST_F(StreamApiTest, PostBasic) {
  21517. httplib::Client cli(HOST, PORT);
  21518. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21519. "application/json");
  21520. ASSERT_TRUE(result.is_valid());
  21521. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21522. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21523. }
  21524. TEST_F(StreamApiTest, PostWithHeaders) {
  21525. httplib::Client cli(HOST, PORT);
  21526. httplib::Headers headers{{"X-Custom", "value"}};
  21527. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21528. "text/plain");
  21529. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21530. }
  21531. TEST_F(StreamApiTest, PostWithParams) {
  21532. httplib::Client cli(HOST, PORT);
  21533. httplib::Params params{{"k", "v"}};
  21534. auto result =
  21535. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21536. auto body = read_body(result);
  21537. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21538. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21539. }
  21540. TEST_F(StreamApiTest, PostLarge) {
  21541. httplib::Client cli(HOST, PORT);
  21542. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21543. size_t total = 0;
  21544. while (result.next()) {
  21545. total += result.size();
  21546. }
  21547. EXPECT_EQ(100u * 1024u, total);
  21548. }
  21549. // stream::Put/Patch tests
  21550. TEST_F(StreamApiTest, PutAndPatch) {
  21551. httplib::Client cli(HOST, PORT);
  21552. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21553. EXPECT_EQ("PUT:test", read_body(put));
  21554. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21555. EXPECT_EQ("PATCH:test", read_body(patch));
  21556. }
  21557. // stream::Delete tests
  21558. TEST_F(StreamApiTest, Delete) {
  21559. httplib::Client cli(HOST, PORT);
  21560. auto del1 = httplib::stream::Delete(cli, "/resource");
  21561. EXPECT_EQ("Deleted", read_body(del1));
  21562. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21563. EXPECT_EQ("Deleted:data", read_body(del2));
  21564. }
  21565. // stream::Head/Options tests
  21566. TEST_F(StreamApiTest, HeadAndOptions) {
  21567. httplib::Client cli(HOST, PORT);
  21568. auto head = httplib::stream::Head(cli, "/head-test");
  21569. EXPECT_TRUE(head.is_valid());
  21570. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21571. auto opts = httplib::stream::Options(cli, "/options");
  21572. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21573. }
  21574. // SSL stream::* tests
  21575. #ifdef CPPHTTPLIB_SSL_ENABLED
  21576. class SSLStreamApiTest : public ::testing::Test {
  21577. protected:
  21578. void SetUp() override {
  21579. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21580. res.set_content("Hello SSL!", "text/plain");
  21581. });
  21582. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21583. res.set_content(req.body, "text/plain");
  21584. });
  21585. port_ = svr_.bind_to_any_port("127.0.0.1");
  21586. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21587. svr_.wait_until_ready();
  21588. }
  21589. void TearDown() override {
  21590. svr_.stop();
  21591. if (thread_.joinable()) thread_.join();
  21592. }
  21593. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21594. std::thread thread_;
  21595. int port_ = 0;
  21596. };
  21597. TEST_F(SSLStreamApiTest, GetAndPost) {
  21598. httplib::SSLClient cli("127.0.0.1", port_);
  21599. cli.enable_server_certificate_verification(false);
  21600. auto get = httplib::stream::Get(cli, "/hello");
  21601. EXPECT_EQ("Hello SSL!", read_body(get));
  21602. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21603. EXPECT_EQ("test", read_body(post));
  21604. }
  21605. #endif
  21606. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21607. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21608. // BodyReader
  21609. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21610. // Test that read timeout during streaming is detected
  21611. // Use a large content-length response where server delays mid-stream
  21612. Server svr;
  21613. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21614. // Send a large response with delay in the middle
  21615. res.set_content_provider(
  21616. 1000, // content_length
  21617. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21618. if (offset < 100) {
  21619. // Send first 100 bytes immediately
  21620. std::string data(100, 'A');
  21621. sink.write(data.c_str(), data.size());
  21622. return true;
  21623. }
  21624. // Then delay longer than client timeout
  21625. std::this_thread::sleep_for(std::chrono::seconds(3));
  21626. std::string data(900, 'B');
  21627. sink.write(data.c_str(), data.size());
  21628. return true;
  21629. });
  21630. });
  21631. auto port = 8091;
  21632. std::thread t([&]() { svr.listen("localhost", port); });
  21633. svr.wait_until_ready();
  21634. Client cli("localhost", port);
  21635. cli.set_read_timeout(1, 0); // 1 second timeout
  21636. auto handle = cli.open_stream("GET", "/slow-stream");
  21637. ASSERT_TRUE(handle.is_valid());
  21638. char buf[256];
  21639. ssize_t total = 0;
  21640. ssize_t n;
  21641. bool got_error = false;
  21642. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21643. total += n;
  21644. }
  21645. if (n < 0) {
  21646. got_error = true;
  21647. // Should be timeout or read error
  21648. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21649. handle.get_read_error() == Error::Read)
  21650. << "Actual error: " << to_string(handle.get_read_error());
  21651. }
  21652. // Either we got an error, or we got less data than expected
  21653. EXPECT_TRUE(got_error || total < 1000)
  21654. << "Expected timeout but got all " << total << " bytes";
  21655. svr.stop();
  21656. t.join();
  21657. }
  21658. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21659. // Test connection closed detection via BodyReader
  21660. Server svr;
  21661. std::atomic<bool> close_now{false};
  21662. svr.Get("/will-close", [&](const Request &, Response &res) {
  21663. res.set_content_provider(
  21664. 10000, // Large content_length that we won't fully send
  21665. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21666. if (offset < 100) {
  21667. std::string data(100, 'X');
  21668. sink.write(data.c_str(), data.size());
  21669. return true;
  21670. }
  21671. // Wait for signal then abort
  21672. while (!close_now) {
  21673. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21674. }
  21675. return false; // Abort - server will close connection
  21676. });
  21677. });
  21678. auto port = 8092;
  21679. std::thread t([&]() { svr.listen("localhost", port); });
  21680. svr.wait_until_ready();
  21681. Client cli("localhost", port);
  21682. auto handle = cli.open_stream("GET", "/will-close");
  21683. ASSERT_TRUE(handle.is_valid());
  21684. char buf[256];
  21685. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21686. EXPECT_GT(n, 0) << "First read should succeed";
  21687. // Signal server to close
  21688. close_now = true;
  21689. // Keep reading until error or EOF
  21690. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21691. // Keep reading
  21692. }
  21693. // Should get an error since content_length wasn't satisfied
  21694. if (n < 0) {
  21695. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21696. handle.get_read_error() == Error::Read)
  21697. << "Actual error: " << to_string(handle.get_read_error());
  21698. }
  21699. svr.stop();
  21700. t.join();
  21701. }
  21702. #ifdef CPPHTTPLIB_SSL_ENABLED
  21703. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21704. // Test that read timeout during SSL streaming is detected
  21705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21706. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21707. res.set_content_provider(
  21708. 1000, "text/plain",
  21709. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21710. if (offset < 100) {
  21711. std::string data(100, 'A');
  21712. sink.write(data.c_str(), data.size());
  21713. return true;
  21714. }
  21715. std::this_thread::sleep_for(std::chrono::seconds(3));
  21716. std::string data(900, 'B');
  21717. sink.write(data.c_str(), data.size());
  21718. return true;
  21719. });
  21720. });
  21721. auto port = 8093;
  21722. std::thread t([&]() { svr.listen("localhost", port); });
  21723. svr.wait_until_ready();
  21724. SSLClient cli("localhost", port);
  21725. cli.enable_server_certificate_verification(false);
  21726. cli.set_read_timeout(1, 0); // 1 second timeout
  21727. auto handle = cli.open_stream("GET", "/slow-stream");
  21728. ASSERT_TRUE(handle.is_valid());
  21729. char buf[256];
  21730. ssize_t total = 0;
  21731. ssize_t n;
  21732. bool got_error = false;
  21733. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21734. total += n;
  21735. }
  21736. if (n < 0) {
  21737. got_error = true;
  21738. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21739. handle.get_read_error() == Error::Read)
  21740. << "Actual error: " << to_string(handle.get_read_error());
  21741. }
  21742. EXPECT_TRUE(got_error || total < 1000)
  21743. << "Expected timeout but got all " << total << " bytes";
  21744. svr.stop();
  21745. t.join();
  21746. }
  21747. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21748. // Test SSL connection closed detection
  21749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21750. std::atomic<bool> close_now{false};
  21751. svr.Get("/will-close", [&](const Request &, Response &res) {
  21752. res.set_content_provider(
  21753. 10000, "text/plain",
  21754. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21755. if (offset < 100) {
  21756. std::string data(100, 'X');
  21757. sink.write(data.c_str(), data.size());
  21758. return true;
  21759. }
  21760. while (!close_now) {
  21761. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21762. }
  21763. return false;
  21764. });
  21765. });
  21766. auto port = 8094;
  21767. std::thread t([&]() { svr.listen("localhost", port); });
  21768. svr.wait_until_ready();
  21769. SSLClient cli("localhost", port);
  21770. cli.enable_server_certificate_verification(false);
  21771. auto handle = cli.open_stream("GET", "/will-close");
  21772. ASSERT_TRUE(handle.is_valid());
  21773. char buf[256];
  21774. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21775. EXPECT_GT(n, 0);
  21776. // Signal server to close
  21777. close_now = true;
  21778. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21779. // Keep reading
  21780. }
  21781. if (n < 0) {
  21782. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21783. handle.get_read_error() == Error::Read)
  21784. << "Actual error: " << to_string(handle.get_read_error());
  21785. }
  21786. svr.stop();
  21787. t.join();
  21788. }
  21789. #endif
  21790. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21791. using namespace httplib;
  21792. // Create a test file
  21793. const char *fname = "etag_testfile.txt";
  21794. const char *content = "etag-content";
  21795. {
  21796. std::ofstream ofs(fname);
  21797. ofs << content;
  21798. ASSERT_TRUE(ofs.good());
  21799. }
  21800. Server svr;
  21801. svr.set_mount_point("/static", ".");
  21802. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21803. svr.wait_until_ready();
  21804. Client cli(HOST, PORT);
  21805. // First request: should get 200 with ETag header
  21806. auto res1 = cli.Get("/static/etag_testfile.txt");
  21807. ASSERT_TRUE(res1);
  21808. ASSERT_EQ(200, res1->status);
  21809. ASSERT_TRUE(res1->has_header("ETag"));
  21810. std::string etag = res1->get_header_value("ETag");
  21811. EXPECT_FALSE(etag.empty());
  21812. // Verify ETag format: W/"hex-hex"
  21813. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21814. EXPECT_EQ('W', etag[0]);
  21815. EXPECT_EQ('/', etag[1]);
  21816. EXPECT_EQ('"', etag[2]);
  21817. EXPECT_EQ('"', etag.back());
  21818. // Exact match: expect 304 Not Modified
  21819. Headers h2 = {{"If-None-Match", etag}};
  21820. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21821. ASSERT_TRUE(res2);
  21822. EXPECT_EQ(304, res2->status);
  21823. // Wildcard match: expect 304 Not Modified
  21824. Headers h3 = {{"If-None-Match", "*"}};
  21825. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21826. ASSERT_TRUE(res3);
  21827. EXPECT_EQ(304, res3->status);
  21828. // Non-matching ETag: expect 200
  21829. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21830. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21831. ASSERT_TRUE(res4);
  21832. EXPECT_EQ(200, res4->status);
  21833. // Multiple ETags with one matching: expect 304
  21834. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21835. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21836. ASSERT_TRUE(res5);
  21837. EXPECT_EQ(304, res5->status);
  21838. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21839. // that equivalent to the single comma-separated list above, so the match on
  21840. // the second line must still be found.
  21841. Headers h6;
  21842. h6.emplace("If-None-Match", "W/\"other\"");
  21843. h6.emplace("If-None-Match", etag);
  21844. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21845. ASSERT_TRUE(res6);
  21846. EXPECT_EQ(304, res6->status);
  21847. svr.stop();
  21848. t.join();
  21849. std::remove(fname);
  21850. }
  21851. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21852. using namespace httplib;
  21853. Server svr;
  21854. svr.set_mount_point("/static", ".");
  21855. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21856. svr.wait_until_ready();
  21857. Client cli(HOST, PORT);
  21858. // Send If-None-Match: * to a non-existent file
  21859. Headers h = {{"If-None-Match", "*"}};
  21860. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21862. EXPECT_EQ(404, res->status);
  21863. svr.stop();
  21864. t.join();
  21865. }
  21866. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21867. using namespace httplib;
  21868. // Create a test file
  21869. const char *fname = "etag_boundary_testfile.txt";
  21870. const char *content = "boundary-test";
  21871. {
  21872. std::ofstream ofs(fname);
  21873. ofs << content;
  21874. ASSERT_TRUE(ofs.good());
  21875. }
  21876. Server svr;
  21877. svr.set_mount_point("/static", ".");
  21878. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21879. svr.wait_until_ready();
  21880. Client cli(HOST, PORT);
  21881. // Get the actual ETag
  21882. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21883. ASSERT_TRUE(res1);
  21884. ASSERT_EQ(200, res1->status);
  21885. ASSERT_TRUE(res1->has_header("ETag"));
  21886. std::string etag = res1->get_header_value("ETag");
  21887. // Test 1: Very long ETag value (longer than actual ETag)
  21888. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21889. Headers h1 = {{"If-None-Match", "W/"
  21890. "\"very-long-etag-value-that-is-much-longer-"
  21891. "than-the-actual-etag-value\""}};
  21892. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21893. ASSERT_TRUE(res2);
  21894. EXPECT_EQ(200, res2->status); // Should not match
  21895. // Test 2: Long string followed by wildcard
  21896. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21897. // string)
  21898. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21899. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21900. ASSERT_TRUE(res3);
  21901. EXPECT_EQ(304, res3->status); // Should match on "*"
  21902. // Test 3: Wildcard followed by long string
  21903. // Should match on "*" immediately and return 304
  21904. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21905. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21906. ASSERT_TRUE(res4);
  21907. EXPECT_EQ(304, res4->status); // Should match on "*"
  21908. // Test 4: Multiple long non-matching values
  21909. // Should NOT match and return 200 (test that all comparisons are safe)
  21910. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21911. "W/\"second-long-non-matching-value\", "
  21912. "W/\"third-long-non-matching-value\""}};
  21913. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21914. ASSERT_TRUE(res5);
  21915. EXPECT_EQ(200, res5->status); // Should not match
  21916. // Test 5: Single character that is not "*" (edge case)
  21917. Headers h5 = {{"If-None-Match", "X"}};
  21918. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21919. ASSERT_TRUE(res6);
  21920. EXPECT_EQ(200, res6->status); // Should not match
  21921. svr.stop();
  21922. t.join();
  21923. std::remove(fname);
  21924. }
  21925. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21926. using namespace httplib;
  21927. // Create a test file
  21928. const char *fname = "ims_testfile.txt";
  21929. const char *content = "if-modified-since-test";
  21930. {
  21931. std::ofstream ofs(fname);
  21932. ofs << content;
  21933. ASSERT_TRUE(ofs.good());
  21934. }
  21935. Server svr;
  21936. svr.set_mount_point("/static", ".");
  21937. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21938. svr.wait_until_ready();
  21939. Client cli(HOST, PORT);
  21940. // First request: should get 200 with Last-Modified header
  21941. auto res1 = cli.Get("/static/ims_testfile.txt");
  21942. ASSERT_TRUE(res1);
  21943. ASSERT_EQ(200, res1->status);
  21944. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21945. std::string last_modified = res1->get_header_value("Last-Modified");
  21946. EXPECT_FALSE(last_modified.empty());
  21947. // If-Modified-Since with same time: expect 304
  21948. Headers h2 = {{"If-Modified-Since", last_modified}};
  21949. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21950. ASSERT_TRUE(res2);
  21951. EXPECT_EQ(304, res2->status);
  21952. // If-Modified-Since with future time: expect 304
  21953. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21954. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21955. ASSERT_TRUE(res3);
  21956. EXPECT_EQ(304, res3->status);
  21957. // If-Modified-Since with past time: expect 200
  21958. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21959. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21960. ASSERT_TRUE(res4);
  21961. EXPECT_EQ(200, res4->status);
  21962. // If-None-Match takes precedence over If-Modified-Since
  21963. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21964. ASSERT_TRUE(res1->has_header("ETag"));
  21965. std::string etag = res1->get_header_value("ETag");
  21966. Headers h5 = {{"If-None-Match", etag},
  21967. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21968. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21969. ASSERT_TRUE(res5);
  21970. EXPECT_EQ(304, res5->status);
  21971. svr.stop();
  21972. t.join();
  21973. std::remove(fname);
  21974. }
  21975. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21976. using namespace httplib;
  21977. Server svr;
  21978. // Endpoint that returns compressible content
  21979. svr.Get("/compressible", [](const Request &, Response &res) {
  21980. // Return a large enough body to trigger compression
  21981. std::string body(1000, 'a');
  21982. res.set_content(body, "text/plain");
  21983. });
  21984. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21985. svr.wait_until_ready();
  21986. Client cli(HOST, PORT);
  21987. // Request with gzip support: should get Vary header when compressed
  21988. cli.set_compress(true);
  21989. auto res1 = cli.Get("/compressible");
  21990. ASSERT_TRUE(res1);
  21991. EXPECT_EQ(200, res1->status);
  21992. // If Content-Encoding is set, Vary should also be set
  21993. if (res1->has_header("Content-Encoding")) {
  21994. EXPECT_TRUE(res1->has_header("Vary"));
  21995. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21996. }
  21997. // Request without Accept-Encoding header: should not have compression
  21998. Headers h_no_compress;
  21999. auto res2 = cli.Get("/compressible", h_no_compress);
  22000. ASSERT_TRUE(res2);
  22001. EXPECT_EQ(200, res2->status);
  22002. // Verify Vary header is present when compression is applied
  22003. // (the exact behavior depends on server configuration)
  22004. svr.stop();
  22005. t.join();
  22006. }
  22007. TEST(ETagTest, IfRangeWithETag) {
  22008. using namespace httplib;
  22009. // Create a test file with known content
  22010. const char *fname = "if_range_testfile.txt";
  22011. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22012. {
  22013. std::ofstream ofs(fname);
  22014. ofs << content;
  22015. ASSERT_TRUE(ofs.good());
  22016. }
  22017. Server svr;
  22018. svr.set_mount_point("/static", ".");
  22019. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22020. svr.wait_until_ready();
  22021. Client cli(HOST, PORT);
  22022. // First request: get ETag
  22023. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22024. ASSERT_TRUE(res1);
  22025. ASSERT_EQ(200, res1->status);
  22026. ASSERT_TRUE(res1->has_header("ETag"));
  22027. std::string etag = res1->get_header_value("ETag");
  22028. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22029. // Since our server generates weak ETags (W/"..."), If-Range with our
  22030. // ETag should NOT result in partial content - it should return full content.
  22031. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22032. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22033. ASSERT_TRUE(res2);
  22034. // Weak ETag in If-Range -> full content (200), not partial (206)
  22035. EXPECT_EQ(200, res2->status);
  22036. EXPECT_EQ(content, res2->body);
  22037. EXPECT_FALSE(res2->has_header("Content-Range"));
  22038. // Range request with non-matching If-Range (ETag): should get 200 (full
  22039. // content)
  22040. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22041. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22042. ASSERT_TRUE(res3);
  22043. EXPECT_EQ(200, res3->status);
  22044. EXPECT_EQ(content, res3->body);
  22045. EXPECT_FALSE(res3->has_header("Content-Range"));
  22046. // Range request with strong ETag (hypothetical - our server doesn't generate
  22047. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22048. // should return full content)
  22049. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22050. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22051. ASSERT_TRUE(res4);
  22052. EXPECT_EQ(200, res4->status);
  22053. EXPECT_EQ(content, res4->body);
  22054. EXPECT_FALSE(res4->has_header("Content-Range"));
  22055. svr.stop();
  22056. t.join();
  22057. std::remove(fname);
  22058. }
  22059. TEST(ETagTest, IfRangeWithDate) {
  22060. using namespace httplib;
  22061. // Create a test file
  22062. const char *fname = "if_range_date_testfile.txt";
  22063. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22064. {
  22065. std::ofstream ofs(fname);
  22066. ofs << content;
  22067. ASSERT_TRUE(ofs.good());
  22068. }
  22069. Server svr;
  22070. svr.set_mount_point("/static", ".");
  22071. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22072. svr.wait_until_ready();
  22073. Client cli(HOST, PORT);
  22074. // First request: get Last-Modified
  22075. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22076. ASSERT_TRUE(res1);
  22077. ASSERT_EQ(200, res1->status);
  22078. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22079. std::string last_modified = res1->get_header_value("Last-Modified");
  22080. // Range request with matching If-Range (date): should get 206
  22081. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22082. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22083. ASSERT_TRUE(res2);
  22084. EXPECT_EQ(206, res2->status);
  22085. EXPECT_EQ("FGHIJ", res2->body);
  22086. // Range request with old If-Range date: should get 200 (full content)
  22087. Headers h3 = {{"Range", "bytes=5-9"},
  22088. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22089. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22090. ASSERT_TRUE(res3);
  22091. EXPECT_EQ(200, res3->status);
  22092. EXPECT_EQ(content, res3->body);
  22093. // Range request with future If-Range date: should get 206
  22094. Headers h4 = {{"Range", "bytes=0-4"},
  22095. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22096. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22097. ASSERT_TRUE(res4);
  22098. EXPECT_EQ(206, res4->status);
  22099. EXPECT_EQ("ABCDE", res4->body);
  22100. svr.stop();
  22101. t.join();
  22102. std::remove(fname);
  22103. }
  22104. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22105. using namespace httplib;
  22106. const char *fname = "etag_malformed.txt";
  22107. const char *content = "malformed-etag";
  22108. {
  22109. std::ofstream ofs(fname);
  22110. ofs << content;
  22111. ASSERT_TRUE(ofs.good());
  22112. }
  22113. Server svr;
  22114. svr.set_mount_point("/static", ".");
  22115. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22116. svr.wait_until_ready();
  22117. Client cli(HOST, PORT);
  22118. // baseline: should get 200 and an ETag
  22119. auto res1 = cli.Get("/static/etag_malformed.txt");
  22120. ASSERT_TRUE(res1);
  22121. ASSERT_EQ(200, res1->status);
  22122. ASSERT_TRUE(res1->has_header("ETag"));
  22123. // Malformed ETag value (missing quotes) should be treated as non-matching
  22124. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22125. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22126. ASSERT_TRUE(res_bad);
  22127. EXPECT_EQ(200, res_bad->status);
  22128. // Whitespace-only header value should be considered invalid / non-matching
  22129. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22130. "Host: localhost\r\n"
  22131. "If-None-Match: \r\n"
  22132. "Connection: close\r\n"
  22133. "\r\n";
  22134. std::string out;
  22135. ASSERT_TRUE(send_request(5, raw_req, &out));
  22136. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22137. svr.stop();
  22138. t.join();
  22139. std::remove(fname);
  22140. }
  22141. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22142. using namespace httplib;
  22143. const char *fname = "ims_invalid_format.txt";
  22144. const char *content = "ims-bad-format";
  22145. {
  22146. std::ofstream ofs(fname);
  22147. ofs << content;
  22148. ASSERT_TRUE(ofs.good());
  22149. }
  22150. Server svr;
  22151. svr.set_mount_point("/static", ".");
  22152. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22153. svr.wait_until_ready();
  22154. Client cli(HOST, PORT);
  22155. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22156. ASSERT_TRUE(res1);
  22157. ASSERT_EQ(200, res1->status);
  22158. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22159. // If-Modified-Since with invalid format should not result in 304
  22160. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22161. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22162. ASSERT_TRUE(res_bad);
  22163. EXPECT_EQ(200, res_bad->status);
  22164. // If-Range with invalid date format should be treated as mismatch -> full
  22165. // content (200)
  22166. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22167. {"If-Range", "invalid-date"}};
  22168. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22169. ASSERT_TRUE(res_ifrange);
  22170. EXPECT_EQ(200, res_ifrange->status);
  22171. svr.stop();
  22172. t.join();
  22173. std::remove(fname);
  22174. }
  22175. TEST(ETagTest, IfRangeWithMalformedETag) {
  22176. using namespace httplib;
  22177. const char *fname = "ifrange_malformed.txt";
  22178. const std::string content = "0123456789";
  22179. {
  22180. std::ofstream ofs(fname);
  22181. ofs << content;
  22182. ASSERT_TRUE(ofs.good());
  22183. }
  22184. Server svr;
  22185. svr.set_mount_point("/static", ".");
  22186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22187. svr.wait_until_ready();
  22188. Client cli(HOST, PORT);
  22189. // First request: get ETag
  22190. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22191. ASSERT_TRUE(res1);
  22192. ASSERT_EQ(200, res1->status);
  22193. ASSERT_TRUE(res1->has_header("ETag"));
  22194. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22195. // full content (200)
  22196. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22197. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22198. ASSERT_TRUE(res2);
  22199. EXPECT_EQ(200, res2->status);
  22200. EXPECT_EQ(content, res2->body);
  22201. svr.stop();
  22202. t.join();
  22203. std::remove(fname);
  22204. }
  22205. TEST(ETagTest, ExtremeLargeDateValues) {
  22206. using namespace httplib;
  22207. const char *fname = "ims_extreme_date.txt";
  22208. const char *content = "ims-extreme-date";
  22209. {
  22210. std::ofstream ofs(fname);
  22211. ofs << content;
  22212. ASSERT_TRUE(ofs.good());
  22213. }
  22214. Server svr;
  22215. svr.set_mount_point("/static", ".");
  22216. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22217. svr.wait_until_ready();
  22218. Client cli(HOST, PORT);
  22219. auto res1 = cli.Get(std::string("/static/") + fname);
  22220. ASSERT_TRUE(res1);
  22221. ASSERT_EQ(200, res1->status);
  22222. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22223. // Extremely large year that may overflow date parsing routines.
  22224. Headers h_large_date = {
  22225. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22226. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22227. ASSERT_TRUE(res_bad);
  22228. // Expect server to treat this as invalid/mismatch and return full content
  22229. EXPECT_EQ(200, res_bad->status);
  22230. // If-Range with extremely large date should be treated as mismatch -> full
  22231. // content (200)
  22232. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22233. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22234. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22235. ASSERT_TRUE(res_ifrange);
  22236. EXPECT_EQ(200, res_ifrange->status);
  22237. svr.stop();
  22238. t.join();
  22239. std::remove(fname);
  22240. }
  22241. TEST(ETagTest, NegativeFileModificationTime) {
  22242. using namespace httplib;
  22243. const char *fname = "ims_negative_mtime.txt";
  22244. const std::string content = "negative-mtime";
  22245. {
  22246. std::ofstream ofs(fname);
  22247. ofs << content;
  22248. ASSERT_TRUE(ofs.good());
  22249. }
  22250. // Try to set file mtime to a negative value. This may fail on some
  22251. // platforms/filesystems; if it fails, the test will still verify server
  22252. // behaves safely by performing a regular conditional request.
  22253. #if defined(__APPLE__) || defined(__linux__)
  22254. bool set_negative = false;
  22255. do {
  22256. struct timeval times[2];
  22257. // access time: now
  22258. times[0].tv_sec = time(nullptr);
  22259. times[0].tv_usec = 0;
  22260. // modification time: negative (e.g., -1)
  22261. times[1].tv_sec = -1;
  22262. times[1].tv_usec = 0;
  22263. if (utimes(fname, times) == 0) { set_negative = true; }
  22264. } while (0);
  22265. #else
  22266. bool set_negative = false;
  22267. #endif
  22268. Server svr;
  22269. svr.set_mount_point("/static", ".");
  22270. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22271. svr.wait_until_ready();
  22272. Client cli(HOST, PORT);
  22273. auto res1 = cli.Get(std::string("/static/") + fname);
  22274. ASSERT_TRUE(res1);
  22275. ASSERT_EQ(200, res1->status);
  22276. bool has_last_modified = res1->has_header("Last-Modified");
  22277. std::string last_modified;
  22278. if (has_last_modified) {
  22279. last_modified = res1->get_header_value("Last-Modified");
  22280. }
  22281. if (set_negative) {
  22282. // If we successfully set a negative mtime, ensure server returns a
  22283. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22284. // with an old date and ensure server handles it without crash.
  22285. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22286. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22287. ASSERT_TRUE(res2);
  22288. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22289. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22290. } else {
  22291. // Could not set negative mtime on this platform; fall back to verifying
  22292. // that normal invalid/malformed dates are treated safely (non-304).
  22293. Headers h_bad_date = {
  22294. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22295. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22296. ASSERT_TRUE(res_bad);
  22297. EXPECT_EQ(200, res_bad->status);
  22298. }
  22299. svr.stop();
  22300. t.join();
  22301. std::remove(fname);
  22302. }
  22303. //==============================================================================
  22304. // Integration Tests with Server
  22305. //==============================================================================
  22306. class SSEIntegrationTest : public ::testing::Test {
  22307. protected:
  22308. void SetUp() override {
  22309. stop_server_.store(false);
  22310. events_.clear();
  22311. server_ = httplib::detail::make_unique<Server>();
  22312. setup_server();
  22313. start_server();
  22314. }
  22315. void TearDown() override {
  22316. stop_server_.store(true);
  22317. event_cv_.notify_all();
  22318. server_->stop();
  22319. if (server_thread_.joinable()) { server_thread_.join(); }
  22320. }
  22321. void setup_server() {
  22322. // Simple SSE endpoint
  22323. server_->Get("/events", [this](const Request &req, Response &res) {
  22324. auto last_id = req.get_header_value("Last-Event-ID");
  22325. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22326. res.set_chunked_content_provider(
  22327. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22328. std::unique_lock<std::mutex> lock(event_mutex_);
  22329. if (event_cv_.wait_for(
  22330. lock, std::chrono::milliseconds(200), [this] {
  22331. return !events_.empty() || stop_server_.load();
  22332. })) {
  22333. if (stop_server_.load()) { return false; }
  22334. if (!events_.empty()) {
  22335. std::string event = events_.front();
  22336. events_.erase(events_.begin());
  22337. sink.write(event.data(), event.size());
  22338. return true;
  22339. }
  22340. }
  22341. return !stop_server_.load();
  22342. });
  22343. });
  22344. // Endpoint that returns error
  22345. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22346. res.status = 500;
  22347. res.set_content("Internal Server Error", "text/plain");
  22348. });
  22349. // Endpoint for custom event types
  22350. server_->Get("/custom-events", [](const Request &, Response &res) {
  22351. res.set_chunked_content_provider(
  22352. "text/event-stream", [](size_t offset, DataSink &sink) {
  22353. if (offset == 0) {
  22354. std::string event = "event: update\ndata: updated\n\n"
  22355. "event: delete\ndata: deleted\n\n";
  22356. sink.write(event.data(), event.size());
  22357. }
  22358. return false; // End stream after sending
  22359. });
  22360. });
  22361. }
  22362. void start_server() {
  22363. port_ = server_->bind_to_any_port(HOST);
  22364. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22365. // Wait for server to start
  22366. while (!server_->is_running()) {
  22367. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22368. }
  22369. }
  22370. int get_port() const { return port_; }
  22371. void send_event(const std::string &event) {
  22372. std::lock_guard<std::mutex> lock(event_mutex_);
  22373. events_.push_back(event);
  22374. event_cv_.notify_all();
  22375. }
  22376. std::unique_ptr<Server> server_;
  22377. std::thread server_thread_;
  22378. std::mutex event_mutex_;
  22379. std::condition_variable event_cv_;
  22380. std::vector<std::string> events_;
  22381. std::atomic<bool> stop_server_{false};
  22382. std::string last_received_event_id_;
  22383. int port_ = 0;
  22384. };
  22385. //==============================================================================
  22386. // SSE Parsing Tests
  22387. //==============================================================================
  22388. class SSEParsingTest : public SSEIntegrationTest {
  22389. protected:
  22390. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22391. // A trailing sentinel event tells when the whole stream has been parsed.
  22392. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22393. auto body = stream + "event: end\ndata: end\n\n";
  22394. server_->Get("/parse", [body](const Request &, Response &res) {
  22395. res.set_content(body, "text/event-stream");
  22396. });
  22397. return collect("/parse");
  22398. }
  22399. // Runs SSEClient against path until an "end" event arrives and returns the
  22400. // messages dispatched before it
  22401. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22402. Client client(HOST, get_port());
  22403. sse::SSEClient sse(client, path);
  22404. std::mutex mutex;
  22405. std::condition_variable cv;
  22406. std::vector<sse::SSEMessage> messages;
  22407. auto done = false;
  22408. sse.on_message([&](const sse::SSEMessage &msg) {
  22409. std::lock_guard<std::mutex> lock(mutex);
  22410. // Ignore a replay from a reconnect that races with stop()
  22411. if (!done) { messages.push_back(msg); }
  22412. });
  22413. sse.on_event("end", [&](const sse::SSEMessage &) {
  22414. std::lock_guard<std::mutex> lock(mutex);
  22415. done = true;
  22416. cv.notify_all();
  22417. });
  22418. sse.set_reconnect_interval(100);
  22419. sse.start_async();
  22420. {
  22421. std::unique_lock<std::mutex> lock(mutex);
  22422. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22423. }
  22424. sse.stop();
  22425. EXPECT_TRUE(done);
  22426. return messages;
  22427. }
  22428. };
  22429. TEST_F(SSEParsingTest, SingleLineData) {
  22430. auto msgs = parse("data: hello\n\n");
  22431. ASSERT_EQ(msgs.size(), 1u);
  22432. EXPECT_EQ(msgs[0].data, "hello");
  22433. EXPECT_EQ(msgs[0].event, "message");
  22434. }
  22435. TEST_F(SSEParsingTest, MultiLineData) {
  22436. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22437. ASSERT_EQ(msgs.size(), 1u);
  22438. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22439. }
  22440. TEST_F(SSEParsingTest, CustomEventType) {
  22441. auto msgs = parse("event: update\ndata: payload\n\n");
  22442. ASSERT_EQ(msgs.size(), 1u);
  22443. EXPECT_EQ(msgs[0].event, "update");
  22444. EXPECT_EQ(msgs[0].data, "payload");
  22445. }
  22446. TEST_F(SSEParsingTest, EventIdHandling) {
  22447. auto msgs = parse("id: 12345\ndata: test\n\n");
  22448. ASSERT_EQ(msgs.size(), 1u);
  22449. EXPECT_EQ(msgs[0].id, "12345");
  22450. }
  22451. TEST_F(SSEParsingTest, EmptyEventId) {
  22452. auto msgs = parse("id:\ndata: test\n\n");
  22453. ASSERT_EQ(msgs.size(), 1u);
  22454. EXPECT_EQ(msgs[0].id, "");
  22455. }
  22456. TEST_F(SSEParsingTest, CommentsIgnored) {
  22457. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22458. ASSERT_EQ(msgs.size(), 1u);
  22459. EXPECT_EQ(msgs[0].data, "hello");
  22460. EXPECT_EQ(msgs[0].event, "message");
  22461. }
  22462. TEST_F(SSEParsingTest, ColonInValue) {
  22463. auto msgs = parse("data: hello:world:test\n\n");
  22464. ASSERT_EQ(msgs.size(), 1u);
  22465. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22466. }
  22467. TEST_F(SSEParsingTest, FieldNameOnly) {
  22468. // A line without a colon is a field name with an empty value
  22469. auto msgs = parse("data\n\n");
  22470. ASSERT_EQ(msgs.size(), 1u);
  22471. EXPECT_EQ(msgs[0].data, "");
  22472. }
  22473. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22474. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22475. ASSERT_EQ(msgs.size(), 1u);
  22476. EXPECT_EQ(msgs[0].event, "update");
  22477. EXPECT_EQ(msgs[0].data, "hello");
  22478. }
  22479. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22480. auto msgs = parse("data\r\n\r\n");
  22481. ASSERT_EQ(msgs.size(), 1u);
  22482. EXPECT_EQ(msgs[0].data, "");
  22483. }
  22484. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22485. auto msgs = parse("event: update\rdata: hello\r\r");
  22486. ASSERT_EQ(msgs.size(), 1u);
  22487. EXPECT_EQ(msgs[0].event, "update");
  22488. EXPECT_EQ(msgs[0].data, "hello");
  22489. }
  22490. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22491. // Chunk boundaries fall inside every \r\n and right before the first one
  22492. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22493. "\n\r", "\nevent: end\ndata: end\n\n"};
  22494. server_->Get("/split", [chunks](const Request &, Response &res) {
  22495. auto i = std::make_shared<size_t>(0);
  22496. res.set_chunked_content_provider(
  22497. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22498. if (*i == chunks.size()) {
  22499. sink.done();
  22500. } else {
  22501. sink.write(chunks[*i].data(), chunks[*i].size());
  22502. (*i)++;
  22503. }
  22504. return true;
  22505. });
  22506. });
  22507. auto msgs = collect("/split");
  22508. ASSERT_EQ(msgs.size(), 1u);
  22509. EXPECT_EQ(msgs[0].event, "update");
  22510. EXPECT_EQ(msgs[0].data, "hello");
  22511. }
  22512. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22513. // Only a BOM at the start of the stream is ignored
  22514. auto msgs = parse("\xEF\xBB\xBF"
  22515. "data: first\n\n"
  22516. "\xEF\xBB\xBF"
  22517. "data: second\n\n");
  22518. ASSERT_EQ(msgs.size(), 1u);
  22519. EXPECT_EQ(msgs[0].data, "first");
  22520. }
  22521. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22522. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22523. ASSERT_EQ(msgs.size(), 1u);
  22524. EXPECT_EQ(msgs[0].data, "hello");
  22525. EXPECT_EQ(msgs[0].event, "message");
  22526. }
  22527. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22528. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22529. ASSERT_EQ(msgs.size(), 2u);
  22530. EXPECT_EQ(msgs[0].data, "hello");
  22531. EXPECT_EQ(msgs[1].data, "hello");
  22532. }
  22533. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22534. // An event without data is not dispatched, and its type must not leak
  22535. // into the next event
  22536. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22537. ASSERT_EQ(msgs.size(), 1u);
  22538. EXPECT_EQ(msgs[0].event, "message");
  22539. EXPECT_EQ(msgs[0].data, "hello");
  22540. }
  22541. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22542. // Also when the empty field replaces an earlier type
  22543. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22544. ASSERT_EQ(msgs.size(), 2u);
  22545. EXPECT_EQ(msgs[0].event, "message");
  22546. EXPECT_EQ(msgs[1].event, "message");
  22547. }
  22548. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22549. // The first connection sends only an id; the second echoes back the
  22550. // Last-Event-ID it was reconnected with
  22551. std::atomic<int> connection_count{0};
  22552. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22553. if (connection_count++ == 0) {
  22554. res.set_content("id: 42\n\n", "text/event-stream");
  22555. } else {
  22556. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22557. "\n\nevent: end\ndata: end\n\n",
  22558. "text/event-stream");
  22559. }
  22560. });
  22561. auto msgs = collect("/id-only");
  22562. ASSERT_EQ(msgs.size(), 1u);
  22563. EXPECT_EQ(msgs[0].data, "42");
  22564. }
  22565. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22566. // The first connection sets an id and then clears it with an empty one; the
  22567. // second reports whether it was reconnected with a Last-Event-ID
  22568. std::atomic<int> connection_count{0};
  22569. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22570. if (connection_count++ == 0) {
  22571. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22572. "text/event-stream");
  22573. } else {
  22574. res.set_content(
  22575. std::string("data: ") +
  22576. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22577. "\n\nevent: end\ndata: end\n\n",
  22578. "text/event-stream");
  22579. }
  22580. });
  22581. auto msgs = collect("/id-clear");
  22582. ASSERT_EQ(msgs.size(), 3u);
  22583. EXPECT_EQ(msgs[0].id, "1");
  22584. EXPECT_EQ(msgs[1].id, "");
  22585. EXPECT_EQ(msgs[2].data, "not sent");
  22586. }
  22587. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22588. // The first connection sets an id and then sends ids that cannot be carried
  22589. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22590. // with
  22591. std::atomic<int> connection_count{0};
  22592. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22593. if (connection_count++ == 0) {
  22594. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22595. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22596. "text/event-stream");
  22597. } else {
  22598. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22599. "\n\nevent: end\ndata: end\n\n",
  22600. "text/event-stream");
  22601. }
  22602. });
  22603. auto msgs = collect("/id-unsendable");
  22604. ASSERT_EQ(msgs.size(), 1u);
  22605. EXPECT_EQ(msgs[0].data, "42");
  22606. }
  22607. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22608. auto msgs = parse("event: notification\nid: evt-42\n"
  22609. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22610. ASSERT_EQ(msgs.size(), 1u);
  22611. EXPECT_EQ(msgs[0].event, "notification");
  22612. EXPECT_EQ(msgs[0].id, "evt-42");
  22613. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22614. }
  22615. TEST(SSEMessageTest, Clear) {
  22616. sse::SSEMessage msg;
  22617. msg.event = "custom";
  22618. msg.data = "some data";
  22619. msg.id = "123";
  22620. msg.clear();
  22621. EXPECT_EQ(msg.event, "message");
  22622. EXPECT_EQ(msg.data, "");
  22623. EXPECT_EQ(msg.id, "");
  22624. }
  22625. //==============================================================================
  22626. // SSE Integration Tests
  22627. //==============================================================================
  22628. // Test: Successful connection and on_open callback
  22629. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22630. // Add a simple endpoint that sends one event and closes
  22631. server_->Get("/simple-event", [](const Request &, Response &res) {
  22632. res.set_chunked_content_provider(
  22633. "text/event-stream", [](size_t offset, DataSink &sink) {
  22634. if (offset == 0) {
  22635. std::string event = "data: hello\n\n";
  22636. sink.write(event.data(), event.size());
  22637. }
  22638. return false; // Close stream after sending
  22639. });
  22640. });
  22641. Client client("localhost", get_port());
  22642. sse::SSEClient sse(client, "/simple-event");
  22643. std::atomic<bool> open_called{false};
  22644. std::atomic<bool> message_received{false};
  22645. sse.on_open([&open_called]() { open_called.store(true); });
  22646. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22647. if (msg.data == "hello") { message_received.store(true); }
  22648. });
  22649. sse.set_reconnect_interval(100);
  22650. sse.set_max_reconnect_attempts(1);
  22651. // Start async
  22652. sse.start_async();
  22653. // Wait for message to be processed
  22654. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22655. sse.stop();
  22656. EXPECT_TRUE(open_called.load());
  22657. EXPECT_TRUE(message_received.load());
  22658. }
  22659. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22660. // A data line that never ends.
  22661. server_->Get("/endless-line", [](const Request &, Response &res) {
  22662. res.set_chunked_content_provider(
  22663. "text/event-stream", [](size_t offset, DataSink &sink) {
  22664. if (offset == 0) { sink.write("data: ", 6); }
  22665. std::string chunk(64 * 1024, 'A');
  22666. return sink.write(chunk.data(), chunk.size());
  22667. });
  22668. });
  22669. Client client("localhost", get_port());
  22670. sse::SSEClient sse(client, "/endless-line");
  22671. std::atomic<bool> too_long{false};
  22672. sse.on_error([&](Error err) {
  22673. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22674. });
  22675. sse.set_max_reconnect_attempts(1);
  22676. sse.start_async();
  22677. for (int i = 0; i < 500 && !too_long; i++) {
  22678. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22679. }
  22680. sse.stop();
  22681. EXPECT_TRUE(too_long);
  22682. }
  22683. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22684. // Far more in all than the client's payload limit below.
  22685. server_->Get("/many-events", [](const Request &, Response &res) {
  22686. res.set_chunked_content_provider(
  22687. "text/event-stream", [](size_t offset, DataSink &sink) {
  22688. if (offset == 0) {
  22689. std::string events;
  22690. for (int i = 0; i < 1000; i++) {
  22691. events += "data: message\n\n";
  22692. }
  22693. sink.write(events.data(), events.size());
  22694. }
  22695. return false;
  22696. });
  22697. });
  22698. Client client("localhost", get_port());
  22699. client.set_payload_max_length(1024);
  22700. sse::SSEClient sse(client, "/many-events");
  22701. std::atomic<int> messages{0};
  22702. std::atomic<bool> too_large{false};
  22703. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22704. sse.on_error([&](Error err) {
  22705. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22706. });
  22707. sse.set_max_reconnect_attempts(1);
  22708. sse.start_async();
  22709. for (int i = 0; i < 500 && messages < 1000; i++) {
  22710. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22711. }
  22712. sse.stop();
  22713. EXPECT_GE(messages.load(), 1000);
  22714. EXPECT_FALSE(too_large);
  22715. }
  22716. // Test: on_message callback
  22717. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22718. // Endpoint that sends multiple events then closes
  22719. server_->Get("/multi-event", [](const Request &, Response &res) {
  22720. res.set_chunked_content_provider(
  22721. "text/event-stream", [](size_t offset, DataSink &sink) {
  22722. if (offset == 0) {
  22723. std::string events = "data: message1\n\ndata: message2\n\n";
  22724. sink.write(events.data(), events.size());
  22725. }
  22726. return false;
  22727. });
  22728. });
  22729. Client client("localhost", get_port());
  22730. sse::SSEClient sse(client, "/multi-event");
  22731. std::vector<std::string> received_messages;
  22732. std::mutex messages_mutex;
  22733. sse.on_message([&](const sse::SSEMessage &msg) {
  22734. std::lock_guard<std::mutex> lock(messages_mutex);
  22735. received_messages.push_back(msg.data);
  22736. });
  22737. sse.set_reconnect_interval(100);
  22738. sse.set_max_reconnect_attempts(1);
  22739. sse.start_async();
  22740. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22741. sse.stop();
  22742. std::lock_guard<std::mutex> lock(messages_mutex);
  22743. EXPECT_GE(received_messages.size(), 2u);
  22744. if (received_messages.size() >= 2) {
  22745. EXPECT_EQ(received_messages[0], "message1");
  22746. EXPECT_EQ(received_messages[1], "message2");
  22747. }
  22748. }
  22749. // Test: on_event for specific types
  22750. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22751. Client client("localhost", get_port());
  22752. sse::SSEClient sse(client, "/custom-events");
  22753. std::atomic<bool> update_received{false};
  22754. std::atomic<bool> delete_received{false};
  22755. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22756. if (msg.data == "updated") { update_received.store(true); }
  22757. });
  22758. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22759. if (msg.data == "deleted") { delete_received.store(true); }
  22760. });
  22761. sse.set_max_reconnect_attempts(1);
  22762. sse.start_async();
  22763. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22764. sse.stop();
  22765. EXPECT_TRUE(update_received.load());
  22766. EXPECT_TRUE(delete_received.load());
  22767. }
  22768. // Test: on_error callback on connection failure
  22769. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22770. // Connect to a non-existent port
  22771. Client client("localhost", 59999);
  22772. sse::SSEClient sse(client, "/events");
  22773. std::atomic<bool> error_called{false};
  22774. Error received_error = Error::Success;
  22775. sse.on_error([&](Error err) {
  22776. error_called.store(true);
  22777. received_error = err;
  22778. });
  22779. sse.set_reconnect_interval(50);
  22780. sse.set_max_reconnect_attempts(1);
  22781. sse.start_async();
  22782. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22783. sse.stop();
  22784. EXPECT_TRUE(error_called.load());
  22785. EXPECT_NE(received_error, Error::Success);
  22786. }
  22787. // Test: Last-Event-ID header sent on reconnect
  22788. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22789. // Endpoint that sends event with ID
  22790. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22791. res.set_chunked_content_provider(
  22792. "text/event-stream", [](size_t offset, DataSink &sink) {
  22793. if (offset == 0) {
  22794. std::string event = "id: evt-123\ndata: test\n\n";
  22795. sink.write(event.data(), event.size());
  22796. }
  22797. return false;
  22798. });
  22799. });
  22800. Client client("localhost", get_port());
  22801. sse::SSEClient sse(client, "/event-with-id");
  22802. std::atomic<bool> id_received{false};
  22803. sse.on_message([&](const sse::SSEMessage &msg) {
  22804. if (!msg.id.empty()) { id_received.store(true); }
  22805. });
  22806. sse.set_reconnect_interval(100);
  22807. sse.set_max_reconnect_attempts(1);
  22808. sse.start_async();
  22809. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22810. sse.stop();
  22811. EXPECT_TRUE(id_received.load());
  22812. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22813. }
  22814. // Test: last_event_id() read from another thread while start_async() runs
  22815. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22816. // Ids of every length up to 200, so the stored id keeps changing size
  22817. server_->Get("/many-ids", [](const Request &, Response &res) {
  22818. res.set_chunked_content_provider(
  22819. "text/event-stream", [](size_t offset, DataSink &sink) {
  22820. if (offset == 0) {
  22821. std::string events;
  22822. for (size_t i = 0; i < 2000; i++) {
  22823. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22824. events += "data: x\n\n";
  22825. }
  22826. events += "id: end\ndata: x\n\n";
  22827. sink.write(events.data(), events.size());
  22828. }
  22829. return false;
  22830. });
  22831. });
  22832. Client client("localhost", get_port());
  22833. sse::SSEClient sse(client, "/many-ids");
  22834. // Wait out the rest of the test rather than replay the stream
  22835. sse.set_reconnect_interval(10000);
  22836. sse.set_max_reconnect_attempts(1);
  22837. sse.start_async();
  22838. auto well_formed = true;
  22839. std::string id;
  22840. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22841. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22842. id = sse.last_event_id();
  22843. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22844. well_formed = false;
  22845. }
  22846. }
  22847. sse.stop();
  22848. EXPECT_TRUE(well_formed);
  22849. EXPECT_EQ(sse.last_event_id(), "end");
  22850. }
  22851. // Test: Manual stop
  22852. TEST_F(SSEIntegrationTest, ManualStop) {
  22853. // Endpoint that sends one event and stays open briefly. The server outlives
  22854. // this test body, so the provider uses the fixture's flag, not a local.
  22855. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22856. res.set_chunked_content_provider(
  22857. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22858. if (offset == 0) {
  22859. std::string event = "data: connected\n\n";
  22860. sink.write(event.data(), event.size());
  22861. }
  22862. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22863. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22864. }
  22865. return false;
  22866. });
  22867. });
  22868. Client client("localhost", get_port());
  22869. sse::SSEClient sse(client, "/stay-open");
  22870. std::atomic<bool> connected{false};
  22871. sse.on_open([&connected]() { connected.store(true); });
  22872. sse.set_reconnect_interval(100);
  22873. sse.set_max_reconnect_attempts(1);
  22874. sse.start_async();
  22875. // Wait for connection to establish
  22876. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22877. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22878. }
  22879. EXPECT_TRUE(connected.load());
  22880. EXPECT_TRUE(sse.is_connected());
  22881. // Signal handler to stop
  22882. stop_server_.store(true);
  22883. // Stop SSE client
  22884. sse.stop();
  22885. EXPECT_FALSE(sse.is_connected());
  22886. }
  22887. // Sends one event, then nothing until stop is set
  22888. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22889. return [&stop](const Request &, Response &res) {
  22890. res.set_chunked_content_provider(
  22891. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22892. if (offset == 0) {
  22893. std::string event = "data: hello\n\n";
  22894. sink.write(event.data(), event.size());
  22895. }
  22896. while (!stop.load()) {
  22897. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22898. }
  22899. return false;
  22900. });
  22901. };
  22902. }
  22903. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22904. static void check_stop_interrupts_blocked_read(Client &client) {
  22905. client.set_read_timeout(30, 0);
  22906. for (auto by_destructor : {false, true}) {
  22907. std::atomic<bool> received{false};
  22908. std::chrono::steady_clock::time_point start;
  22909. {
  22910. sse::SSEClient sse(client, "/idle-stream");
  22911. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22912. sse.start_async();
  22913. for (int i = 0; i < 500 && !received.load(); ++i) {
  22914. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22915. }
  22916. ASSERT_TRUE(received.load());
  22917. // Let the client block in the next read
  22918. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22919. start = std::chrono::steady_clock::now();
  22920. if (!by_destructor) { sse.stop(); }
  22921. }
  22922. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22923. std::chrono::seconds(2));
  22924. }
  22925. }
  22926. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22927. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22928. Client client("localhost", get_port());
  22929. check_stop_interrupts_blocked_read(client);
  22930. }
  22931. #ifdef CPPHTTPLIB_SSL_ENABLED
  22932. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22934. std::atomic<bool> done{false};
  22935. svr.Get("/idle-stream", idle_event_stream(done));
  22936. auto port = svr.bind_to_any_port(HOST);
  22937. std::thread t([&] { svr.listen_after_bind(); });
  22938. auto se = detail::scope_exit([&] {
  22939. done.store(true);
  22940. svr.stop();
  22941. t.join();
  22942. });
  22943. svr.wait_until_ready();
  22944. Client client("https://localhost:" + std::to_string(port));
  22945. client.enable_server_certificate_verification(false);
  22946. check_stop_interrupts_blocked_read(client);
  22947. }
  22948. #endif
  22949. // Test: SSEClient with custom headers
  22950. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22951. // Setup a server endpoint that checks for custom header
  22952. std::atomic<bool> header_received{false};
  22953. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22954. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22955. header_received.store(true);
  22956. }
  22957. res.set_chunked_content_provider("text/event-stream",
  22958. [](size_t, DataSink &) { return false; });
  22959. });
  22960. Client client("localhost", get_port());
  22961. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22962. sse::SSEClient sse(client, "/header-check", headers);
  22963. sse.set_max_reconnect_attempts(1);
  22964. sse.start_async();
  22965. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22966. sse.stop();
  22967. EXPECT_TRUE(header_received.load());
  22968. }
  22969. // Test: Reconnect interval configuration
  22970. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22971. Client client("localhost", get_port());
  22972. sse::SSEClient sse(client, "/events");
  22973. auto &result = sse.set_reconnect_interval(500);
  22974. // Builder pattern should return reference to self
  22975. EXPECT_EQ(&result, &sse);
  22976. }
  22977. // Test: Max reconnect attempts
  22978. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22979. // Connect to non-existent port to force reconnects
  22980. Client client("localhost", 59998);
  22981. sse::SSEClient sse(client, "/events");
  22982. std::atomic<int> error_count{0};
  22983. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22984. sse.set_reconnect_interval(50);
  22985. sse.set_max_reconnect_attempts(2);
  22986. auto start = std::chrono::steady_clock::now();
  22987. sse.start(); // Blocking call
  22988. auto end = std::chrono::steady_clock::now();
  22989. // Should have stopped after 2 failed attempts
  22990. EXPECT_GE(error_count.load(), 2);
  22991. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22992. auto duration =
  22993. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22994. #ifdef _WIN32
  22995. // Windows is much slower for socket connection failures
  22996. EXPECT_LT(duration.count(), 7000);
  22997. #else
  22998. EXPECT_LT(duration.count(), 1000);
  22999. #endif
  23000. }
  23001. // Test: Multi-line data in integration
  23002. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23003. // Endpoint with multi-line data
  23004. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23005. res.set_chunked_content_provider(
  23006. "text/event-stream", [](size_t offset, DataSink &sink) {
  23007. if (offset == 0) {
  23008. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23009. sink.write(event.data(), event.size());
  23010. }
  23011. return false;
  23012. });
  23013. });
  23014. Client client("localhost", get_port());
  23015. sse::SSEClient sse(client, "/multiline-data");
  23016. std::string received_data;
  23017. std::mutex data_mutex;
  23018. sse.on_message([&](const sse::SSEMessage &msg) {
  23019. std::lock_guard<std::mutex> lock(data_mutex);
  23020. received_data = msg.data;
  23021. });
  23022. sse.set_reconnect_interval(100);
  23023. sse.set_max_reconnect_attempts(1);
  23024. sse.start_async();
  23025. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23026. sse.stop();
  23027. std::lock_guard<std::mutex> lock(data_mutex);
  23028. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23029. }
  23030. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23031. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23032. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23033. DataSink &sink) {
  23034. if (offset == 0) {
  23035. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23036. sink.write(events.data(), events.size());
  23037. }
  23038. return false;
  23039. });
  23040. });
  23041. Client client("localhost", get_port());
  23042. sse::SSEClient sse(client, "/empty-data-lines");
  23043. std::mutex mutex;
  23044. std::condition_variable cv;
  23045. std::vector<std::string> received;
  23046. sse.on_message([&](const sse::SSEMessage &msg) {
  23047. std::lock_guard<std::mutex> lock(mutex);
  23048. received.push_back(msg.data);
  23049. cv.notify_all();
  23050. });
  23051. sse.set_max_reconnect_attempts(1);
  23052. sse.start_async();
  23053. {
  23054. std::unique_lock<std::mutex> lock(mutex);
  23055. cv.wait_for(lock, std::chrono::seconds(2),
  23056. [&] { return received.size() >= 3; });
  23057. }
  23058. sse.stop();
  23059. ASSERT_GE(received.size(), 3u);
  23060. EXPECT_EQ(received[0], "");
  23061. EXPECT_EQ(received[1], "\nhello");
  23062. EXPECT_EQ(received[2], "");
  23063. }
  23064. // Test: Auto-reconnect after server disconnection
  23065. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23066. std::atomic<int> connection_count{0};
  23067. std::atomic<int> message_count{0};
  23068. // Endpoint that sends one event and closes, forcing reconnect
  23069. server_->Get("/reconnect-test",
  23070. [&connection_count](const Request &, Response &res) {
  23071. connection_count.fetch_add(1);
  23072. res.set_chunked_content_provider(
  23073. "text/event-stream", [](size_t offset, DataSink &sink) {
  23074. if (offset == 0) {
  23075. std::string event = "data: hello\n\n";
  23076. sink.write(event.data(), event.size());
  23077. }
  23078. return false; // Close connection after sending
  23079. });
  23080. });
  23081. Client client("localhost", get_port());
  23082. sse::SSEClient sse(client, "/reconnect-test");
  23083. sse.on_message([&message_count](const sse::SSEMessage &) {
  23084. message_count.fetch_add(1);
  23085. });
  23086. sse.set_reconnect_interval(100);
  23087. sse.set_max_reconnect_attempts(3);
  23088. sse.start_async();
  23089. // Wait long enough for multiple reconnects
  23090. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23091. sse.stop();
  23092. // Should have connected multiple times (initial + reconnects)
  23093. EXPECT_GE(connection_count.load(), 2);
  23094. // Should have received messages from multiple connections
  23095. EXPECT_GE(message_count.load(), 2);
  23096. }
  23097. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23098. std::atomic<int> connection_count{0};
  23099. // Neither Content-Length nor chunked: the close ends the stream
  23100. server_->Get("/close-delimited",
  23101. [&connection_count](const Request &, Response &res) {
  23102. connection_count.fetch_add(1);
  23103. res.set_content_provider(
  23104. "text/event-stream", [](size_t offset, DataSink &sink) {
  23105. if (offset == 0) {
  23106. std::string event = "data: hello\n\n";
  23107. sink.write(event.data(), event.size());
  23108. } else {
  23109. sink.done();
  23110. }
  23111. return true;
  23112. });
  23113. });
  23114. Client client("localhost", get_port());
  23115. sse::SSEClient sse(client, "/close-delimited");
  23116. std::atomic<int> error_count{0};
  23117. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23118. sse.set_reconnect_interval(100);
  23119. sse.start_async();
  23120. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23121. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23122. }
  23123. sse.stop();
  23124. // Reconnects as after any end of the stream, but reports no error
  23125. EXPECT_GE(connection_count.load(), 2);
  23126. EXPECT_EQ(0, error_count.load());
  23127. }
  23128. // Test: A retry field that is not all ASCII digits is ignored
  23129. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  23130. std::atomic<int> connection_count{0};
  23131. server_->Get("/bad-retry",
  23132. [&connection_count](const Request &, Response &res) {
  23133. connection_count.fetch_add(1);
  23134. res.set_chunked_content_provider(
  23135. "text/event-stream", [](size_t offset, DataSink &sink) {
  23136. if (offset == 0) {
  23137. std::string event = "retry: -1\ndata: hello\n\n";
  23138. sink.write(event.data(), event.size());
  23139. }
  23140. return false;
  23141. });
  23142. });
  23143. Client client("localhost", get_port());
  23144. sse::SSEClient sse(client, "/bad-retry");
  23145. sse.set_reconnect_interval(10000);
  23146. sse.start_async();
  23147. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23148. sse.stop();
  23149. EXPECT_EQ(connection_count.load(), 1);
  23150. }
  23151. // Test: A retry field of all ASCII digits sets the reconnection time
  23152. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23153. std::mutex mutex;
  23154. std::condition_variable cv;
  23155. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23156. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23157. {
  23158. std::lock_guard<std::mutex> lock(mutex);
  23159. connected_at.push_back(std::chrono::steady_clock::now());
  23160. cv.notify_all();
  23161. }
  23162. res.set_chunked_content_provider(
  23163. "text/event-stream", [](size_t offset, DataSink &sink) {
  23164. if (offset == 0) {
  23165. std::string event = "retry: 0\ndata: hello\n\n";
  23166. sink.write(event.data(), event.size());
  23167. }
  23168. return false;
  23169. });
  23170. });
  23171. Client client("localhost", get_port());
  23172. sse::SSEClient sse(client, "/zero-retry");
  23173. sse.set_reconnect_interval(10000);
  23174. sse.start_async();
  23175. {
  23176. std::unique_lock<std::mutex> lock(mutex);
  23177. cv.wait_for(lock, std::chrono::seconds(5),
  23178. [&] { return connected_at.size() >= 2; });
  23179. }
  23180. sse.stop();
  23181. // The server-supplied interval is applied, but never below 100ms, so
  23182. // "retry: 0" does not cause a busy reconnect loop
  23183. std::lock_guard<std::mutex> lock(mutex);
  23184. ASSERT_GE(connected_at.size(), 2u);
  23185. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23186. connected_at[1] - connected_at[0])
  23187. .count();
  23188. EXPECT_GE(interval_ms, 100);
  23189. }
  23190. // Test: Last-Event-ID sent on reconnect
  23191. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23192. std::atomic<int> connection_count{0};
  23193. std::vector<std::string> received_last_event_ids;
  23194. std::mutex id_mutex;
  23195. // Endpoint that checks Last-Event-ID header and sends event with ID
  23196. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23197. int conn = connection_count.fetch_add(1);
  23198. // Capture the Last-Event-ID header from each connection
  23199. {
  23200. std::lock_guard<std::mutex> lock(id_mutex);
  23201. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23202. }
  23203. res.set_chunked_content_provider(
  23204. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23205. if (offset == 0) {
  23206. std::string event =
  23207. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23208. sink.write(event.data(), event.size());
  23209. }
  23210. return false;
  23211. });
  23212. });
  23213. Client client("localhost", get_port());
  23214. sse::SSEClient sse(client, "/reconnect-with-id");
  23215. sse.set_reconnect_interval(100);
  23216. sse.set_max_reconnect_attempts(3);
  23217. sse.start_async();
  23218. // Wait for at least 2 connections
  23219. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23220. sse.stop();
  23221. // Verify behavior
  23222. std::lock_guard<std::mutex> lock(id_mutex);
  23223. EXPECT_GE(received_last_event_ids.size(), 2u);
  23224. // First connection should have no Last-Event-ID
  23225. if (!received_last_event_ids.empty()) {
  23226. EXPECT_EQ(received_last_event_ids[0], "");
  23227. }
  23228. // Second connection should have Last-Event-ID from first connection
  23229. if (received_last_event_ids.size() >= 2) {
  23230. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23231. }
  23232. }
  23233. // Test: set_headers updates headers used on reconnect
  23234. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23235. std::vector<std::string> received_tokens;
  23236. std::mutex token_mutex;
  23237. // Endpoint that captures Authorization header
  23238. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23239. {
  23240. std::lock_guard<std::mutex> lock(token_mutex);
  23241. received_tokens.push_back(req.get_header_value("Authorization"));
  23242. }
  23243. res.set_chunked_content_provider(
  23244. "text/event-stream", [](size_t offset, DataSink &sink) {
  23245. if (offset == 0) {
  23246. std::string event = "data: hello\n\n";
  23247. sink.write(event.data(), event.size());
  23248. }
  23249. return false; // Close connection to trigger reconnect
  23250. });
  23251. });
  23252. Client client("localhost", get_port());
  23253. Headers headers = {{"Authorization", "Bearer old-token"}};
  23254. sse::SSEClient sse(client, "/auth-check", headers);
  23255. // Update headers on each successful connection
  23256. sse.on_open(
  23257. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23258. sse.set_reconnect_interval(100);
  23259. sse.set_max_reconnect_attempts(3);
  23260. sse.start_async();
  23261. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23262. sse.stop();
  23263. std::lock_guard<std::mutex> lock(token_mutex);
  23264. ASSERT_GE(received_tokens.size(), 2u);
  23265. // First connection uses original header
  23266. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23267. // Second connection uses updated header from set_headers
  23268. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23269. }
  23270. // Test: 401 allows reconnection (so on_error can refresh headers)
  23271. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23272. std::atomic<int> connection_count{0};
  23273. // Endpoint: returns 401 on first attempt, 200 on second
  23274. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23275. int conn = connection_count.fetch_add(1);
  23276. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23277. res.status = StatusCode::Unauthorized_401;
  23278. res.set_content("Unauthorized", "text/plain");
  23279. return;
  23280. }
  23281. res.set_chunked_content_provider(
  23282. "text/event-stream", [](size_t offset, DataSink &sink) {
  23283. if (offset == 0) {
  23284. std::string event = "data: authenticated\n\n";
  23285. sink.write(event.data(), event.size());
  23286. }
  23287. return false;
  23288. });
  23289. });
  23290. Client client("localhost", get_port());
  23291. Headers headers = {{"Authorization", "Bearer expired"}};
  23292. sse::SSEClient sse(client, "/auth-retry", headers);
  23293. std::atomic<bool> message_received{false};
  23294. // Refresh token on error
  23295. sse.on_error(
  23296. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23297. sse.on_message([&](const sse::SSEMessage &msg) {
  23298. if (msg.data == "authenticated") { message_received.store(true); }
  23299. });
  23300. sse.set_reconnect_interval(100);
  23301. sse.set_max_reconnect_attempts(3);
  23302. sse.start_async();
  23303. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23304. sse.stop();
  23305. // Should have reconnected after 401 and succeeded with new token
  23306. EXPECT_GE(connection_count.load(), 2);
  23307. EXPECT_TRUE(message_received.load());
  23308. }
  23309. TEST(Issue2318Test, EmptyHostString) {
  23310. {
  23311. httplib::Client cli_empty("", PORT);
  23312. auto res = cli_empty.Get("/");
  23313. ASSERT_FALSE(res);
  23314. EXPECT_EQ(httplib::Error::Connection, res.error());
  23315. }
  23316. {
  23317. httplib::Client cli(" ", PORT);
  23318. auto res = cli.Get("/");
  23319. ASSERT_FALSE(res);
  23320. EXPECT_EQ(httplib::Error::Connection, res.error());
  23321. }
  23322. }
  23323. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23324. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23325. Server svr;
  23326. // Set a small payload limit (1KB)
  23327. svr.set_payload_max_length(1024);
  23328. svr.Post("/test", [&](const Request &req, Response &res) {
  23329. res.set_content("Body size: " + std::to_string(req.body.size()),
  23330. "text/plain");
  23331. });
  23332. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23333. auto se = detail::scope_exit([&] {
  23334. svr.stop();
  23335. listen_thread.join();
  23336. });
  23337. svr.wait_until_ready();
  23338. // Create data that compresses well but exceeds limit when decompressed
  23339. // 8KB of repeated null bytes compresses to a very small size
  23340. std::string original_data(8 * 1024, '\0');
  23341. // Compress the data using gzip
  23342. std::string compressed_data;
  23343. detail::gzip_compressor compressor;
  23344. compressor.compress(original_data.data(), original_data.size(), true,
  23345. [&](const char *data, size_t size) {
  23346. compressed_data.append(data, size);
  23347. return true;
  23348. });
  23349. // Verify compression worked (compressed should be much smaller)
  23350. ASSERT_LT(compressed_data.size(), original_data.size());
  23351. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23352. // Send compressed data with Content-Encoding: gzip
  23353. Client cli(HOST, PORT);
  23354. Headers headers = {{"Content-Encoding", "gzip"}};
  23355. auto res =
  23356. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23357. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23359. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23360. }
  23361. #endif
  23362. // ============================================================================
  23363. // OpenSSL-Specific Tests
  23364. // ============================================================================
  23365. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23366. X509 *readCertificate(const std::string &strFileName) {
  23367. std::ifstream inStream(strFileName);
  23368. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23369. std::istreambuf_iterator<char>());
  23370. if (strCertPEM.empty()) return (nullptr);
  23371. BIO *pbCert = BIO_new(BIO_s_mem());
  23372. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23373. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23374. BIO_free(pbCert);
  23375. return (pCert);
  23376. }
  23377. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23378. std::ifstream inStream(strFileName);
  23379. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23380. std::istreambuf_iterator<char>());
  23381. if (strPrivateKeyPEM.empty()) return (nullptr);
  23382. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23383. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23384. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23385. BIO_free(pbPrivKey);
  23386. return (pPrivateKey);
  23387. }
  23388. TEST(BindServerTest, UpdateCerts) {
  23389. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23390. int port = svr.bind_to_any_port("0.0.0.0");
  23391. ASSERT_TRUE(svr.is_valid());
  23392. ASSERT_TRUE(port > 0);
  23393. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23394. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23395. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23396. ASSERT_TRUE(cert != nullptr);
  23397. ASSERT_TRUE(ca_cert != nullptr);
  23398. ASSERT_TRUE(key != nullptr);
  23399. X509_STORE *cert_store = X509_STORE_new();
  23400. X509_STORE_add_cert(cert_store, ca_cert);
  23401. // svr.update_certs(cert, key, cert_store); // deprecated
  23402. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23403. CLIENT_CA_CERT_FILE);
  23404. ASSERT_TRUE(svr.is_valid());
  23405. svr.stop();
  23406. X509_STORE_free(cert_store);
  23407. X509_free(cert);
  23408. X509_free(ca_cert);
  23409. EVP_PKEY_free(key);
  23410. }
  23411. // Test that update_certs() updates client CA list correctly
  23412. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23413. // Start with file-based constructor
  23414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23415. ASSERT_TRUE(svr.is_valid());
  23416. // Initially no client CA list should be set
  23417. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23418. ASSERT_TRUE(ssl_ctx != nullptr);
  23419. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23420. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23421. // Now update with client CA (PEM string)
  23422. std::string cert_pem, key_pem, ca_pem;
  23423. read_file(SERVER_CERT_FILE, cert_pem);
  23424. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23425. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23426. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23427. ASSERT_TRUE(svr.is_valid());
  23428. // Now client CA list should be set
  23429. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23430. ASSERT_TRUE(ca_list_after != nullptr);
  23431. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23432. }
  23433. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23434. // Test that the file-path SSLServer constructor properly sets the client CA
  23435. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23437. ASSERT_TRUE(svr.is_valid());
  23438. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23439. ASSERT_TRUE(ssl_ctx != nullptr);
  23440. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23441. ASSERT_TRUE(ca_list != nullptr);
  23442. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23443. }
  23444. #endif
  23445. // ============================================================================
  23446. // MbedTLS-Specific Tests
  23447. // ============================================================================
  23448. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23449. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23450. using namespace httplib::tls;
  23451. // Track if callback was invoked
  23452. bool callback_invoked = false;
  23453. // The callback receives void* ctx which is actually MbedTlsContext*
  23454. // We can access the mbedtls_ssl_config via the context
  23455. auto setup_callback = [&callback_invoked](void *ctx) {
  23456. callback_invoked = true;
  23457. // Cast to MbedTlsContext* to access the ssl config
  23458. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23459. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23460. // Use static variables to hold certificate data (simplified for test)
  23461. static mbedtls_x509_crt own_cert;
  23462. static mbedtls_pk_context own_key;
  23463. static mbedtls_x509_crt ca_chain;
  23464. static bool initialized = false;
  23465. if (!initialized) {
  23466. mbedtls_x509_crt_init(&own_cert);
  23467. mbedtls_pk_init(&own_key);
  23468. mbedtls_x509_crt_init(&ca_chain);
  23469. // Load server certificate
  23470. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23471. return false;
  23472. }
  23473. // Load server private key.
  23474. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23475. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23476. #if MBEDTLS_VERSION_MAJOR == 3
  23477. ,
  23478. mbedtls_ctr_drbg_random, nullptr
  23479. #endif
  23480. ) != 0) {
  23481. return false;
  23482. }
  23483. // Load CA chain for client verification
  23484. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23485. return false;
  23486. }
  23487. initialized = true;
  23488. }
  23489. // Configure the SSL config
  23490. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23491. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23492. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23493. // Set minimum TLS version using mbedTLS native API
  23494. #if MBEDTLS_VERSION_MAJOR >= 3
  23495. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23496. #else
  23497. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23498. MBEDTLS_SSL_MINOR_VERSION_3);
  23499. #endif
  23500. return true;
  23501. };
  23502. SSLServer svr(setup_callback);
  23503. ASSERT_TRUE(svr.is_valid());
  23504. ASSERT_TRUE(callback_invoked);
  23505. svr.Get("/test", [&](const Request &req, Response &res) {
  23506. res.set_content("test", "text/plain");
  23507. auto cert = req.peer_cert();
  23508. ASSERT_TRUE(static_cast<bool>(cert));
  23509. auto common_name = cert.subject_cn();
  23510. EXPECT_EQ("Common Name", common_name);
  23511. });
  23512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23513. auto se = detail::scope_exit([&] {
  23514. svr.stop();
  23515. t.join();
  23516. ASSERT_FALSE(svr.is_running());
  23517. });
  23518. svr.wait_until_ready();
  23519. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23520. cli.enable_server_certificate_verification(false);
  23521. cli.set_connection_timeout(30);
  23522. auto res = cli.Get("/test");
  23523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23524. ASSERT_EQ(StatusCode::OK_200, res->status);
  23525. }
  23526. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23527. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23528. // keep-alive SSL session, which reads through that config in
  23529. // mbedtls_ssl_close_notify.
  23530. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23532. ASSERT_TRUE(svr.is_valid());
  23533. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23534. res.set_content("test", "text/plain");
  23535. });
  23536. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23537. auto se = detail::scope_exit([&] {
  23538. svr.stop();
  23539. t.join();
  23540. ASSERT_FALSE(svr.is_running());
  23541. });
  23542. svr.wait_until_ready();
  23543. {
  23544. SSLClient cli(HOST, PORT);
  23545. cli.enable_server_certificate_verification(false);
  23546. cli.set_keep_alive(true);
  23547. auto res = cli.Get("/test");
  23548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23549. ASSERT_EQ(StatusCode::OK_200, res->status);
  23550. // cli is destructed here with the keep-alive SSL session still open.
  23551. }
  23552. }
  23553. #endif
  23554. // WebSocket Tests
  23555. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23556. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23557. // defining the meaning of these bits has been negotiated.
  23558. auto make_frame = [](uint8_t first_byte) {
  23559. std::string frame;
  23560. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23561. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23562. frame += "Hello";
  23563. return frame;
  23564. };
  23565. // RSV1 set (0x40)
  23566. {
  23567. detail::BufferStream strm;
  23568. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23569. ws::Opcode opcode;
  23570. std::string payload;
  23571. bool fin;
  23572. EXPECT_EQ(
  23573. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23574. ws::impl::FrameRead::Fail);
  23575. }
  23576. // RSV2 set (0x20)
  23577. {
  23578. detail::BufferStream strm;
  23579. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23580. ws::Opcode opcode;
  23581. std::string payload;
  23582. bool fin;
  23583. EXPECT_EQ(
  23584. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23585. ws::impl::FrameRead::Fail);
  23586. }
  23587. // RSV3 set (0x10)
  23588. {
  23589. detail::BufferStream strm;
  23590. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23591. ws::Opcode opcode;
  23592. std::string payload;
  23593. bool fin;
  23594. EXPECT_EQ(
  23595. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23596. ws::impl::FrameRead::Fail);
  23597. }
  23598. // No RSV bits set - should succeed
  23599. {
  23600. detail::BufferStream strm;
  23601. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23602. ws::Opcode opcode;
  23603. std::string payload;
  23604. bool fin;
  23605. EXPECT_EQ(
  23606. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23607. ws::impl::FrameRead::Ok);
  23608. EXPECT_EQ(ws::Opcode::Text, opcode);
  23609. EXPECT_EQ("Hello", payload);
  23610. EXPECT_TRUE(fin);
  23611. }
  23612. }
  23613. TEST(WebSocketTest, ControlFrameValidation) {
  23614. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23615. // payload length <= 125.
  23616. // Ping with FIN=0 - must be rejected
  23617. {
  23618. detail::BufferStream strm;
  23619. std::string frame;
  23620. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23621. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23622. strm.write(frame.data(), frame.size());
  23623. ws::Opcode opcode;
  23624. std::string payload;
  23625. bool fin;
  23626. EXPECT_EQ(
  23627. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23628. ws::impl::FrameRead::Fail);
  23629. }
  23630. // Close with FIN=0 - must be rejected
  23631. {
  23632. detail::BufferStream strm;
  23633. std::string frame;
  23634. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23635. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23636. strm.write(frame.data(), frame.size());
  23637. ws::Opcode opcode;
  23638. std::string payload;
  23639. bool fin;
  23640. EXPECT_EQ(
  23641. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23642. ws::impl::FrameRead::Fail);
  23643. }
  23644. // Ping with payload_len=126 (extended length) - must be rejected
  23645. {
  23646. detail::BufferStream strm;
  23647. std::string frame;
  23648. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23649. frame += static_cast<char>(126); // payload_len=126 (>125)
  23650. frame += static_cast<char>(0x00); // extended length high byte
  23651. frame += static_cast<char>(126); // extended length low byte
  23652. frame += std::string(126, 'x');
  23653. strm.write(frame.data(), frame.size());
  23654. ws::Opcode opcode;
  23655. std::string payload;
  23656. bool fin;
  23657. EXPECT_EQ(
  23658. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23659. ws::impl::FrameRead::Fail);
  23660. }
  23661. // Ping with FIN=1 and payload_len=125 - should succeed
  23662. {
  23663. detail::BufferStream strm;
  23664. std::string frame;
  23665. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23666. frame += static_cast<char>(125); // payload_len=125
  23667. frame += std::string(125, 'x');
  23668. strm.write(frame.data(), frame.size());
  23669. ws::Opcode opcode;
  23670. std::string payload;
  23671. bool fin;
  23672. EXPECT_EQ(
  23673. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23674. ws::impl::FrameRead::Ok);
  23675. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23676. EXPECT_EQ(125u, payload.size());
  23677. EXPECT_TRUE(fin);
  23678. }
  23679. }
  23680. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23681. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23682. // length MUST be 0.
  23683. // MSB set - must be rejected
  23684. {
  23685. detail::BufferStream strm;
  23686. std::string frame;
  23687. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23688. frame += static_cast<char>(127); // 64-bit extended length
  23689. frame += static_cast<char>(0x80); // MSB set (invalid)
  23690. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23691. strm.write(frame.data(), frame.size());
  23692. ws::Opcode opcode;
  23693. std::string payload;
  23694. bool fin;
  23695. EXPECT_EQ(
  23696. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23697. ws::impl::FrameRead::Fail);
  23698. }
  23699. // MSB clear - should pass length parsing (will be rejected by max_len,
  23700. // but that's a different check; use a small length to verify)
  23701. {
  23702. detail::BufferStream strm;
  23703. std::string frame;
  23704. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23705. frame += static_cast<char>(127); // 64-bit extended length
  23706. frame += std::string(7, '\0'); // high bytes = 0
  23707. frame += static_cast<char>(0x03); // length = 3
  23708. frame += "abc";
  23709. strm.write(frame.data(), frame.size());
  23710. ws::Opcode opcode;
  23711. std::string payload;
  23712. bool fin;
  23713. EXPECT_EQ(
  23714. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23715. ws::impl::FrameRead::Ok);
  23716. EXPECT_EQ(ws::Opcode::Text, opcode);
  23717. EXPECT_EQ("abc", payload);
  23718. }
  23719. }
  23720. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23721. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23722. // Valid UTF-8
  23723. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23724. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23725. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23726. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23727. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23728. // Invalid UTF-8
  23729. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23730. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23731. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23732. EXPECT_FALSE(
  23733. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23734. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23735. }
  23736. TEST(WebSocketTest, ConnectAndDisconnect) {
  23737. Server svr;
  23738. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23739. std::string msg;
  23740. while (ws.read(msg)) {}
  23741. });
  23742. auto port = svr.bind_to_any_port(HOST);
  23743. std::thread t([&]() { svr.listen_after_bind(); });
  23744. svr.wait_until_ready();
  23745. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23746. auto res = client.connect();
  23747. ASSERT_TRUE(res);
  23748. EXPECT_EQ(Error::Success, res.error());
  23749. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23750. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23751. EXPECT_TRUE(client.is_open());
  23752. client.close();
  23753. EXPECT_FALSE(client.is_open());
  23754. svr.stop();
  23755. t.join();
  23756. }
  23757. TEST(WebSocketTest, ValidURL) {
  23758. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23759. EXPECT_TRUE(ws1.is_valid());
  23760. ws::WebSocketClient ws2("ws://example.com/path");
  23761. EXPECT_TRUE(ws2.is_valid());
  23762. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23763. EXPECT_TRUE(ws3.is_valid());
  23764. #ifdef CPPHTTPLIB_SSL_ENABLED
  23765. ws::WebSocketClient wss1("wss://example.com/path");
  23766. EXPECT_TRUE(wss1.is_valid());
  23767. ws::WebSocketClient wss2("wss://example.com:443/path");
  23768. EXPECT_TRUE(wss2.is_valid());
  23769. #endif
  23770. }
  23771. TEST(WebSocketTest, InvalidURL) {
  23772. // No scheme
  23773. ws::WebSocketClient ws1("localhost:8080/path");
  23774. EXPECT_FALSE(ws1.is_valid());
  23775. // No path
  23776. ws::WebSocketClient ws2("ws://localhost:8080");
  23777. EXPECT_FALSE(ws2.is_valid());
  23778. // Empty string
  23779. ws::WebSocketClient ws3("");
  23780. EXPECT_FALSE(ws3.is_valid());
  23781. // Missing host
  23782. ws::WebSocketClient ws4("ws://:8080/path");
  23783. EXPECT_FALSE(ws4.is_valid());
  23784. // Port number overflow — should not crash
  23785. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23786. EXPECT_FALSE(ws5.is_valid());
  23787. // Port out of range
  23788. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23789. EXPECT_FALSE(ws6.is_valid());
  23790. }
  23791. TEST(WebSocketTest, UnsupportedScheme) {
  23792. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23793. ws::WebSocketClient ws1("http://localhost:8080/path");
  23794. EXPECT_FALSE(ws1.is_valid());
  23795. ws::WebSocketClient ws2("https://localhost:8080/path");
  23796. EXPECT_FALSE(ws2.is_valid());
  23797. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23798. EXPECT_FALSE(ws3.is_valid());
  23799. #else
  23800. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23801. std::invalid_argument);
  23802. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23803. std::invalid_argument);
  23804. #endif
  23805. }
  23806. TEST(WebSocketTest, ConnectWhenInvalid) {
  23807. ws::WebSocketClient ws("not a valid url");
  23808. EXPECT_FALSE(ws.is_valid());
  23809. auto res = ws.connect();
  23810. EXPECT_FALSE(res);
  23811. EXPECT_EQ(Error::Connection, res.error());
  23812. EXPECT_EQ(-1, res.status());
  23813. }
  23814. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23815. // Grab a port that is free, then close it again so nothing listens there
  23816. Server svr;
  23817. auto port = svr.bind_to_any_port(HOST);
  23818. svr.stop();
  23819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23820. auto res = client.connect();
  23821. ASSERT_FALSE(res);
  23822. EXPECT_EQ(Error::Connection, res.error());
  23823. EXPECT_EQ(-1, res.status());
  23824. }
  23825. TEST(WebSocketTest, DefaultPort) {
  23826. ws::WebSocketClient ws1("ws://example.com/path");
  23827. EXPECT_TRUE(ws1.is_valid());
  23828. // ws:// defaults to port 80 (verified by successful parse)
  23829. #ifdef CPPHTTPLIB_SSL_ENABLED
  23830. ws::WebSocketClient ws2("wss://example.com/path");
  23831. EXPECT_TRUE(ws2.is_valid());
  23832. // wss:// defaults to port 443 (verified by successful parse)
  23833. #endif
  23834. }
  23835. TEST(WebSocketTest, IPv6LiteralAddress) {
  23836. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23837. EXPECT_TRUE(ws1.is_valid());
  23838. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23839. EXPECT_TRUE(ws2.is_valid());
  23840. }
  23841. TEST(WebSocketTest, ComplexPath) {
  23842. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23843. EXPECT_TRUE(ws1.is_valid());
  23844. ws::WebSocketClient ws2("ws://localhost:8080/");
  23845. EXPECT_TRUE(ws2.is_valid());
  23846. }
  23847. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23848. Server svr;
  23849. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23850. std::string msg;
  23851. while (ws.read(msg)) {}
  23852. });
  23853. auto port = svr.bind_to_any_port(HOST);
  23854. std::thread t([&]() { svr.listen_after_bind(); });
  23855. svr.wait_until_ready();
  23856. auto another_host = "example.com";
  23857. auto wrong_ip = "192.0.2.1";
  23858. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23859. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  23860. ASSERT_TRUE(client.connect());
  23861. EXPECT_TRUE(client.is_open());
  23862. client.close();
  23863. svr.stop();
  23864. t.join();
  23865. }
  23866. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23867. Server svr;
  23868. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23869. std::string msg;
  23870. while (ws.read(msg)) {}
  23871. });
  23872. auto port = svr.bind_to_any_port(HOST);
  23873. std::thread t([&]() { svr.listen_after_bind(); });
  23874. svr.wait_until_ready();
  23875. auto wrong_ip = "192.0.2.1";
  23876. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23877. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  23878. client.set_connection_timeout(1);
  23879. client.set_read_timeout(1);
  23880. client.set_write_timeout(1);
  23881. EXPECT_FALSE(client.connect());
  23882. EXPECT_FALSE(client.is_open());
  23883. svr.stop();
  23884. t.join();
  23885. }
  23886. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23887. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23888. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23889. // (RFC 6761) is only a map key and the Host header value.
  23890. auto host = "target.invalid";
  23891. Server svr;
  23892. std::string received_host;
  23893. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23894. received_host = req.get_header_value("Host");
  23895. std::string msg;
  23896. while (ws.read(msg)) {}
  23897. });
  23898. auto port = svr.bind_to_any_port(HOST);
  23899. std::thread t([&]() { svr.listen_after_bind(); });
  23900. // ASSERT_* below returns from the test body, which would leave t joinable
  23901. // and make ~thread call std::terminate.
  23902. auto se = detail::scope_exit([&] {
  23903. svr.stop();
  23904. if (t.joinable()) { t.join(); }
  23905. });
  23906. svr.wait_until_ready();
  23907. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23908. std::to_string(port) + "/ws");
  23909. client.set_direct_hostname_addr_map({{host, HOST}});
  23910. ASSERT_TRUE(client.connect());
  23911. EXPECT_TRUE(client.is_open());
  23912. client.close();
  23913. svr.stop();
  23914. t.join();
  23915. // The mapping only redirects the connection; the identity stays host_.
  23916. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23917. }
  23918. class WebSocketIntegrationTest : public ::testing::Test {
  23919. protected:
  23920. void SetUp() override {
  23921. server_ = httplib::detail::make_unique<Server>();
  23922. setup_server();
  23923. start_server();
  23924. }
  23925. void TearDown() override {
  23926. server_->stop();
  23927. if (server_thread_.joinable()) { server_thread_.join(); }
  23928. }
  23929. void setup_server() {
  23930. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23931. std::string msg;
  23932. ws::ReadResult ret;
  23933. while ((ret = ws.read(msg))) {
  23934. if (ret == ws::Binary) {
  23935. ws.send(msg.data(), msg.size());
  23936. } else {
  23937. ws.send(msg);
  23938. }
  23939. }
  23940. });
  23941. server_->WebSocket("/ws-echo-string",
  23942. [](const Request &, ws::WebSocket &ws) {
  23943. std::string msg;
  23944. while (ws.read(msg)) {
  23945. ws.send("echo: " + msg);
  23946. }
  23947. });
  23948. server_->WebSocket(
  23949. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23950. // Echo back request metadata
  23951. ws.send("path:" + req.path);
  23952. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23953. std::string msg;
  23954. while (ws.read(msg)) {}
  23955. });
  23956. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23957. std::string msg;
  23958. ws.read(msg); // wait for a message
  23959. ws.close();
  23960. });
  23961. server_->WebSocket("/ws-close-status",
  23962. [](const Request &, ws::WebSocket &ws) {
  23963. std::string msg;
  23964. ws.read(msg); // wait for a message
  23965. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23966. });
  23967. server_->WebSocket(
  23968. "/ws-subprotocol",
  23969. [](const Request &, ws::WebSocket &ws) {
  23970. std::string msg;
  23971. while (ws.read(msg)) {
  23972. ws.send(msg);
  23973. }
  23974. },
  23975. [](const std::vector<std::string> &protocols) -> std::string {
  23976. for (const auto &p : protocols) {
  23977. if (p == "graphql-ws") { return p; }
  23978. }
  23979. return "";
  23980. });
  23981. server_->WebSocket(
  23982. "/ws-subprotocol-unoffered",
  23983. [](const Request &, ws::WebSocket &ws) {
  23984. std::string msg;
  23985. while (ws.read(msg)) {
  23986. ws.send(msg);
  23987. }
  23988. },
  23989. [](const std::vector<std::string> &) -> std::string {
  23990. return "admin";
  23991. });
  23992. }
  23993. void start_server() {
  23994. port_ = server_->bind_to_any_port(HOST);
  23995. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23996. server_->wait_until_ready();
  23997. }
  23998. std::unique_ptr<Server> server_;
  23999. std::thread server_thread_;
  24000. int port_ = 0;
  24001. };
  24002. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24004. "/ws-echo");
  24005. ASSERT_TRUE(client.connect());
  24006. ASSERT_TRUE(client.is_open());
  24007. ASSERT_TRUE(client.send("Hello WebSocket"));
  24008. std::string msg;
  24009. EXPECT_EQ(ws::Text, client.read(msg));
  24010. EXPECT_EQ("Hello WebSocket", msg);
  24011. client.close();
  24012. }
  24013. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24015. "/ws-echo");
  24016. ASSERT_TRUE(client.connect());
  24017. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24018. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24019. std::string msg;
  24020. EXPECT_EQ(ws::Binary, client.read(msg));
  24021. EXPECT_EQ(binary_data, msg);
  24022. client.close();
  24023. }
  24024. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24026. "/ws-echo");
  24027. ASSERT_TRUE(client.connect());
  24028. for (int i = 0; i < 10; i++) {
  24029. auto text = "message " + std::to_string(i);
  24030. ASSERT_TRUE(client.send(text));
  24031. std::string msg;
  24032. ASSERT_TRUE(client.read(msg));
  24033. EXPECT_EQ(text, msg);
  24034. }
  24035. client.close();
  24036. }
  24037. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24039. "/ws-close");
  24040. ASSERT_TRUE(client.connect());
  24041. // Send a message to trigger the server to close
  24042. ASSERT_TRUE(client.send("trigger close"));
  24043. // The server will close, so read should return false
  24044. std::string msg;
  24045. EXPECT_FALSE(client.read(msg));
  24046. EXPECT_FALSE(client.is_open());
  24047. }
  24048. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24050. "/ws-echo");
  24051. ASSERT_TRUE(client.connect());
  24052. // 128KB message
  24053. std::string large_data(128 * 1024, 'X');
  24054. ASSERT_TRUE(client.send(large_data));
  24055. std::string msg;
  24056. ASSERT_TRUE(client.read(msg));
  24057. EXPECT_EQ(large_data, msg);
  24058. client.close();
  24059. }
  24060. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24062. "/ws-echo");
  24063. ASSERT_TRUE(client.connect());
  24064. const int num_threads = 4;
  24065. std::vector<std::thread> threads;
  24066. std::atomic<int> send_count{0};
  24067. for (int t = 0; t < num_threads; t++) {
  24068. threads.emplace_back([&client, &send_count, t]() {
  24069. for (int i = 0; i < 5; i++) {
  24070. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24071. if (client.send(text)) { send_count++; }
  24072. }
  24073. });
  24074. }
  24075. for (auto &th : threads) {
  24076. th.join();
  24077. }
  24078. int received = 0;
  24079. std::string msg;
  24080. while (received < send_count.load()) {
  24081. if (!client.read(msg)) { break; }
  24082. received++;
  24083. }
  24084. EXPECT_EQ(send_count.load(), received);
  24085. client.close();
  24086. }
  24087. TEST_F(WebSocketIntegrationTest, ReadString) {
  24088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24089. "/ws-echo-string");
  24090. ASSERT_TRUE(client.connect());
  24091. ASSERT_TRUE(client.send("hello"));
  24092. std::string msg;
  24093. ASSERT_TRUE(client.read(msg));
  24094. EXPECT_EQ("echo: hello", msg);
  24095. ASSERT_TRUE(client.send("world"));
  24096. ASSERT_TRUE(client.read(msg));
  24097. EXPECT_EQ("echo: world", msg);
  24098. client.close();
  24099. }
  24100. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24101. Headers headers = {{"X-Test-Header", "test-value"}};
  24102. ws::WebSocketClient client(
  24103. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24104. ASSERT_TRUE(client.connect());
  24105. std::string msg;
  24106. ASSERT_TRUE(client.read(msg));
  24107. EXPECT_EQ("path:/ws-request-info", msg);
  24108. ASSERT_TRUE(client.read(msg));
  24109. EXPECT_EQ("header:test-value", msg);
  24110. client.close();
  24111. }
  24112. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24114. "/ws-echo");
  24115. client.set_read_timeout(1, 0); // 1 second
  24116. ASSERT_TRUE(client.connect());
  24117. // Don't send anything — server echo handler waits for a message, so read()
  24118. // should time out. The connection survives it: nothing was consumed.
  24119. std::string msg;
  24120. EXPECT_EQ(client.read(msg), ws::Timeout);
  24121. EXPECT_TRUE(client.is_open());
  24122. // And it is still usable afterwards.
  24123. EXPECT_TRUE(client.send("after timeout"));
  24124. EXPECT_EQ(client.read(msg), ws::Text);
  24125. EXPECT_EQ(msg, "after timeout");
  24126. }
  24127. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24128. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24129. "/ws-echo");
  24130. client.set_read_timeout(1, 0);
  24131. ASSERT_TRUE(client.connect());
  24132. ASSERT_TRUE(client.send("first"));
  24133. std::string msg;
  24134. ASSERT_EQ(client.read(msg), ws::Text);
  24135. ASSERT_EQ(msg, "first");
  24136. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24137. // not be used with a read timeout: it would reprocess the previous message.
  24138. EXPECT_EQ(client.read(msg), ws::Timeout);
  24139. EXPECT_EQ(msg, "first");
  24140. }
  24141. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24142. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24143. "/ws-echo");
  24144. ASSERT_TRUE(client.connect());
  24145. // Setting it once the connection is open reaches the live stream, not just
  24146. // the seed for the next connect().
  24147. client.set_read_timeout(1, 0);
  24148. std::string msg;
  24149. EXPECT_EQ(client.read(msg), ws::Timeout);
  24150. EXPECT_TRUE(client.is_open());
  24151. }
  24152. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24153. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24154. "/ws-echo");
  24155. client.set_read_timeout(5, 0);
  24156. ASSERT_TRUE(client.connect());
  24157. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24158. // The server should reject it and close the connection.
  24159. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24160. client.send(oversized);
  24161. // The server's read() should have failed due to payload limit,
  24162. // so our read() should return false (connection closed).
  24163. std::string msg;
  24164. EXPECT_FALSE(client.read(msg));
  24165. }
  24166. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24168. "/ws-echo");
  24169. client.set_read_timeout(10, 0);
  24170. ASSERT_TRUE(client.connect());
  24171. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24172. // This should succeed.
  24173. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24174. ASSERT_TRUE(client.send(at_limit));
  24175. std::string msg;
  24176. ASSERT_TRUE(client.read(msg));
  24177. EXPECT_EQ(at_limit.size(), msg.size());
  24178. client.close();
  24179. }
  24180. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24182. "/nonexistent");
  24183. auto res = client.connect();
  24184. EXPECT_FALSE(res);
  24185. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24186. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24187. EXPECT_FALSE(client.is_open());
  24188. }
  24189. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24190. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24191. "/ws-echo");
  24192. ASSERT_TRUE(client.connect());
  24193. ASSERT_TRUE(client.send(""));
  24194. std::string msg;
  24195. EXPECT_EQ(ws::Text, client.read(msg));
  24196. EXPECT_EQ("", msg);
  24197. client.close();
  24198. }
  24199. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24201. "/ws-echo");
  24202. // First connection
  24203. ASSERT_TRUE(client.connect());
  24204. ASSERT_TRUE(client.send("first"));
  24205. std::string msg;
  24206. ASSERT_TRUE(client.read(msg));
  24207. EXPECT_EQ("first", msg);
  24208. client.close();
  24209. EXPECT_FALSE(client.is_open());
  24210. // Reconnect using the same client object
  24211. ASSERT_TRUE(client.connect());
  24212. ASSERT_TRUE(client.is_open());
  24213. ASSERT_TRUE(client.send("second"));
  24214. ASSERT_TRUE(client.read(msg));
  24215. EXPECT_EQ("second", msg);
  24216. client.close();
  24217. }
  24218. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24219. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24220. "/ws-close-status");
  24221. ASSERT_TRUE(client.connect());
  24222. // Trigger the server to close with GoingAway status
  24223. ASSERT_TRUE(client.send("trigger"));
  24224. // read() should return false after receiving the close frame
  24225. std::string msg;
  24226. EXPECT_FALSE(client.read(msg));
  24227. EXPECT_FALSE(client.is_open());
  24228. }
  24229. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24231. "/ws-echo");
  24232. ASSERT_TRUE(client.connect());
  24233. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24234. EXPECT_FALSE(client.is_open());
  24235. }
  24236. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24237. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24238. ws::WebSocketClient client(
  24239. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24240. ASSERT_TRUE(client.connect());
  24241. // Server should have selected graphql-ws
  24242. EXPECT_EQ("graphql-ws", client.subprotocol());
  24243. client.close();
  24244. }
  24245. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24246. Headers headers;
  24247. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24248. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24249. ws::WebSocketClient client(
  24250. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24251. ASSERT_TRUE(client.connect());
  24252. // The offer on the second field line counts too, so graphql-ws is selected
  24253. EXPECT_EQ("graphql-ws", client.subprotocol());
  24254. client.close();
  24255. }
  24256. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24257. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24258. ws::WebSocketClient client(
  24259. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24260. ASSERT_TRUE(client.connect());
  24261. // Server should not have selected any subprotocol
  24262. EXPECT_TRUE(client.subprotocol().empty());
  24263. client.close();
  24264. }
  24265. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24266. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24268. "/ws-subprotocol-unoffered",
  24269. headers);
  24270. ASSERT_TRUE(client.connect());
  24271. EXPECT_TRUE(client.subprotocol().empty());
  24272. client.close();
  24273. }
  24274. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24275. // Connect without requesting any subprotocol
  24276. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24277. "/ws-subprotocol");
  24278. ASSERT_TRUE(client.connect());
  24279. EXPECT_TRUE(client.subprotocol().empty());
  24280. client.close();
  24281. }
  24282. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24284. "/ws-echo");
  24285. client.set_tcp_nodelay(true);
  24286. client.set_connection_timeout(3, 0);
  24287. bool socket_options_called = false;
  24288. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24289. ASSERT_TRUE(client.connect());
  24290. ASSERT_TRUE(client.is_open());
  24291. EXPECT_TRUE(socket_options_called);
  24292. ASSERT_TRUE(client.send("hello"));
  24293. std::string msg;
  24294. auto result = client.read(msg);
  24295. EXPECT_EQ(result, ws::ReadResult::Text);
  24296. EXPECT_EQ(msg, "hello");
  24297. client.close();
  24298. }
  24299. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24300. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24301. "/ws-echo");
  24302. client.set_connection_timeout(std::chrono::seconds(3));
  24303. client.set_write_timeout(std::chrono::seconds(3));
  24304. // A sub-second remainder exercises the seconds/microseconds split.
  24305. client.set_read_timeout(std::chrono::milliseconds(1500));
  24306. ASSERT_TRUE(client.connect());
  24307. auto start = std::chrono::steady_clock::now();
  24308. std::string msg;
  24309. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24310. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24311. std::chrono::steady_clock::now() - start)
  24312. .count();
  24313. // Above 1s so that dropping the microseconds half of the split fails here.
  24314. // Ignoring the setter altogether would not reach this line at all: a client
  24315. // waits forever by default.
  24316. EXPECT_GE(elapsed, 1400);
  24317. EXPECT_LT(elapsed, 30000);
  24318. }
  24319. #ifndef _WIN32
  24320. // A send() that times out after part of the data went out returns the count
  24321. // written so far. Every byte of the frame must still be sent, or the peer reads
  24322. // the next frame's header and payload as the rest of this one.
  24323. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24324. signal(SIGPIPE, SIG_IGN);
  24325. const std::string large(4 * 1024 * 1024, 'A');
  24326. std::atomic<bool> large_sent{false};
  24327. std::atomic<bool> small_sent{false};
  24328. Server svr;
  24329. svr.set_write_timeout(0, 500000);
  24330. svr.set_socket_options([](socket_t sock) {
  24331. int size = 8192;
  24332. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24333. reinterpret_cast<const char *>(&size), sizeof(size));
  24334. });
  24335. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24336. large_sent = ws.send(large.data(), large.size());
  24337. small_sent = ws.send("after");
  24338. std::string msg;
  24339. while (ws.read(msg)) {}
  24340. });
  24341. auto port = svr.bind_to_any_port(HOST);
  24342. std::thread t([&]() { svr.listen_after_bind(); });
  24343. auto se = detail::scope_exit([&] {
  24344. svr.stop();
  24345. t.join();
  24346. });
  24347. svr.wait_until_ready();
  24348. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24349. std::to_string(port) + "/ws");
  24350. client.set_read_timeout(5);
  24351. client.set_socket_options([](socket_t sock) {
  24352. int size = 8192;
  24353. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24354. reinterpret_cast<const char *>(&size), sizeof(size));
  24355. });
  24356. ASSERT_TRUE(client.connect());
  24357. // Outlast the server's write timeout, then drain.
  24358. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24359. std::string msg;
  24360. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24361. EXPECT_TRUE(msg == large);
  24362. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24363. EXPECT_EQ("after", msg);
  24364. EXPECT_TRUE(large_sent);
  24365. EXPECT_TRUE(small_sent);
  24366. client.close();
  24367. }
  24368. #endif
  24369. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24370. Server svr;
  24371. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24372. if (!req.has_header("Authorization")) {
  24373. res.status = StatusCode::Unauthorized_401;
  24374. res.set_content("Unauthorized", "text/plain");
  24375. return Server::HandlerResponse::Handled;
  24376. }
  24377. return Server::HandlerResponse::Unhandled;
  24378. });
  24379. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24380. std::string msg;
  24381. while (ws.read(msg)) {
  24382. ws.send(msg);
  24383. }
  24384. });
  24385. auto port = svr.bind_to_any_port("localhost");
  24386. std::thread t([&]() { svr.listen_after_bind(); });
  24387. svr.wait_until_ready();
  24388. // Without Authorization header - should be rejected before upgrade
  24389. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24390. EXPECT_FALSE(client1.connect());
  24391. // The rejection is framed like any other HTTP response
  24392. {
  24393. Client cli("localhost", port);
  24394. Headers headers = {{"Upgrade", "websocket"},
  24395. {"Connection", "Upgrade"},
  24396. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24397. {"Sec-WebSocket-Version", "13"}};
  24398. auto res = cli.Get("/ws", headers);
  24399. ASSERT_TRUE(res);
  24400. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24401. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24402. EXPECT_EQ("Unauthorized", res->body);
  24403. }
  24404. // With Authorization header - should succeed
  24405. Headers headers = {{"Authorization", "Bearer token123"}};
  24406. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24407. headers);
  24408. ASSERT_TRUE(client2.connect());
  24409. ASSERT_TRUE(client2.send("hello"));
  24410. std::string msg;
  24411. ASSERT_TRUE(client2.read(msg));
  24412. EXPECT_EQ("hello", msg);
  24413. client2.close();
  24414. svr.stop();
  24415. t.join();
  24416. }
  24417. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24418. Server svr;
  24419. std::atomic<int> pre_routing_calls{0};
  24420. std::atomic<int> pre_request_calls{0};
  24421. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24422. pre_routing_calls++;
  24423. if (req.path == "/handled") {
  24424. res.set_content("handled", "text/plain");
  24425. return Server::HandlerResponse::Handled;
  24426. }
  24427. return Server::HandlerResponse::Unhandled;
  24428. });
  24429. svr.set_pre_request_handler([&](const Request &, Response &) {
  24430. pre_request_calls++;
  24431. return Server::HandlerResponse::Unhandled;
  24432. });
  24433. svr.Get("/http", [](const Request &, Response &res) {
  24434. res.set_content("http", "text/plain");
  24435. });
  24436. svr.WebSocket("/ws",
  24437. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24438. auto port = svr.bind_to_any_port("localhost");
  24439. std::thread t([&]() { svr.listen_after_bind(); });
  24440. auto se = detail::scope_exit([&] {
  24441. svr.stop();
  24442. t.join();
  24443. });
  24444. svr.wait_until_ready();
  24445. Headers upgrade = {{"Upgrade", "websocket"},
  24446. {"Connection", "Upgrade"},
  24447. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24448. {"Sec-WebSocket-Version", "13"}};
  24449. auto get = [&](const char *path) {
  24450. pre_routing_calls = 0;
  24451. return Client("localhost", port).Get(path, upgrade);
  24452. };
  24453. // No WebSocket route, but an HTTP one
  24454. auto res = get("/http");
  24455. ASSERT_TRUE(res);
  24456. EXPECT_EQ(StatusCode::OK_200, res->status);
  24457. EXPECT_EQ("http", res->body);
  24458. EXPECT_EQ(1, pre_routing_calls);
  24459. EXPECT_EQ(1, pre_request_calls);
  24460. // No route at all
  24461. res = get("/none");
  24462. ASSERT_TRUE(res);
  24463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24464. EXPECT_EQ(1, pre_routing_calls);
  24465. // Answered by the pre-routing handler
  24466. res = get("/handled");
  24467. ASSERT_TRUE(res);
  24468. EXPECT_EQ(StatusCode::OK_200, res->status);
  24469. EXPECT_EQ("handled", res->body);
  24470. EXPECT_EQ(1, pre_routing_calls);
  24471. // A WebSocket route
  24472. pre_routing_calls = 0;
  24473. pre_request_calls = 0;
  24474. {
  24475. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24476. "/ws");
  24477. ASSERT_TRUE(client.connect());
  24478. std::string msg;
  24479. ASSERT_TRUE(client.read(msg));
  24480. EXPECT_EQ("ws", msg);
  24481. client.close();
  24482. }
  24483. EXPECT_EQ(1, pre_routing_calls);
  24484. EXPECT_EQ(1, pre_request_calls);
  24485. }
  24486. // An upgrade request answered by a hook leaves its body unread, so that body
  24487. // must not be served as the next request on the connection.
  24488. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24489. Server svr;
  24490. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24491. if (req.path == "/pre-routing") {
  24492. res.set_content("pre-routing", "text/plain");
  24493. return Server::HandlerResponse::Handled;
  24494. }
  24495. return Server::HandlerResponse::Unhandled;
  24496. });
  24497. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24498. if (req.matched_route == "/pre-request") {
  24499. res.set_content("pre-request", "text/plain");
  24500. return Server::HandlerResponse::Handled;
  24501. }
  24502. return Server::HandlerResponse::Unhandled;
  24503. });
  24504. svr.Get("/smuggled", [](const Request &, Response &res) {
  24505. res.set_content("smuggled", "text/plain");
  24506. });
  24507. svr.WebSocket("/pre-request",
  24508. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24509. auto port = svr.bind_to_any_port(HOST);
  24510. std::thread t([&]() { svr.listen_after_bind(); });
  24511. auto se = detail::scope_exit([&] {
  24512. svr.stop();
  24513. t.join();
  24514. });
  24515. svr.wait_until_ready();
  24516. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24517. for (auto path : {"/pre-routing", "/pre-request"}) {
  24518. std::string req = std::string("GET ") + path +
  24519. " HTTP/1.1\r\n"
  24520. "Host: localhost\r\n"
  24521. "Upgrade: websocket\r\n"
  24522. "Connection: Upgrade\r\n"
  24523. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24524. "Sec-WebSocket-Version: 13\r\n"
  24525. "Content-Length: " +
  24526. std::to_string(body.size()) + "\r\n\r\n" + body;
  24527. std::string res;
  24528. ASSERT_TRUE(send_request(5, req, &res, port));
  24529. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24530. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24531. // Only one response, and the body was not served as a request
  24532. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24533. }
  24534. }
  24535. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24536. Server svr;
  24537. std::atomic<int> pre_request_calls{0};
  24538. std::atomic<bool> route_matched{false};
  24539. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24540. pre_request_calls++;
  24541. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24542. if (req.get_header_value("Authorization") != "Bearer token123") {
  24543. res.status = StatusCode::Unauthorized_401;
  24544. res.set_content("Unauthorized", "text/plain");
  24545. return Server::HandlerResponse::Handled;
  24546. }
  24547. return Server::HandlerResponse::Unhandled;
  24548. });
  24549. std::atomic<bool> handler_called{false};
  24550. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24551. handler_called = true;
  24552. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24553. });
  24554. auto port = svr.bind_to_any_port("localhost");
  24555. std::thread t([&]() { svr.listen_after_bind(); });
  24556. svr.wait_until_ready();
  24557. // Without Authorization header - should be rejected before upgrade
  24558. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24559. "/ws/1");
  24560. EXPECT_FALSE(client1.connect());
  24561. EXPECT_FALSE(handler_called);
  24562. EXPECT_EQ(1, pre_request_calls);
  24563. EXPECT_TRUE(route_matched);
  24564. // The rejection is an ordinary HTTP response, not a protocol switch
  24565. {
  24566. Client cli("localhost", port);
  24567. Headers headers = {{"Upgrade", "websocket"},
  24568. {"Connection", "Upgrade"},
  24569. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24570. {"Sec-WebSocket-Version", "13"}};
  24571. auto res = cli.Get("/ws/1", headers);
  24572. ASSERT_TRUE(res);
  24573. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24574. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24575. EXPECT_EQ("Unauthorized", res->body);
  24576. }
  24577. EXPECT_FALSE(handler_called);
  24578. // With Authorization header - should succeed
  24579. Headers headers = {{"Authorization", "Bearer token123"}};
  24580. ws::WebSocketClient client2(
  24581. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24582. ASSERT_TRUE(client2.connect());
  24583. std::string msg;
  24584. ASSERT_TRUE(client2.read(msg));
  24585. EXPECT_EQ("/ws/:id 2", msg);
  24586. EXPECT_TRUE(handler_called);
  24587. client2.close();
  24588. svr.stop();
  24589. t.join();
  24590. }
  24591. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24592. static Headers websocket_upgrade_headers() {
  24593. return {{"Upgrade", "websocket"},
  24594. {"Connection", "Upgrade"},
  24595. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24596. {"Sec-WebSocket-Version", "13"},
  24597. {"Sec-WebSocket-Protocol", "chat"}};
  24598. }
  24599. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24600. Server svr;
  24601. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24602. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24603. return Server::HandlerResponse::Unhandled;
  24604. });
  24605. svr.set_pre_request_handler([](const Request &req, Response &) {
  24606. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24607. return Server::HandlerResponse::Unhandled;
  24608. });
  24609. svr.set_exception_handler(
  24610. [](const Request &, Response &res, std::exception_ptr ep) {
  24611. try {
  24612. std::rethrow_exception(ep);
  24613. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24614. });
  24615. auto handler = [](const Request &, ws::WebSocket &) {};
  24616. svr.WebSocket("/pre-routing", handler);
  24617. svr.WebSocket("/pre-request", handler);
  24618. svr.WebSocket("/sub-protocol", handler,
  24619. [](const std::vector<std::string> &) -> std::string {
  24620. throw std::runtime_error("/sub-protocol");
  24621. });
  24622. auto port = svr.bind_to_any_port(HOST);
  24623. ASSERT_GT(port, 0);
  24624. thread t = thread([&] { svr.listen_after_bind(); });
  24625. auto se = detail::scope_exit([&] {
  24626. svr.stop();
  24627. t.join();
  24628. ASSERT_FALSE(svr.is_running());
  24629. });
  24630. svr.wait_until_ready();
  24631. Client cli(HOST, port);
  24632. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24633. auto res = cli.Get(path, websocket_upgrade_headers());
  24634. if (!res) {
  24635. ADD_FAILURE() << path << ": " << to_string(res.error());
  24636. continue;
  24637. }
  24638. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24639. EXPECT_EQ(path, res->body);
  24640. }
  24641. }
  24642. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24643. Server svr;
  24644. svr.set_pre_routing_handler(
  24645. [](const Request &, Response &) -> Server::HandlerResponse {
  24646. throw std::runtime_error("pre-routing");
  24647. });
  24648. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24649. auto port = svr.bind_to_any_port(HOST);
  24650. ASSERT_GT(port, 0);
  24651. thread t = thread([&] { svr.listen_after_bind(); });
  24652. auto se = detail::scope_exit([&] {
  24653. svr.stop();
  24654. t.join();
  24655. ASSERT_FALSE(svr.is_running());
  24656. });
  24657. svr.wait_until_ready();
  24658. Client cli(HOST, port);
  24659. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24660. ASSERT_TRUE(res) << to_string(res.error());
  24661. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24662. }
  24663. #endif
  24664. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24665. Server svr;
  24666. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24667. // A read timeout is how a handler gets control back. Without it, a handler
  24668. // parked in read() can never write on the connection it is reading.
  24669. ws.set_read_timeout(std::chrono::milliseconds(100));
  24670. std::string msg;
  24671. while (ws.is_open()) {
  24672. auto r = ws.read(msg);
  24673. if (r == httplib::ws::Timeout) {
  24674. ws.send("tick");
  24675. continue;
  24676. }
  24677. if (r == httplib::ws::Fail) { break; }
  24678. ws.send(msg);
  24679. }
  24680. });
  24681. auto port = svr.bind_to_any_port("localhost");
  24682. std::thread t([&]() { svr.listen_after_bind(); });
  24683. svr.wait_until_ready();
  24684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24685. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24686. ASSERT_TRUE(client.connect());
  24687. // The client sends nothing, so anything it receives came out of the
  24688. // handler's timeout path.
  24689. std::string msg;
  24690. ASSERT_EQ(client.read(msg), ws::Text);
  24691. EXPECT_EQ("tick", msg);
  24692. client.close();
  24693. svr.stop();
  24694. t.join();
  24695. }
  24696. // Stream::read may return fewer bytes than asked for. This is that contract at
  24697. // its worst -- one byte per call -- which is what a frame header straddling a
  24698. // read buffer's boundary looks like to the frame parser.
  24699. class WsByteAtATimeStream : public Stream {
  24700. public:
  24701. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24702. bool is_readable() const override { return true; }
  24703. bool wait_readable() const override { return true; }
  24704. bool wait_writable() const override { return true; }
  24705. ssize_t read(char *ptr, size_t size) override {
  24706. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24707. *ptr = data_[pos_++];
  24708. return 1;
  24709. }
  24710. ssize_t write(const char *, size_t size) override {
  24711. return static_cast<ssize_t>(size);
  24712. }
  24713. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24714. ip = "127.0.0.1";
  24715. port = 0;
  24716. }
  24717. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24718. ip = "127.0.0.1";
  24719. port = 0;
  24720. }
  24721. socket_t socket() const override { return INVALID_SOCKET; }
  24722. time_t duration() const override { return 0; }
  24723. private:
  24724. std::string data_;
  24725. size_t pos_ = 0;
  24726. };
  24727. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24728. // The payload uses the 16-bit extended length, so the header, the length
  24729. // and the mask key are all multi-byte fields here. Each used to be read
  24730. // with a single read() call, which fails as soon as one is split. The
  24731. // payload is also a little over one read chunk, so it is read in two.
  24732. std::string body;
  24733. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24734. body += static_cast<char>(i % 251);
  24735. }
  24736. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24737. std::string frame;
  24738. frame += static_cast<char>(0x81); // FIN + Text
  24739. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24740. frame += static_cast<char>(body.size() >> 8);
  24741. frame += static_cast<char>(body.size() & 0xff);
  24742. for (size_t i = 0; i < 4; i++) {
  24743. frame += static_cast<char>(mask[i]);
  24744. }
  24745. for (size_t i = 0; i < body.size(); i++) {
  24746. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24747. }
  24748. WsByteAtATimeStream strm(frame);
  24749. ws::Opcode opcode;
  24750. std::string payload;
  24751. bool fin = false;
  24752. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24753. /*expect_masked=*/true, body.size()),
  24754. ws::impl::FrameRead::Ok);
  24755. EXPECT_TRUE(fin);
  24756. EXPECT_EQ(opcode, ws::Opcode::Text);
  24757. EXPECT_EQ(payload, body);
  24758. }
  24759. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24760. std::string body(2000, 'x');
  24761. std::string frame;
  24762. frame += static_cast<char>(0x82); // FIN + Binary
  24763. frame += static_cast<char>(126); // 16-bit length follows
  24764. frame += static_cast<char>(body.size() >> 8);
  24765. frame += static_cast<char>(body.size() & 0xff);
  24766. frame += body;
  24767. detail::BufferStream strm;
  24768. strm.write(frame.data(), frame.size());
  24769. ws::Opcode opcode;
  24770. std::string payload;
  24771. bool fin;
  24772. EXPECT_EQ(
  24773. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24774. ws::impl::FrameRead::Ok);
  24775. EXPECT_EQ(body, payload);
  24776. }
  24777. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24778. // The header announces the largest payload allowed, and only 3 bytes of it
  24779. // ever arrive.
  24780. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24781. std::string frame;
  24782. frame += static_cast<char>(0x82); // FIN + Binary
  24783. frame += static_cast<char>(127); // 64-bit length follows
  24784. for (int shift = 56; shift >= 0; shift -= 8) {
  24785. frame += static_cast<char>((len >> shift) & 0xff);
  24786. }
  24787. frame += "abc";
  24788. detail::BufferStream strm;
  24789. strm.write(frame.data(), frame.size());
  24790. ws::Opcode opcode;
  24791. std::string payload;
  24792. bool fin;
  24793. EXPECT_EQ(
  24794. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24795. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24796. ws::impl::FrameRead::Fail);
  24797. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24798. }
  24799. TEST(WebSocketTest, QueryStringInHandshake) {
  24800. Server svr;
  24801. std::mutex mtx;
  24802. std::string received_target;
  24803. std::string received_token;
  24804. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24805. {
  24806. std::lock_guard<std::mutex> lock(mtx);
  24807. received_target = req.target;
  24808. if (req.has_param("token")) {
  24809. received_token = req.get_param_value("token");
  24810. }
  24811. }
  24812. std::string msg;
  24813. while (ws.read(msg)) {
  24814. ws.send(msg);
  24815. }
  24816. });
  24817. auto port = svr.bind_to_any_port("localhost");
  24818. std::thread t([&]() { svr.listen_after_bind(); });
  24819. svr.wait_until_ready();
  24820. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24821. "/ws?token=ABC&session=123");
  24822. ASSERT_TRUE(client.connect());
  24823. // Round-trip ensures the handler has run and captured the request.
  24824. ASSERT_TRUE(client.send("hello"));
  24825. std::string msg;
  24826. ASSERT_TRUE(client.read(msg));
  24827. EXPECT_EQ("hello", msg);
  24828. client.close();
  24829. {
  24830. std::lock_guard<std::mutex> lock(mtx);
  24831. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24832. EXPECT_EQ("ABC", received_token);
  24833. }
  24834. svr.stop();
  24835. t.join();
  24836. }
  24837. // Run a handshake against a throwaway server and hand the request the server
  24838. // received back to the caller, so tests can assert on the headers the client
  24839. // actually put on the wire.
  24840. static void capture_websocket_handshake_request(
  24841. const Headers &client_headers,
  24842. std::function<void(const Request &, int port)> verify) {
  24843. Server svr;
  24844. std::mutex mtx;
  24845. Request received;
  24846. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24847. {
  24848. std::lock_guard<std::mutex> lock(mtx);
  24849. received = req;
  24850. }
  24851. std::string msg;
  24852. while (ws.read(msg)) {
  24853. ws.send(msg);
  24854. }
  24855. });
  24856. auto port = svr.bind_to_any_port("localhost");
  24857. std::thread t([&]() { svr.listen_after_bind(); });
  24858. auto se = detail::scope_exit([&] {
  24859. svr.stop();
  24860. t.join();
  24861. });
  24862. svr.wait_until_ready();
  24863. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24864. client_headers);
  24865. ASSERT_TRUE(client.connect());
  24866. ASSERT_TRUE(client.send("hello"));
  24867. std::string msg;
  24868. ASSERT_TRUE(client.read(msg));
  24869. client.close();
  24870. {
  24871. std::lock_guard<std::mutex> lock(mtx);
  24872. verify(received, port);
  24873. }
  24874. }
  24875. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24876. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24877. // Non-default port must be present in the Host header. Default ports
  24878. // (80/443) are omitted; that logic is covered by
  24879. // MakeHostAndPortStringTest.
  24880. EXPECT_EQ("localhost:" + std::to_string(port),
  24881. req.get_header_value("Host"));
  24882. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24883. req.get_header_value("User-Agent"));
  24884. EXPECT_FALSE(req.has_header("Accept"));
  24885. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24886. EXPECT_FALSE(req.has_header("Content-Length"));
  24887. });
  24888. }
  24889. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24890. capture_websocket_handshake_request(
  24891. {{"Host", "example.com"},
  24892. {"User-Agent", "custom-agent"},
  24893. {"X-Custom", "value"}},
  24894. [](const Request &req, int) {
  24895. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24896. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24897. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24898. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24899. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24900. });
  24901. }
  24902. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24903. capture_websocket_handshake_request(
  24904. {{"Upgrade", "bogus"},
  24905. {"Connection", "close"},
  24906. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24907. {"Sec-WebSocket-Version", "8"}},
  24908. [](const Request &req, int) {
  24909. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24910. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24911. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24912. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24913. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24914. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24915. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24916. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24917. req.get_header_value("Sec-WebSocket-Key"));
  24918. });
  24919. }
  24920. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24921. // A header the client refuses to send must abort the handshake before any
  24922. // part of it reaches the wire; a lone request line would otherwise sit in
  24923. // the peer's buffer as a truncated request.
  24924. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24925. ASSERT_NE(INVALID_SOCKET, srv);
  24926. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24927. sockaddr_in addr{};
  24928. addr.sin_family = AF_INET;
  24929. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24930. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24931. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24932. ASSERT_EQ(0, ::listen(srv, 1));
  24933. sockaddr_in bound{};
  24934. socklen_t bound_len = sizeof(bound);
  24935. ASSERT_EQ(
  24936. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24937. auto port = ntohs(bound.sin_port);
  24938. ssize_t received = -1;
  24939. std::thread t([&] {
  24940. // Bound every blocking call so a regression fails the test with a bad
  24941. // value instead of hanging the suite.
  24942. fd_set rfds;
  24943. FD_ZERO(&rfds);
  24944. FD_SET(srv, &rfds);
  24945. timeval tv{5, 0};
  24946. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24947. 0) {
  24948. return;
  24949. }
  24950. sockaddr_in cli_addr{};
  24951. socklen_t cli_len = sizeof(cli_addr);
  24952. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24953. if (cli == INVALID_SOCKET) { return; }
  24954. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24955. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24956. char buf[4096];
  24957. received = ::recv(cli, buf, sizeof(buf), 0);
  24958. });
  24959. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24960. // connect() has already shut the socket down by the time it returns false,
  24961. // so the peer sees EOF without waiting for the client to be destroyed.
  24962. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24963. {{"X-Bad", "a\r\nInjected: 1"}});
  24964. EXPECT_FALSE(client.connect());
  24965. t.join();
  24966. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24967. EXPECT_EQ(0, received);
  24968. }
  24969. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24970. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24971. // contains "upgrade" as a substring is a different token and must not
  24972. // start a WebSocket handshake.
  24973. auto make_request = [](const std::vector<std::string> &connection_values) {
  24974. Request req;
  24975. req.method = "GET";
  24976. req.headers.emplace("Upgrade", "websocket");
  24977. for (const auto &value : connection_values) {
  24978. req.headers.emplace("Connection", value);
  24979. }
  24980. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24981. req.headers.emplace("Sec-WebSocket-Version", "13");
  24982. return req;
  24983. };
  24984. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24985. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24986. EXPECT_TRUE(
  24987. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24988. EXPECT_TRUE(
  24989. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24990. EXPECT_TRUE(
  24991. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24992. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24993. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24994. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24995. EXPECT_FALSE(
  24996. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24997. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24998. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24999. }
  25000. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25001. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25002. // asks recipients to match each protocol-name case-insensitively, and RFC
  25003. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25004. // client naming websocket alongside another protocol, or on a second field
  25005. // line, is offering websocket; a value that merely contains "websocket" as a
  25006. // substring is a different protocol name and is not.
  25007. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25008. Request req;
  25009. req.method = "GET";
  25010. for (const auto &value : upgrade_values) {
  25011. req.headers.emplace("Upgrade", value);
  25012. }
  25013. req.headers.emplace("Connection", "Upgrade");
  25014. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25015. req.headers.emplace("Sec-WebSocket-Version", "13");
  25016. return req;
  25017. };
  25018. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25019. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25020. EXPECT_TRUE(
  25021. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25022. EXPECT_TRUE(
  25023. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25024. EXPECT_TRUE(
  25025. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25026. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25027. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25028. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25029. EXPECT_FALSE(
  25030. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25031. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25032. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25033. }
  25034. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25035. Server svr;
  25036. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25037. auto port = svr.bind_to_any_port("localhost");
  25038. std::thread t([&]() { svr.listen_after_bind(); });
  25039. auto se = detail::scope_exit([&] {
  25040. svr.stop();
  25041. t.join();
  25042. });
  25043. svr.wait_until_ready();
  25044. Headers headers = {{"Upgrade", "websocket"},
  25045. {"Connection", "notupgrade"},
  25046. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25047. {"Sec-WebSocket-Version", "13"}};
  25048. Client cli("localhost", port);
  25049. auto res = cli.Get("/ws", headers);
  25050. // The route exists only as a WebSocket route, so a request that fails the
  25051. // handshake check falls through to ordinary routing.
  25052. ASSERT_TRUE(res);
  25053. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25054. }
  25055. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25056. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25057. // Connection value is the only thing left for the client to reject.
  25058. Server svr;
  25059. svr.Get("/ws", [](const Request &req, Response &res) {
  25060. res.status = StatusCode::SwitchingProtocol_101;
  25061. res.set_header("Upgrade", "websocket");
  25062. res.set_header("Connection", "notupgrade");
  25063. res.set_header("Sec-WebSocket-Accept",
  25064. detail::websocket_accept_key(
  25065. req.get_header_value("Sec-WebSocket-Key")));
  25066. });
  25067. auto port = svr.bind_to_any_port("localhost");
  25068. std::thread t([&]() { svr.listen_after_bind(); });
  25069. auto se = detail::scope_exit([&] {
  25070. svr.stop();
  25071. t.join();
  25072. });
  25073. svr.wait_until_ready();
  25074. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25075. auto res = client.connect();
  25076. EXPECT_FALSE(res);
  25077. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25078. EXPECT_FALSE(client.is_open());
  25079. }
  25080. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25081. Server svr;
  25082. svr.Get("/ws", [](const Request &req, Response &res) {
  25083. res.status = StatusCode::SwitchingProtocol_101;
  25084. res.set_header("Upgrade", "websocket");
  25085. res.set_header("Connection", "Upgrade");
  25086. res.set_header("Sec-WebSocket-Accept",
  25087. detail::websocket_accept_key(
  25088. req.get_header_value("Sec-WebSocket-Key")));
  25089. res.set_header("Sec-WebSocket-Protocol", "admin");
  25090. });
  25091. auto port = svr.bind_to_any_port("localhost");
  25092. std::thread t([&]() { svr.listen_after_bind(); });
  25093. auto se = detail::scope_exit([&] {
  25094. svr.stop();
  25095. t.join();
  25096. });
  25097. svr.wait_until_ready();
  25098. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25099. // Server selects a subprotocol the client never offered
  25100. {
  25101. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25102. ws::WebSocketClient client(url, headers);
  25103. auto res = client.connect();
  25104. EXPECT_FALSE(res);
  25105. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25106. EXPECT_FALSE(client.is_open());
  25107. EXPECT_TRUE(client.subprotocol().empty());
  25108. }
  25109. // Client offered none but the server named one anyway
  25110. {
  25111. ws::WebSocketClient client(url);
  25112. auto res = client.connect();
  25113. EXPECT_FALSE(res);
  25114. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25115. EXPECT_FALSE(client.is_open());
  25116. EXPECT_TRUE(client.subprotocol().empty());
  25117. }
  25118. }
  25119. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25120. // The socket path doubles as the URL host, so it must not contain '/'.
  25121. const char *shard = getenv("GTEST_SHARD_INDEX");
  25122. const std::string sock_path =
  25123. shard ? std::string("httplib-ws-") + shard + ".sock"
  25124. : std::string("httplib-ws.sock");
  25125. std::remove(sock_path.c_str());
  25126. Server svr;
  25127. std::mutex mtx;
  25128. std::string received_host;
  25129. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25130. {
  25131. std::lock_guard<std::mutex> lock(mtx);
  25132. received_host = req.get_header_value("Host");
  25133. }
  25134. std::string msg;
  25135. while (ws.read(msg)) {
  25136. ws.send(msg);
  25137. }
  25138. });
  25139. svr.set_address_family(AF_UNIX);
  25140. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25141. auto se = detail::scope_exit([&] {
  25142. svr.stop();
  25143. t.join();
  25144. std::remove(sock_path.c_str());
  25145. });
  25146. svr.wait_until_ready();
  25147. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25148. client.set_address_family(AF_UNIX);
  25149. ASSERT_TRUE(client.connect());
  25150. ASSERT_TRUE(client.send("hello"));
  25151. std::string msg;
  25152. ASSERT_TRUE(client.read(msg));
  25153. client.close();
  25154. {
  25155. std::lock_guard<std::mutex> lock(mtx);
  25156. // There is no host:port for a Unix socket, so the same "localhost"
  25157. // placeholder the HTTP client uses is expected.
  25158. EXPECT_EQ("localhost", received_host);
  25159. }
  25160. }
  25161. // Two threads must never parse WebSocket frames from the same stream.
  25162. // close() used to read the peer's Close reply with its own frame read, so it
  25163. // raced a reader thread that was in the middle of a payload: the payload loop
  25164. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25165. // so bytes taken by close() were replaced with bytes from further along the
  25166. // stream. The message kept its length and silently changed content.
  25167. //
  25168. // The raw peer below sends a frame header plus part of the payload, waits for
  25169. // the handler to call close(), and only then sends the rest. Whichever thread
  25170. // would win the race for those bytes, the message must arrive intact, because
  25171. // close() must not touch the stream while read() owns it.
  25172. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25173. #ifndef _WIN32
  25174. signal(SIGPIPE, SIG_IGN);
  25175. #endif
  25176. const size_t payload_len = 120; // fits the 7-bit length field
  25177. const size_t prefix_len = 8;
  25178. const int attempts = 8;
  25179. std::string expected(payload_len, '\0');
  25180. for (size_t i = 0; i < payload_len; i++) {
  25181. expected[i] = static_cast<char>('a' + i % 26);
  25182. }
  25183. std::atomic<bool> peer_stalled{false};
  25184. std::atomic<bool> handler_done{false};
  25185. std::mutex received_mutex;
  25186. std::vector<std::string> received;
  25187. // Bound every wait, so a regression fails the test instead of hanging the
  25188. // suite.
  25189. auto wait_for = [](const std::atomic<bool> &flag) {
  25190. for (int i = 0; i < 500 && !flag; i++) {
  25191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25192. }
  25193. };
  25194. Server svr;
  25195. svr.set_websocket_ping_interval(0);
  25196. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25197. std::thread reader([&]() {
  25198. std::string msg;
  25199. while (ws.read(msg)) {
  25200. std::lock_guard<std::mutex> guard(received_mutex);
  25201. received.push_back(msg);
  25202. }
  25203. });
  25204. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25205. // inside read_websocket_frame() when close() runs.
  25206. wait_for(peer_stalled);
  25207. ws.close();
  25208. reader.join();
  25209. handler_done = true;
  25210. });
  25211. auto port = svr.bind_to_any_port("127.0.0.1");
  25212. std::thread t([&]() { svr.listen_after_bind(); });
  25213. auto se = detail::scope_exit([&] {
  25214. svr.stop();
  25215. t.join();
  25216. });
  25217. svr.wait_until_ready();
  25218. auto send_bytes = [](socket_t s, const std::string &data) {
  25219. #ifdef _WIN32
  25220. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25221. #else
  25222. auto n = ::send(s, data.data(), data.size(), 0);
  25223. #endif
  25224. return n == static_cast<decltype(n)>(data.size());
  25225. };
  25226. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25227. // Every length used here fits the 7-bit length field.
  25228. auto masked_header = [](uint8_t first_byte, size_t len) {
  25229. std::string h;
  25230. h += static_cast<char>(first_byte);
  25231. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25232. h.append(4, '\0'); // mask key
  25233. return h;
  25234. };
  25235. for (int attempt = 0; attempt < attempts; attempt++) {
  25236. peer_stalled = false;
  25237. handler_done = false;
  25238. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25239. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25240. auto se_sock = detail::scope_exit([&] {
  25241. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25242. });
  25243. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25244. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25245. sockaddr_in addr{};
  25246. addr.sin_family = AF_INET;
  25247. addr.sin_port = htons(static_cast<uint16_t>(port));
  25248. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25249. ASSERT_EQ(
  25250. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25251. << "attempt " << attempt;
  25252. ASSERT_TRUE(send_bytes(sock,
  25253. "GET /ws HTTP/1.1\r\n"
  25254. "Host: 127.0.0.1\r\n"
  25255. "Upgrade: websocket\r\n"
  25256. "Connection: Upgrade\r\n"
  25257. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25258. "Sec-WebSocket-Version: 13\r\n"
  25259. "\r\n"))
  25260. << "attempt " << attempt;
  25261. std::string response;
  25262. while (response.find("\r\n\r\n") == std::string::npos) {
  25263. char buf[512];
  25264. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25265. if (n <= 0) { break; }
  25266. response.append(buf, static_cast<size_t>(n));
  25267. }
  25268. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25269. << "attempt " << attempt;
  25270. // Send the header of a Binary message but only the first prefix_len bytes
  25271. // of its payload, leaving the reader thread stalled inside the payload.
  25272. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25273. expected.substr(0, prefix_len)))
  25274. << "attempt " << attempt;
  25275. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25276. peer_stalled = true;
  25277. // Let close() send its Close frame and park in its own read before the
  25278. // rest of the payload arrives, so both threads are waiting for it.
  25279. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25280. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25281. close_frame += static_cast<char>(0x03); // status 1000
  25282. close_frame += static_cast<char>(0xE8);
  25283. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25284. << "attempt " << attempt;
  25285. // Closing the peer releases the reader thread even on the buggy path,
  25286. // where it waits for bytes another thread already consumed.
  25287. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25288. detail::close_socket(sock);
  25289. sock = INVALID_SOCKET;
  25290. wait_for(handler_done);
  25291. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25292. }
  25293. std::lock_guard<std::mutex> guard(received_mutex);
  25294. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25295. << "a message in flight when close() ran was dropped";
  25296. for (size_t i = 0; i < received.size(); i++) {
  25297. EXPECT_EQ(expected, received[i]) << "message " << i;
  25298. }
  25299. }
  25300. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25301. // returning the socket, or INVALID_SOCKET.
  25302. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25303. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25304. if (sock == INVALID_SOCKET) { return sock; }
  25305. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25306. sockaddr_in addr{};
  25307. addr.sin_family = AF_INET;
  25308. addr.sin_port = htons(static_cast<uint16_t>(port));
  25309. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25310. std::string req = "GET " + path +
  25311. " HTTP/1.1\r\n"
  25312. "Host: 127.0.0.1\r\n"
  25313. "Upgrade: websocket\r\n"
  25314. "Connection: Upgrade\r\n"
  25315. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25316. "Sec-WebSocket-Version: 13\r\n"
  25317. "\r\n";
  25318. std::string res;
  25319. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25320. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25321. static_cast<ssize_t>(req.size())) {
  25322. char c;
  25323. while (res.find("\r\n\r\n") == std::string::npos &&
  25324. ::recv(sock, &c, 1, 0) == 1) {
  25325. res += c;
  25326. }
  25327. }
  25328. if (res.find(" 101 ") == std::string::npos) {
  25329. detail::close_socket(sock);
  25330. return INVALID_SOCKET;
  25331. }
  25332. return sock;
  25333. }
  25334. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25335. // The payload must fit the 7-bit length field.
  25336. static std::string masked_frame(uint8_t first_byte,
  25337. const std::string &payload) {
  25338. std::string f;
  25339. f += static_cast<char>(first_byte);
  25340. f += static_cast<char>(0x80 | payload.size());
  25341. f.append(4, '\0');
  25342. return f + payload;
  25343. }
  25344. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25345. std::atomic<bool> done{false};
  25346. std::string received;
  25347. Server svr;
  25348. svr.set_websocket_ping_interval(0);
  25349. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25350. std::string msg;
  25351. if (ws.read(msg) == ws::Binary) { received = msg; }
  25352. done = true;
  25353. });
  25354. auto port = svr.bind_to_any_port("127.0.0.1");
  25355. std::thread t([&]() { svr.listen_after_bind(); });
  25356. auto se = detail::scope_exit([&] {
  25357. svr.stop();
  25358. t.join();
  25359. });
  25360. svr.wait_until_ready();
  25361. auto sock = connect_raw_websocket(port, "/ws");
  25362. ASSERT_NE(INVALID_SOCKET, sock);
  25363. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25364. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25365. masked_frame(0x89, "p") + // FIN + Ping
  25366. masked_frame(0x80, "lo"); // FIN + Continuation
  25367. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25368. for (int i = 0; i < 500 && !done; i++) {
  25369. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25370. }
  25371. ASSERT_TRUE(done);
  25372. EXPECT_EQ("Hello", received);
  25373. // The Ping between the fragments is answered with a Pong.
  25374. char pong[3];
  25375. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25376. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25377. }
  25378. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25379. Server svr;
  25380. svr.set_websocket_ping_interval(-1);
  25381. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25382. std::string msg;
  25383. while (ws.read(msg)) {}
  25384. });
  25385. auto port = svr.bind_to_any_port("127.0.0.1");
  25386. std::thread t([&]() { svr.listen_after_bind(); });
  25387. auto se = detail::scope_exit([&] {
  25388. svr.stop();
  25389. t.join();
  25390. });
  25391. svr.wait_until_ready();
  25392. auto sock = connect_raw_websocket(port, "/ws");
  25393. ASSERT_NE(INVALID_SOCKET, sock);
  25394. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25395. // Nothing comes while the client stays quiet.
  25396. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25397. char c;
  25398. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25399. }
  25400. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25401. // and that has to end a read() already waiting on the peer, on every platform.
  25402. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25403. // The peer sends no pings, and its handler never calls read(), which is
  25404. // where pongs are written.
  25405. std::mutex mutex;
  25406. std::condition_variable cv;
  25407. auto release = false;
  25408. svr.set_websocket_ping_interval(0);
  25409. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25410. std::unique_lock<std::mutex> lock(mutex);
  25411. cv.wait(lock, [&] { return release; });
  25412. });
  25413. auto port = svr.bind_to_any_port(HOST);
  25414. std::thread t([&]() { svr.listen_after_bind(); });
  25415. auto se = detail::scope_exit([&] {
  25416. {
  25417. std::lock_guard<std::mutex> lock(mutex);
  25418. release = true;
  25419. }
  25420. cv.notify_all();
  25421. svr.stop();
  25422. t.join();
  25423. });
  25424. svr.wait_until_ready();
  25425. ws::WebSocketClient client(std::string(scheme) +
  25426. "://localhost:" + std::to_string(port) + "/ws");
  25427. #ifdef CPPHTTPLIB_SSL_ENABLED
  25428. client.enable_server_certificate_verification(false);
  25429. #endif
  25430. // A ping a second, given up on after two go unanswered: about 3s
  25431. client.set_websocket_ping_interval(1);
  25432. client.set_websocket_max_missed_pongs(2);
  25433. // Well past that, so that a read the timeout ends instead stands out
  25434. client.set_read_timeout(10);
  25435. ASSERT_TRUE(client.connect());
  25436. auto start = std::chrono::steady_clock::now();
  25437. std::string msg;
  25438. EXPECT_EQ(ws::Fail, client.read(msg));
  25439. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25440. std::chrono::steady_clock::now() - start)
  25441. .count(),
  25442. 6000);
  25443. EXPECT_FALSE(client.is_open());
  25444. }
  25445. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25446. Server svr;
  25447. check_pong_timeout_ends_read(svr, "ws");
  25448. }
  25449. #ifdef CPPHTTPLIB_SSL_ENABLED
  25450. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25452. ASSERT_TRUE(svr.is_valid());
  25453. check_pong_timeout_ends_read(svr, "wss");
  25454. }
  25455. #endif
  25456. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25457. Server svr;
  25458. svr.set_websocket_ping_interval(0);
  25459. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25460. std::string msg;
  25461. while (ws.read(msg)) {}
  25462. });
  25463. auto port = svr.bind_to_any_port("127.0.0.1");
  25464. std::thread t([&]() { svr.listen_after_bind(); });
  25465. auto se = detail::scope_exit([&] {
  25466. svr.stop();
  25467. t.join();
  25468. });
  25469. svr.wait_until_ready();
  25470. // Each Close payload and the reply it should get: an echo when valid, 1002
  25471. // otherwise.
  25472. std::vector<std::pair<std::string, std::string>> cases = {
  25473. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25474. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25475. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25476. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25477. };
  25478. // Also between the fragments of a message.
  25479. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25480. for (const auto &c : cases) {
  25481. auto sock = connect_raw_websocket(port, "/ws");
  25482. ASSERT_NE(INVALID_SOCKET, sock);
  25483. auto frames = prefix + masked_frame(0x88, c.first);
  25484. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25485. std::string reply;
  25486. char buf[256];
  25487. while (reply.size() < 2 + c.second.size()) {
  25488. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25489. if (n <= 0) { break; }
  25490. reply.append(buf, static_cast<size_t>(n));
  25491. }
  25492. detail::close_socket(sock);
  25493. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25494. c.second,
  25495. reply);
  25496. }
  25497. }
  25498. }
  25499. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25500. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25501. protected:
  25502. void SetUp() override {
  25503. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25504. SERVER_PRIVATE_KEY_FILE);
  25505. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25506. std::string msg;
  25507. ws::ReadResult ret;
  25508. while ((ret = ws.read(msg))) {
  25509. if (ret == ws::Binary) {
  25510. ws.send(msg.data(), msg.size());
  25511. } else {
  25512. ws.send(msg);
  25513. }
  25514. }
  25515. });
  25516. port_ = server_->bind_to_any_port(HOST);
  25517. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25518. server_->wait_until_ready();
  25519. }
  25520. void TearDown() override {
  25521. server_->stop();
  25522. if (server_thread_.joinable()) { server_thread_.join(); }
  25523. }
  25524. std::unique_ptr<SSLServer> server_;
  25525. std::thread server_thread_;
  25526. int port_ = 0;
  25527. };
  25528. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25529. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25530. {
  25531. ws::WebSocketClient client(url);
  25532. client.enable_server_certificate_verification(false);
  25533. auto calls = 0;
  25534. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25535. calls++;
  25536. return false;
  25537. });
  25538. EXPECT_FALSE(client.connect());
  25539. EXPECT_GT(calls, 0);
  25540. }
  25541. {
  25542. ws::WebSocketClient client(url);
  25543. client.enable_server_certificate_verification(false);
  25544. client.set_session_verifier([](tls::session_t) {
  25545. return SSLVerifierResponse::CertificateRejected;
  25546. });
  25547. EXPECT_FALSE(client.connect());
  25548. }
  25549. {
  25550. ws::WebSocketClient client(url);
  25551. client.enable_server_certificate_verification(false);
  25552. client.set_session_verifier([](tls::session_t) {
  25553. return SSLVerifierResponse::CertificateAccepted;
  25554. });
  25555. EXPECT_TRUE(client.connect());
  25556. }
  25557. }
  25558. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25559. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25560. "/ws-echo");
  25561. client.enable_server_certificate_verification(false);
  25562. ASSERT_TRUE(client.connect());
  25563. ASSERT_TRUE(client.is_open());
  25564. ASSERT_TRUE(client.send("Hello WSS"));
  25565. std::string msg;
  25566. EXPECT_EQ(ws::Text, client.read(msg));
  25567. EXPECT_EQ("Hello WSS", msg);
  25568. client.close();
  25569. }
  25570. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25571. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25572. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25573. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25574. // client (without calling close() first) is the only path that runs
  25575. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25576. // bug exactly.
  25577. //
  25578. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25579. // when linked against an instrumented libssl; run under Valgrind to catch it
  25580. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25581. // suite (the freed session otherwise stalls on the close handshake) — this test
  25582. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25583. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25584. {
  25585. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25586. "/ws-echo");
  25587. client.enable_server_certificate_verification(false);
  25588. client.set_read_timeout(2, 0);
  25589. client.set_write_timeout(2, 0);
  25590. ASSERT_TRUE(client.connect());
  25591. ASSERT_TRUE(client.is_open());
  25592. ASSERT_TRUE(client.send("still open"));
  25593. // Intentionally do NOT call client.close(): leaving scope runs
  25594. // shutdown_and_close() with the WebSocket still open, which must send the
  25595. // close frame while the TLS session is still alive.
  25596. }
  25597. }
  25598. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25599. // shutdown_and_close() at the start of connect(), reproducing the same
  25600. // use-after-free within the test body rather than at scope exit. The second
  25601. // connect must succeed and echo, proving the close handshake ran over a live
  25602. // session. See the note above about memory-tool requirements.
  25603. TEST_F(WebSocketSSLIntegrationTest,
  25604. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25605. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25606. "/ws-echo");
  25607. client.enable_server_certificate_verification(false);
  25608. client.set_read_timeout(2, 0);
  25609. client.set_write_timeout(2, 0);
  25610. ASSERT_TRUE(client.connect());
  25611. ASSERT_TRUE(client.is_open());
  25612. ASSERT_TRUE(client.send("still open"));
  25613. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25614. // the still-open connection, which must not touch a freed TLS session.
  25615. ASSERT_TRUE(client.connect());
  25616. ASSERT_TRUE(client.is_open());
  25617. ASSERT_TRUE(client.send("after reconnect"));
  25618. std::string msg;
  25619. EXPECT_EQ(ws::Text, client.read(msg));
  25620. EXPECT_EQ("after reconnect", msg);
  25621. client.close();
  25622. }
  25623. #endif
  25624. #ifdef CPPHTTPLIB_SSL_ENABLED
  25625. class WebSocketSSLCATest : public ::testing::Test {
  25626. protected:
  25627. void SetUp() override {
  25628. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25629. SERVER_PRIVATE_KEY_FILE);
  25630. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25631. std::string msg;
  25632. while (ws.read(msg)) {
  25633. ws.send(msg);
  25634. }
  25635. });
  25636. port_ = server_->bind_to_any_port("127.0.0.1");
  25637. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25638. server_->wait_until_ready();
  25639. }
  25640. void TearDown() override {
  25641. server_->stop();
  25642. if (server_thread_.joinable()) { server_thread_.join(); }
  25643. }
  25644. std::string url() const {
  25645. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25646. }
  25647. std::unique_ptr<SSLServer> server_;
  25648. std::thread server_thread_;
  25649. int port_ = 0;
  25650. };
  25651. // A custom CA loaded as PEM verifies the server with full certificate
  25652. // verification enabled
  25653. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25654. ws::WebSocketClient client(url());
  25655. std::string cert;
  25656. read_file(SERVER_CERT2_FILE, cert);
  25657. client.load_ca_cert_store(cert.c_str(), cert.size());
  25658. ASSERT_TRUE(client.connect());
  25659. ASSERT_TRUE(client.send("hello"));
  25660. std::string msg;
  25661. EXPECT_EQ(ws::Text, client.read(msg));
  25662. EXPECT_EQ("hello", msg);
  25663. client.close();
  25664. }
  25665. // A custom CA that does not cover the server must fail verification (the
  25666. // custom CA is exclusive; system certs are not loaded alongside it)
  25667. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25668. ws::WebSocketClient client(url());
  25669. std::string cert;
  25670. read_file(CLIENT_CA_CERT_FILE, cert);
  25671. client.load_ca_cert_store(cert.c_str(), cert.size());
  25672. auto res = client.connect();
  25673. ASSERT_FALSE(res);
  25674. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25675. EXPECT_EQ(-1, res.status());
  25676. EXPECT_NE(0u, res.ssl_backend_error());
  25677. }
  25678. // The same CA as a file path rather than PEM in memory
  25679. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25680. ws::WebSocketClient client(url());
  25681. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25682. ASSERT_TRUE(client.connect());
  25683. ASSERT_TRUE(client.send("hello"));
  25684. std::string msg;
  25685. EXPECT_EQ(ws::Text, client.read(msg));
  25686. EXPECT_EQ("hello", msg);
  25687. client.close();
  25688. }
  25689. // ...and a CA file that does not cover the server still fails, so it is the
  25690. // path above that decides the outcome
  25691. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25692. ws::WebSocketClient client(url());
  25693. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25694. ASSERT_FALSE(client.connect());
  25695. }
  25696. // Regression test: reconnecting with a native custom CA store used to reuse
  25697. // a store handle the previous TLS context had already freed (use-after-free
  25698. // under the OpenSSL backend). The context now lives as long as the client.
  25699. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25700. ws::WebSocketClient client(url());
  25701. std::string cert;
  25702. read_file(SERVER_CERT2_FILE, cert);
  25703. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25704. ASSERT_TRUE(client.connect());
  25705. client.close();
  25706. ASSERT_TRUE(client.connect());
  25707. ASSERT_TRUE(client.send("again"));
  25708. std::string msg;
  25709. EXPECT_EQ(ws::Text, client.read(msg));
  25710. EXPECT_EQ("again", msg);
  25711. client.close();
  25712. }
  25713. // Regression test: a certificate with a trusted chain but no identity match
  25714. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25715. // verification entirely for IP hosts, so this connection succeeded there.
  25716. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25717. // chain verification while the identity check must still fail.
  25718. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25720. ASSERT_TRUE(svr.is_valid());
  25721. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25722. std::string msg;
  25723. while (ws.read(msg)) {
  25724. ws.send(msg);
  25725. }
  25726. });
  25727. auto port = svr.bind_to_any_port("127.0.0.1");
  25728. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25729. auto se = detail::scope_exit([&] {
  25730. svr.stop();
  25731. t.join();
  25732. });
  25733. svr.wait_until_ready();
  25734. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25735. "/echo");
  25736. std::string cert;
  25737. read_file(SERVER_CERT_FILE, cert);
  25738. client.load_ca_cert_store(cert.c_str(), cert.size());
  25739. ASSERT_FALSE(client.connect());
  25740. }
  25741. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25742. // SNI, so nothing binds the host name to the TLS session. These bind the
  25743. // server to "localhost" instead, the only shape that exercises the SNI and
  25744. // hostname-verification path with certificate verification left enabled.
  25745. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25746. protected:
  25747. void Start(const char *cert_file) {
  25748. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25749. SERVER_PRIVATE_KEY_FILE);
  25750. ASSERT_TRUE(server_->is_valid());
  25751. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25752. std::string msg;
  25753. while (ws.read(msg)) {
  25754. ws.send(msg);
  25755. }
  25756. });
  25757. port_ = server_->bind_to_any_port("localhost");
  25758. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25759. server_->wait_until_ready();
  25760. }
  25761. void TearDown() override {
  25762. if (server_) { server_->stop(); }
  25763. if (server_thread_.joinable()) { server_thread_.join(); }
  25764. }
  25765. std::string url() const {
  25766. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25767. }
  25768. std::unique_ptr<SSLServer> server_;
  25769. std::thread server_thread_;
  25770. int port_ = 0;
  25771. };
  25772. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25773. // out and the connection is usable
  25774. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25775. Start(SERVER_CERT2_FILE);
  25776. ws::WebSocketClient client(url());
  25777. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25778. ASSERT_TRUE(client.connect());
  25779. ASSERT_TRUE(client.send("hello"));
  25780. std::string msg;
  25781. EXPECT_EQ(ws::Text, client.read(msg));
  25782. EXPECT_EQ("hello", msg);
  25783. client.close();
  25784. }
  25785. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25786. // while the identity check must still reject "localhost"
  25787. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25788. Start(SERVER_CERT_FILE);
  25789. ws::WebSocketClient client(url());
  25790. client.set_ca_cert_path(SERVER_CERT_FILE);
  25791. auto res = client.connect();
  25792. ASSERT_FALSE(res);
  25793. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25794. EXPECT_EQ(-1, res.status());
  25795. }
  25796. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25797. // disabled: the chain is still checked, only the identity check is skipped
  25798. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25799. Start(SERVER_CERT_FILE);
  25800. ws::WebSocketClient client(url());
  25801. client.set_ca_cert_path(SERVER_CERT_FILE);
  25802. client.enable_server_hostname_verification(false);
  25803. ASSERT_TRUE(client.connect());
  25804. ASSERT_TRUE(client.send("hello"));
  25805. std::string msg;
  25806. EXPECT_EQ(ws::Text, client.read(msg));
  25807. EXPECT_EQ("hello", msg);
  25808. client.close();
  25809. }
  25810. // A CA that did not sign the server certificate fails the chain, even though
  25811. // the name would match
  25812. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25813. Start(SERVER_CERT2_FILE);
  25814. ws::WebSocketClient client(url());
  25815. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25816. ASSERT_FALSE(client.connect());
  25817. }
  25818. // With verification disabled, neither the chain nor the name is checked
  25819. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25820. Start(SERVER_CERT_FILE);
  25821. ws::WebSocketClient client(url());
  25822. client.enable_server_certificate_verification(false);
  25823. ASSERT_TRUE(client.connect());
  25824. ASSERT_TRUE(client.send("hello"));
  25825. std::string msg;
  25826. EXPECT_EQ(ws::Text, client.read(msg));
  25827. EXPECT_EQ("hello", msg);
  25828. client.close();
  25829. }
  25830. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25831. protected:
  25832. void SetUp() override {
  25833. server_ = httplib::detail::make_unique<SSLServer>(
  25834. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25835. ASSERT_TRUE(server_->is_valid());
  25836. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25837. std::string msg;
  25838. while (ws.read(msg)) {
  25839. ws.send(msg);
  25840. }
  25841. });
  25842. port_ = server_->bind_to_any_port("localhost");
  25843. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25844. server_->wait_until_ready();
  25845. }
  25846. void TearDown() override {
  25847. server_->stop();
  25848. if (server_thread_.joinable()) { server_thread_.join(); }
  25849. }
  25850. std::string url() const {
  25851. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25852. }
  25853. void ConnectWithClientCert(const std::string &client_cert_file,
  25854. const std::string &client_private_key_file,
  25855. const char *private_key_password) {
  25856. std::string cert_pem, key_pem;
  25857. read_file(client_cert_file, cert_pem);
  25858. read_file(client_private_key_file, key_pem);
  25859. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25860. key_pem.c_str(), key_pem.size(),
  25861. private_key_password};
  25862. ConnectWithPem(pem);
  25863. }
  25864. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25865. ws::WebSocketClient client(url(), pem);
  25866. ASSERT_TRUE(client.is_valid());
  25867. client.enable_server_certificate_verification(false);
  25868. ASSERT_TRUE(client.connect());
  25869. ASSERT_TRUE(client.send("hello"));
  25870. std::string msg;
  25871. EXPECT_EQ(ws::Text, client.read(msg));
  25872. EXPECT_EQ("hello", msg);
  25873. client.close();
  25874. }
  25875. std::unique_ptr<SSLServer> server_;
  25876. std::thread server_thread_;
  25877. int port_ = 0;
  25878. };
  25879. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25880. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25881. }
  25882. // Control for the tests above: the fixture's server really does require a
  25883. // client certificate, so it is the PEM the constructor installed that decides
  25884. // the outcome.
  25885. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25886. ws::WebSocketClient client(url());
  25887. ASSERT_TRUE(client.is_valid());
  25888. client.enable_server_certificate_verification(false);
  25889. EXPECT_FALSE(client.connect());
  25890. }
  25891. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25892. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25893. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25894. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25895. }
  25896. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25897. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25898. std::string cert_pem, key_pem;
  25899. read_file(CLIENT_CERT_FILE, cert_pem);
  25900. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25901. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25902. std::vector<char> key(key_pem.begin(), key_pem.end());
  25903. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25904. key.size(), nullptr};
  25905. ConnectWithPem(pem);
  25906. }
  25907. #endif
  25908. #if !defined(_WIN32)
  25909. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25910. auto secret_dir = std::string("./symlink_test_secret");
  25911. auto served_dir = std::string("./symlink_test_served");
  25912. auto secret_file = secret_dir + "/secret.txt";
  25913. auto symlink_path = served_dir + "/escape";
  25914. // Setup: create directories and files
  25915. mkdir(secret_dir.c_str(), 0755);
  25916. mkdir(served_dir.c_str(), 0755);
  25917. {
  25918. std::ofstream ofs(secret_file);
  25919. ofs << "SECRET_DATA";
  25920. }
  25921. // Create symlink using absolute path so it resolves correctly
  25922. #ifdef PATH_MAX
  25923. char abs_secret[PATH_MAX];
  25924. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25925. #else
  25926. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25927. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25928. ASSERT_NE(nullptr, abs_secret);
  25929. #endif
  25930. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25931. auto se = detail::scope_exit([&] {
  25932. unlink(symlink_path.c_str());
  25933. unlink(secret_file.c_str());
  25934. rmdir(served_dir.c_str());
  25935. rmdir(secret_dir.c_str());
  25936. });
  25937. Server svr;
  25938. svr.set_mount_point("/", served_dir);
  25939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25940. auto se2 = detail::scope_exit([&] {
  25941. svr.stop();
  25942. listen_thread.join();
  25943. });
  25944. svr.wait_until_ready();
  25945. Client cli("localhost", PORT);
  25946. // Symlink pointing outside base dir should be blocked
  25947. auto res = cli.Get("/escape/secret.txt");
  25948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25949. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25950. }
  25951. #endif
  25952. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25953. // "GET /smuggled" request), reads the first response, and only then sends the
  25954. // embedded request as the body. Returns how many times /smuggled ran.
  25955. //
  25956. // The body is sent AFTER receiving the first response (as in the original
  25957. // PoC) so that the stream_line_reader cannot buffer it together with the
  25958. // headers of the first request.
  25959. static int count_smuggled_requests(const std::string &outer_head,
  25960. std::string &first_response) {
  25961. Server svr;
  25962. svr.set_mount_point("/", "./www");
  25963. std::atomic<int> smuggled_count(0);
  25964. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25965. smuggled_count++;
  25966. res.set_content("oops", "text/plain");
  25967. });
  25968. svr.Post("/post", [&](const Request &req, Response &res) {
  25969. res.set_content(req.body, "text/plain");
  25970. });
  25971. auto port = svr.bind_to_any_port("localhost");
  25972. thread t = thread([&] { svr.listen_after_bind(); });
  25973. auto se = detail::scope_exit([&] {
  25974. svr.stop();
  25975. t.join();
  25976. });
  25977. svr.wait_until_ready();
  25978. auto error = Error::Success;
  25979. auto sock = detail::create_client_socket(
  25980. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25981. /*connection_timeout_sec=*/2, 0,
  25982. /*read_timeout_sec=*/2, 0,
  25983. /*write_timeout_sec=*/2, 0, std::string(), error);
  25984. EXPECT_NE(INVALID_SOCKET, sock);
  25985. if (sock == INVALID_SOCKET) { return -1; }
  25986. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25987. // The "smuggled" request will be sent as the body of the outer request
  25988. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25989. "Host: localhost\r\n"
  25990. "Connection: close\r\n"
  25991. "\r\n";
  25992. auto head = outer_head;
  25993. auto len = std::to_string(smuggled.size());
  25994. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25995. pos = head.find("{len}", pos + len.size())) {
  25996. head.replace(pos, 5, len);
  25997. }
  25998. // Step 1: Send only the outer request headers (no body yet)
  25999. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26000. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26001. // Step 2: Read the first response
  26002. char buf[4096];
  26003. for (;;) {
  26004. auto n = recv(sock, buf, sizeof(buf), 0);
  26005. if (n <= 0) break;
  26006. first_response.append(buf, static_cast<size_t>(n));
  26007. // Stop once we have a complete response (headers + body)
  26008. auto hdr_end = first_response.find("\r\n\r\n");
  26009. if (hdr_end != std::string::npos) {
  26010. // Check for Content-Length to know when the body is complete
  26011. auto cl_pos = first_response.find("Content-Length:");
  26012. if (cl_pos != std::string::npos) {
  26013. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26014. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26015. auto cl = std::stoul(
  26016. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26017. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26018. } else {
  26019. break; // No Content-Length, assume headers-only response
  26020. }
  26021. }
  26022. }
  26023. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26024. // vulnerable server the keep-alive loop reads this as a second request. The
  26025. // server may already have closed the connection, so the result is ignored.
  26026. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26027. // Half-close so that a server which drained the body sees EOF and closes,
  26028. // instead of the read below waiting for the read timeout.
  26029. #ifdef _WIN32
  26030. ::shutdown(sock, SD_SEND);
  26031. #else
  26032. ::shutdown(sock, SHUT_WR);
  26033. #endif
  26034. // Step 4: Read until the server closes the connection
  26035. for (;;) {
  26036. auto n = recv(sock, buf, sizeof(buf), 0);
  26037. if (n <= 0) break;
  26038. }
  26039. return smuggled_count.load();
  26040. }
  26041. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26042. // A GET request with Content-Length to a static file handler must have its
  26043. // body drained before the keep-alive connection is reused. Otherwise the
  26044. // unread body bytes are interpreted as the next HTTP request.
  26045. std::string first_response;
  26046. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26047. "Host: localhost\r\n"
  26048. "Content-Length: {len}\r\n"
  26049. "\r\n",
  26050. first_response));
  26051. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26052. }
  26053. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26054. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26055. // be answered with 400 and the connection closed. Treating it as "no body"
  26056. // leaves the body to be parsed as the next request.
  26057. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26058. const char *targets[] = {
  26059. "GET /file", // handler that never reads the body
  26060. "GET /not-found", // no handler matches (404)
  26061. "POST /post", // handler that reads the body
  26062. };
  26063. for (auto target : targets) {
  26064. for (auto value : values) {
  26065. std::string first_response;
  26066. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26067. " HTTP/1.1\r\n"
  26068. "Host: localhost\r\n"
  26069. "Content-Length: " +
  26070. value + "\r\n\r\n",
  26071. first_response))
  26072. << target << " with Content-Length: " << value;
  26073. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  26074. << target << " with Content-Length: " << value;
  26075. }
  26076. }
  26077. }
  26078. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  26079. // A 400 for an unparseable request line leaves the rest of the message
  26080. // unread, so the connection must be closed rather than reused.
  26081. std::string first_response;
  26082. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  26083. "Host: localhost\r\n"
  26084. "Content-Length: {len}\r\n"
  26085. "\r\n",
  26086. first_response));
  26087. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26088. }
  26089. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  26090. // Same as above for a header block that fails to parse.
  26091. std::string first_response;
  26092. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26093. "Host: localhost\r\n"
  26094. "Bad Header\r\n"
  26095. "Content-Length: {len}\r\n"
  26096. "\r\n",
  26097. first_response));
  26098. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26099. }
  26100. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  26101. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  26102. // server must not read another request on that connection, even when the
  26103. // request had no body to drain.
  26104. std::string first_response;
  26105. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  26106. "Host: localhost\r\n"
  26107. "\r\n",
  26108. first_response));
  26109. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26110. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26111. }
  26112. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26113. // A content reader that stops early leaves the stream inside the body.
  26114. // Draining the whole Content-Length from there, or reading the body again,
  26115. // reads into the next request, and whatever follows is parsed as a request
  26116. // of its own.
  26117. Server svr;
  26118. std::atomic<int> smuggled_count(0);
  26119. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26120. svr.Post("/upload", [](const Request &req, Response &res,
  26121. const ContentReader &content_reader) {
  26122. // Stop at the last chunk, so the whole body has been read however it
  26123. // arrives.
  26124. auto length = req.get_header_value_u64("Content-Length");
  26125. size_t total = 0;
  26126. auto consumed = content_reader([&](const char *, size_t n) {
  26127. total += n;
  26128. return total < length;
  26129. });
  26130. EXPECT_FALSE(consumed);
  26131. if (req.has_param("retry")) {
  26132. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26133. }
  26134. // Replace the 400 the aborted read set, which would close the connection.
  26135. res.set_redirect("/done");
  26136. });
  26137. auto port = svr.bind_to_any_port(HOST);
  26138. thread t = thread([&] { svr.listen_after_bind(); });
  26139. auto se = detail::scope_exit([&] {
  26140. svr.stop();
  26141. t.join();
  26142. });
  26143. svr.wait_until_ready();
  26144. // A front end sees the second request as a POST whose body is the GET. The
  26145. // first body is as long as the POST's headers, so draining it again reads
  26146. // exactly those and leaves the GET to be parsed next.
  26147. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26148. "Host: localhost\r\n"
  26149. "\r\n";
  26150. std::string second_head = "POST /post HTTP/1.1\r\n"
  26151. "Host: localhost\r\n"
  26152. "Content-Length: " +
  26153. std::to_string(inner.size()) +
  26154. "\r\n"
  26155. "\r\n";
  26156. for (auto target : {"/upload", "/upload?retry"}) {
  26157. smuggled_count = 0;
  26158. std::string request = "POST " + std::string(target) +
  26159. " HTTP/1.1\r\n"
  26160. "Host: localhost\r\n"
  26161. "Content-Length: " +
  26162. std::to_string(second_head.size()) +
  26163. "\r\n"
  26164. "\r\n" +
  26165. std::string(second_head.size(), 'A') + second_head +
  26166. inner;
  26167. std::string response;
  26168. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26169. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26170. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26171. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26172. EXPECT_EQ(0, smuggled_count.load()) << target;
  26173. }
  26174. }
  26175. // An error response closes the connection anyway, so the body is left unread
  26176. // with a redirect, such as one to a login page.
  26177. static void serve_redirects(Server &svr,
  26178. const std::function<void(int)> &client) {
  26179. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26180. res.set_redirect("/login");
  26181. return Server::HandlerResponse::Handled;
  26182. });
  26183. auto port = svr.bind_to_any_port(HOST);
  26184. ASSERT_GT(port, 0);
  26185. thread t = thread([&] { svr.listen_after_bind(); });
  26186. auto se = detail::scope_exit([&] {
  26187. svr.stop();
  26188. t.join();
  26189. ASSERT_FALSE(svr.is_running());
  26190. });
  26191. svr.wait_until_ready();
  26192. client(port);
  26193. }
  26194. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26195. Server svr;
  26196. serve_redirects(svr, [](int port) {
  26197. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26198. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26199. std::to_string(body.size()) + "\r\n\r\n" + body +
  26200. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26201. std::string resp;
  26202. ASSERT_TRUE(send_request(1, req, &resp, port));
  26203. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26204. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26205. });
  26206. }
  26207. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26208. Server svr;
  26209. svr.set_read_timeout(0, 200000);
  26210. serve_redirects(svr, [](int port) {
  26211. // A byte every 100 ms keeps each read within the read timeout, but not the
  26212. // body as a whole, so the server closes and the bytes sent after that fail.
  26213. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26214. "Content-Length: 10\r\n\r\n"};
  26215. parts.resize(11, "x");
  26216. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26217. });
  26218. }
  26219. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26220. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26221. // must be rejected with 400 Bad Request.
  26222. Server svr;
  26223. svr.Post("/test", [&](const Request &, Response &res) {
  26224. res.set_content("ok", "text/plain");
  26225. });
  26226. thread t = thread([&] { svr.listen(HOST, PORT); });
  26227. auto se = detail::scope_exit([&] {
  26228. svr.stop();
  26229. t.join();
  26230. ASSERT_FALSE(svr.is_running());
  26231. });
  26232. svr.wait_until_ready();
  26233. // Exact "chunked"
  26234. {
  26235. auto req = "POST /test HTTP/1.1\r\n"
  26236. "Host: localhost\r\n"
  26237. "Content-Length: 5\r\n"
  26238. "Transfer-Encoding: chunked\r\n"
  26239. "Connection: close\r\n"
  26240. "\r\n"
  26241. "hello";
  26242. std::string response;
  26243. ASSERT_TRUE(send_request(1, req, &response));
  26244. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26245. response.substr(0, response.find("\r\n")));
  26246. }
  26247. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26248. {
  26249. auto req = "POST /test HTTP/1.1\r\n"
  26250. "Host: localhost\r\n"
  26251. "Content-Length: 5\r\n"
  26252. "Transfer-Encoding: gzip, chunked\r\n"
  26253. "Connection: close\r\n"
  26254. "\r\n"
  26255. "hello";
  26256. std::string response;
  26257. ASSERT_TRUE(send_request(1, req, &response));
  26258. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26259. response.substr(0, response.find("\r\n")));
  26260. }
  26261. }
  26262. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26263. Server svr;
  26264. svr.Post("/test", [&](const Request &, Response &res) {
  26265. res.set_content("ok", "text/plain");
  26266. });
  26267. thread t = thread([&] { svr.listen(HOST, PORT); });
  26268. auto se = detail::scope_exit([&] {
  26269. svr.stop();
  26270. t.join();
  26271. ASSERT_FALSE(svr.is_running());
  26272. });
  26273. svr.wait_until_ready();
  26274. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26275. // length cannot be determined, so the server must answer 400 and close
  26276. // rather than treat the request as bodyless and leave the body in the
  26277. // socket for the next request to pick up.
  26278. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26279. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26280. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26281. std::string response;
  26282. ASSERT_TRUE(send_request(1, req, &response));
  26283. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26284. response.substr(0, response.find("\r\n")))
  26285. << transfer_encoding;
  26286. }
  26287. // RFC 9110 5.3: the codings may also be split across several
  26288. // Transfer-Encoding lines, which combine in the order they were received.
  26289. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26290. // just like the single-line "chunked, gzip" above.
  26291. {
  26292. auto req = "POST /test HTTP/1.1\r\n"
  26293. "Host: localhost\r\n"
  26294. "Transfer-Encoding: chunked\r\n"
  26295. "Transfer-Encoding: gzip\r\n"
  26296. "\r\n"
  26297. "0\r\n\r\n";
  26298. std::string response;
  26299. ASSERT_TRUE(send_request(1, req, &response));
  26300. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26301. response.substr(0, response.find("\r\n")));
  26302. }
  26303. }
  26304. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26305. Server svr;
  26306. svr.Post("/test", [&](const Request &, Response &res) {
  26307. res.set_content("ok", "text/plain");
  26308. });
  26309. auto port = svr.bind_to_any_port(HOST);
  26310. ASSERT_GT(port, 0);
  26311. thread t = thread([&] { svr.listen_after_bind(); });
  26312. auto se = detail::scope_exit([&] {
  26313. svr.stop();
  26314. t.join();
  26315. ASSERT_FALSE(svr.is_running());
  26316. });
  26317. svr.wait_until_ready();
  26318. for (auto transfer_encoding :
  26319. {"Transfer-Encoding: gzip, chunked\r\n",
  26320. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26321. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26322. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26323. transfer_encoding + "\r\n0\r\n\r\n";
  26324. std::string response;
  26325. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26326. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26327. response.substr(0, response.find("\r\n")))
  26328. << transfer_encoding;
  26329. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26330. << transfer_encoding;
  26331. }
  26332. }
  26333. // Regression for issue #2450: a DELETE without Content-Length on a
  26334. // keep-alive connection must not let the post-response drain consume the
  26335. // next request's bytes.
  26336. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26337. Server svr;
  26338. std::atomic<int> delete_count(0);
  26339. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26340. delete_count++;
  26341. res.status = StatusCode::NoContent_204;
  26342. });
  26343. auto port = svr.bind_to_any_port(HOST);
  26344. thread t = thread([&] { svr.listen_after_bind(); });
  26345. auto se = detail::scope_exit([&] {
  26346. svr.stop();
  26347. t.join();
  26348. });
  26349. svr.wait_until_ready();
  26350. auto error = Error::Success;
  26351. auto sock = detail::create_client_socket(
  26352. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26353. /*connection_timeout_sec=*/2, 0,
  26354. /*read_timeout_sec=*/2, 0,
  26355. /*write_timeout_sec=*/2, 0, std::string(), error);
  26356. ASSERT_NE(INVALID_SOCKET, sock);
  26357. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26358. auto send_request_and_read_response = [&](const std::string &req,
  26359. std::string &out) -> bool {
  26360. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26361. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26362. char buf[4096];
  26363. for (;;) {
  26364. auto n = recv(sock, buf, sizeof(buf), 0);
  26365. if (n <= 0) { return !out.empty(); }
  26366. out.append(buf, static_cast<size_t>(n));
  26367. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26368. }
  26369. };
  26370. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26371. "Host: localhost\r\n"
  26372. "\r\n";
  26373. std::string resp1;
  26374. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26375. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26376. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26377. "Host: localhost\r\n"
  26378. "Connection: close\r\n"
  26379. "\r\n";
  26380. std::string resp2;
  26381. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26382. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26383. EXPECT_EQ(2, delete_count.load());
  26384. }
  26385. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26386. Server svr;
  26387. svr.Post("/ingest", [&](const Request &, Response &res,
  26388. const ContentReader &content_reader) {
  26389. auto consumed = content_reader([](const char *, size_t) { return false; });
  26390. EXPECT_FALSE(consumed);
  26391. res.status = StatusCode::Conflict_409;
  26392. res.set_header("Connection", "close");
  26393. });
  26394. auto port = svr.bind_to_any_port(HOST);
  26395. thread t = thread([&] { svr.listen_after_bind(); });
  26396. auto se = detail::scope_exit([&] {
  26397. svr.stop();
  26398. t.join();
  26399. });
  26400. svr.wait_until_ready();
  26401. auto error = Error::Success;
  26402. auto sock = detail::create_client_socket(
  26403. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26404. /*connection_timeout_sec=*/2, 0,
  26405. /*read_timeout_sec=*/1, 0,
  26406. /*write_timeout_sec=*/2, 0, std::string(), error);
  26407. ASSERT_NE(INVALID_SOCKET, sock);
  26408. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26409. std::string request = "POST /ingest HTTP/1.1\r\n"
  26410. "Host: localhost\r\n"
  26411. "Transfer-Encoding: chunked\r\n"
  26412. "\r\n"
  26413. "4\r\n"
  26414. "data\r\n";
  26415. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26416. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26417. std::string response;
  26418. ssize_t received = 0;
  26419. do {
  26420. char buf[4096];
  26421. received = recv(sock, buf, sizeof(buf), 0);
  26422. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26423. } while (received > 0);
  26424. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26425. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26426. EXPECT_EQ(0, received);
  26427. }
  26428. namespace no_proxy_test {
  26429. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26430. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26431. // calling listen().
  26432. class ScopedServer {
  26433. public:
  26434. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26435. ~ScopedServer() {
  26436. svr_.stop();
  26437. if (th_.joinable()) { th_.join(); }
  26438. }
  26439. Server &svr() { return svr_; }
  26440. int port() const { return port_; }
  26441. void listen() {
  26442. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26443. svr_.wait_until_ready();
  26444. }
  26445. private:
  26446. Server svr_;
  26447. std::thread th_;
  26448. int port_ = 0;
  26449. };
  26450. class ProxyAndTargetServers {
  26451. public:
  26452. ProxyAndTargetServers() {
  26453. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26454. proxy_hits_++;
  26455. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26456. res.set_content("via-proxy", "text/plain");
  26457. });
  26458. target_.Get(".*", [this](const Request &req, Response &res) {
  26459. target_hits_++;
  26460. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26461. res.set_content("direct", "text/plain");
  26462. });
  26463. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26464. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26465. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26466. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26467. proxy_mock_.wait_until_ready();
  26468. target_.wait_until_ready();
  26469. }
  26470. ~ProxyAndTargetServers() {
  26471. proxy_mock_.stop();
  26472. target_.stop();
  26473. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26474. if (target_thread_.joinable()) { target_thread_.join(); }
  26475. }
  26476. Server &proxy_mock() { return proxy_mock_; }
  26477. Server &target() { return target_; }
  26478. int proxy_port() const { return proxy_port_; }
  26479. int target_port() const { return target_port_; }
  26480. int proxy_hits() const { return proxy_hits_.load(); }
  26481. int target_hits() const { return target_hits_.load(); }
  26482. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26483. void reset_counters() {
  26484. proxy_hits_ = 0;
  26485. target_hits_ = 0;
  26486. last_had_proxy_authz_ = false;
  26487. }
  26488. private:
  26489. Server proxy_mock_;
  26490. Server target_;
  26491. std::thread proxy_thread_;
  26492. std::thread target_thread_;
  26493. int proxy_port_ = 0;
  26494. int target_port_ = 0;
  26495. std::atomic<int> proxy_hits_{0};
  26496. std::atomic<int> target_hits_{0};
  26497. std::atomic<bool> last_had_proxy_authz_{false};
  26498. };
  26499. inline std::unique_ptr<Client> make_client(const std::string &host,
  26500. ProxyAndTargetServers &s) {
  26501. auto cli = detail::make_unique<Client>(host, s.target_port());
  26502. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26503. cli->set_proxy("127.0.0.1", s.proxy_port());
  26504. return cli;
  26505. }
  26506. } // namespace no_proxy_test
  26507. using no_proxy_test::make_client;
  26508. using no_proxy_test::ProxyAndTargetServers;
  26509. // A stream request carries the credentials a buffered request does
  26510. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26511. no_proxy_test::ScopedServer origin;
  26512. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26513. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26514. });
  26515. origin.listen();
  26516. Client cli("127.0.0.1", origin.port());
  26517. cli.set_basic_auth("user", "pass");
  26518. auto handle = cli.open_stream("GET", "/x");
  26519. ASSERT_TRUE(handle.is_valid());
  26520. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26521. Client bearer("127.0.0.1", origin.port());
  26522. bearer.set_bearer_token_auth("tok");
  26523. auto handle2 = bearer.open_stream("GET", "/x");
  26524. ASSERT_TRUE(handle2.is_valid());
  26525. EXPECT_EQ("Bearer tok", read_all(handle2));
  26526. }
  26527. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26528. // takes its own credentials, as for a buffered request
  26529. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26530. std::string target, authz, proxy_authz;
  26531. no_proxy_test::ScopedServer proxy;
  26532. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26533. target = req.target;
  26534. authz = req.get_header_value("Authorization");
  26535. proxy_authz = req.get_header_value("Proxy-Authorization");
  26536. res.set_content("ok", "text/plain");
  26537. });
  26538. proxy.listen();
  26539. Client cli("origin.example", 8080);
  26540. cli.set_proxy("127.0.0.1", proxy.port());
  26541. cli.set_proxy_basic_auth("puser", "ppass");
  26542. cli.set_basic_auth("user", "pass");
  26543. auto handle = cli.open_stream("GET", "/x");
  26544. ASSERT_TRUE(handle.is_valid());
  26545. EXPECT_EQ("ok", read_all(handle));
  26546. EXPECT_EQ("http://origin.example:8080/x", target);
  26547. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26548. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26549. }
  26550. // In absolute-form the path follows the authority, so a path that does not
  26551. // begin with '/' would make the proxy connect to another host
  26552. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26553. std::vector<std::string> targets;
  26554. no_proxy_test::ScopedServer proxy;
  26555. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26556. targets.push_back(req.target);
  26557. res.set_content("ok", "text/plain");
  26558. });
  26559. proxy.listen();
  26560. Client cli("origin.example", 8080);
  26561. cli.set_proxy("127.0.0.1", proxy.port());
  26562. cli.set_basic_auth("user", "pass");
  26563. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26564. auto res = cli.Get(path);
  26565. EXPECT_FALSE(res) << path;
  26566. auto handle = cli.open_stream("GET", path);
  26567. EXPECT_FALSE(handle.is_valid()) << path;
  26568. }
  26569. EXPECT_TRUE(targets.empty());
  26570. auto res = cli.Get("/x");
  26571. ASSERT_TRUE(res);
  26572. ASSERT_EQ(1u, targets.size());
  26573. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26574. }
  26575. TEST(NoProxyTest, ExactHostnameBypasses) {
  26576. ProxyAndTargetServers s;
  26577. auto cli = make_client("example.com", s);
  26578. cli->set_no_proxy({"example.com"});
  26579. auto res = cli->Get("/");
  26580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26581. EXPECT_EQ(0, s.proxy_hits());
  26582. EXPECT_EQ(1, s.target_hits());
  26583. }
  26584. TEST(NoProxyTest, SubdomainBypasses) {
  26585. ProxyAndTargetServers s;
  26586. auto cli = make_client("foo.example.com", s);
  26587. cli->set_no_proxy({"example.com"});
  26588. auto res = cli->Get("/");
  26589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26590. EXPECT_EQ(0, s.proxy_hits());
  26591. EXPECT_EQ(1, s.target_hits());
  26592. }
  26593. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26594. // Regression guard: "evilexample.com" must not be considered a subdomain
  26595. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26596. // check would let traffic bypass the proxy and leak credentials direct
  26597. // to the attacker host.
  26598. ProxyAndTargetServers s;
  26599. auto cli = make_client("evilexample.com", s);
  26600. cli->set_no_proxy({"example.com"});
  26601. auto res = cli->Get("/");
  26602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26603. EXPECT_GE(s.proxy_hits(), 1);
  26604. EXPECT_EQ(0, s.target_hits());
  26605. }
  26606. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26607. ProxyAndTargetServers s;
  26608. auto cli = make_client("example.com.evil.com", s);
  26609. cli->set_no_proxy({"example.com"});
  26610. auto res = cli->Get("/");
  26611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26612. EXPECT_GE(s.proxy_hits(), 1);
  26613. EXPECT_EQ(0, s.target_hits());
  26614. }
  26615. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26616. ProxyAndTargetServers s;
  26617. auto cli = make_client("example.com", s);
  26618. cli->set_no_proxy({".example.com"});
  26619. auto res = cli->Get("/");
  26620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26621. EXPECT_EQ(0, s.proxy_hits());
  26622. EXPECT_EQ(1, s.target_hits());
  26623. }
  26624. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26625. ProxyAndTargetServers s;
  26626. auto cli = make_client("Example.COM", s);
  26627. cli->set_no_proxy({"EXAMPLE.com"});
  26628. auto res = cli->Get("/");
  26629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26630. EXPECT_EQ(0, s.proxy_hits());
  26631. EXPECT_EQ(1, s.target_hits());
  26632. }
  26633. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26634. ProxyAndTargetServers s;
  26635. auto cli = make_client("example.com.", s);
  26636. cli->set_no_proxy({"example.com"});
  26637. auto res = cli->Get("/");
  26638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26639. EXPECT_EQ(0, s.proxy_hits());
  26640. EXPECT_EQ(1, s.target_hits());
  26641. }
  26642. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26643. // Trailing dots must be normalized on BOTH sides — host and entry.
  26644. // An implementation that only strips the host-side trailing dot would
  26645. // fail to match host "example.com" against entry "example.com." because
  26646. // a literal substring search would compare 11 chars against 12.
  26647. ProxyAndTargetServers s;
  26648. auto cli = make_client("example.com", s);
  26649. cli->set_no_proxy({"example.com."});
  26650. auto res = cli->Get("/");
  26651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26652. EXPECT_EQ(0, s.proxy_hits());
  26653. EXPECT_EQ(1, s.target_hits());
  26654. }
  26655. TEST(NoProxyTest, WildcardBypassesEverything) {
  26656. ProxyAndTargetServers s;
  26657. auto cli = make_client("anything.invalid.test", s);
  26658. cli->set_no_proxy({"*"});
  26659. auto res = cli->Get("/");
  26660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26661. EXPECT_EQ(0, s.proxy_hits());
  26662. EXPECT_EQ(1, s.target_hits());
  26663. }
  26664. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26665. ProxyAndTargetServers s;
  26666. Client cli("127.0.0.1", s.target_port());
  26667. cli.set_proxy("127.0.0.1", s.proxy_port());
  26668. cli.set_no_proxy({"127.0.0.1"});
  26669. auto res = cli.Get("/");
  26670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26671. EXPECT_EQ(0, s.proxy_hits());
  26672. EXPECT_EQ(1, s.target_hits());
  26673. }
  26674. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26675. ProxyAndTargetServers s;
  26676. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26677. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26678. cli.set_proxy("127.0.0.1", s.proxy_port());
  26679. cli.set_no_proxy({"::1"});
  26680. auto res = cli.Get("/");
  26681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26682. EXPECT_EQ(0, s.proxy_hits());
  26683. EXPECT_EQ(1, s.target_hits());
  26684. }
  26685. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26686. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26687. // must still be recognized as IPv6 for CIDR matching. Implementations
  26688. // that detect IPv6 only when the host begins with '[' would parse the
  26689. // host as a hostname and miss the match.
  26690. ProxyAndTargetServers s;
  26691. Client cli("fe80::1", s.target_port());
  26692. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26693. cli.set_proxy("127.0.0.1", s.proxy_port());
  26694. cli.set_no_proxy({"fe80::/10"});
  26695. auto res = cli.Get("/");
  26696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26697. EXPECT_EQ(0, s.proxy_hits());
  26698. EXPECT_EQ(1, s.target_hits());
  26699. }
  26700. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26701. ProxyAndTargetServers s;
  26702. Client cli("::1", s.target_port());
  26703. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26704. cli.set_proxy("127.0.0.1", s.proxy_port());
  26705. cli.set_no_proxy({"[::1]"});
  26706. auto res = cli.Get("/");
  26707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26708. EXPECT_EQ(0, s.proxy_hits());
  26709. EXPECT_EQ(1, s.target_hits());
  26710. }
  26711. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26712. ProxyAndTargetServers s;
  26713. Client cli("fe80::1", s.target_port());
  26714. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26715. cli.set_proxy("127.0.0.1", s.proxy_port());
  26716. cli.set_no_proxy({"[fe80::]/10"});
  26717. auto res = cli.Get("/");
  26718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26719. EXPECT_EQ(0, s.proxy_hits());
  26720. EXPECT_EQ(1, s.target_hits());
  26721. }
  26722. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26723. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26724. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26725. // tricks via address-family conversion.
  26726. ProxyAndTargetServers s;
  26727. Client cli("::ffff:127.0.0.1", s.target_port());
  26728. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26729. cli.set_proxy("127.0.0.1", s.proxy_port());
  26730. cli.set_no_proxy({"127.0.0.1"});
  26731. auto res = cli.Get("/");
  26732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26733. EXPECT_GE(s.proxy_hits(), 1);
  26734. EXPECT_EQ(0, s.target_hits());
  26735. }
  26736. TEST(NoProxyTest, IPv4CidrMatch) {
  26737. ProxyAndTargetServers s;
  26738. Client cli("127.0.0.1", s.target_port());
  26739. cli.set_proxy("127.0.0.1", s.proxy_port());
  26740. cli.set_no_proxy({"127.0.0.0/8"});
  26741. auto res = cli.Get("/");
  26742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26743. EXPECT_EQ(0, s.proxy_hits());
  26744. EXPECT_EQ(1, s.target_hits());
  26745. }
  26746. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26747. ProxyAndTargetServers s;
  26748. Client cli("127.0.0.1", s.target_port());
  26749. cli.set_proxy("127.0.0.1", s.proxy_port());
  26750. cli.set_no_proxy({"10.0.0.0/8"});
  26751. auto res = cli.Get("/");
  26752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26753. EXPECT_GE(s.proxy_hits(), 1);
  26754. EXPECT_EQ(0, s.target_hits());
  26755. }
  26756. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26757. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26758. // IPv4 target matches.
  26759. ProxyAndTargetServers s;
  26760. Client cli("127.0.0.1", s.target_port());
  26761. cli.set_proxy("127.0.0.1", s.proxy_port());
  26762. cli.set_no_proxy({"0.0.0.0/0"});
  26763. auto res = cli.Get("/");
  26764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26765. EXPECT_EQ(0, s.proxy_hits());
  26766. EXPECT_EQ(1, s.target_hits());
  26767. }
  26768. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26769. ProxyAndTargetServers s;
  26770. Client cli("127.0.0.1", s.target_port());
  26771. cli.set_proxy("127.0.0.1", s.proxy_port());
  26772. cli.set_no_proxy({"127.0.0.1"});
  26773. auto res = cli.Get("/");
  26774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26775. EXPECT_EQ(0, s.proxy_hits());
  26776. EXPECT_EQ(1, s.target_hits());
  26777. }
  26778. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26779. ProxyAndTargetServers s;
  26780. Client cli("127.0.0.1", s.target_port());
  26781. cli.set_proxy("127.0.0.1", s.proxy_port());
  26782. cli.set_no_proxy({"127.0.0.0/33"});
  26783. auto res = cli.Get("/");
  26784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26785. EXPECT_GE(s.proxy_hits(), 1);
  26786. EXPECT_EQ(0, s.target_hits());
  26787. }
  26788. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26789. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26790. ProxyAndTargetServers s;
  26791. Client cli("127.0.0.1", s.target_port());
  26792. cli.set_proxy("127.0.0.1", s.proxy_port());
  26793. cli.set_no_proxy({"127.0.0.1/"});
  26794. auto res = cli.Get("/");
  26795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26796. EXPECT_GE(s.proxy_hits(), 1);
  26797. EXPECT_EQ(0, s.target_hits());
  26798. }
  26799. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26800. ProxyAndTargetServers s;
  26801. auto cli = make_client("internal.corp", s);
  26802. cli->set_proxy_basic_auth("u", "p");
  26803. cli->set_no_proxy({"internal.corp"});
  26804. auto res = cli->Get("/");
  26805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26806. EXPECT_EQ(1, s.target_hits());
  26807. EXPECT_EQ(0, s.proxy_hits());
  26808. EXPECT_FALSE(s.last_had_proxy_authz())
  26809. << "Proxy-Authorization must not be sent direct to the target";
  26810. }
  26811. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26812. ProxyAndTargetServers s;
  26813. auto cli = make_client("public.example", s);
  26814. cli->set_proxy_basic_auth("u", "p");
  26815. cli->set_no_proxy({"internal.corp"}); // does not match
  26816. auto res = cli->Get("/");
  26817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26818. EXPECT_GE(s.proxy_hits(), 1);
  26819. EXPECT_TRUE(s.last_had_proxy_authz());
  26820. }
  26821. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26822. std::atomic<int> hits{0};
  26823. std::atomic<int> hits_with_authz{0};
  26824. no_proxy_test::ScopedServer proxy_mock;
  26825. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26826. hits++;
  26827. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26828. if (req.target.find("/redir") != std::string::npos) {
  26829. res.set_redirect("http://other.example/landed");
  26830. } else {
  26831. res.set_content("via-proxy", "text/plain");
  26832. }
  26833. });
  26834. proxy_mock.listen();
  26835. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26836. hits = 0;
  26837. hits_with_authz = 0;
  26838. Client cli("public.example", 80);
  26839. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26840. cli.set_proxy_basic_auth(c.first, c.second);
  26841. cli.set_follow_location(true);
  26842. // The redirect to another host goes through the proxy as well
  26843. auto res = cli.Get("/redir");
  26844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26845. EXPECT_EQ(2, hits.load());
  26846. EXPECT_EQ(2, hits_with_authz.load());
  26847. }
  26848. }
  26849. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26850. ProxyAndTargetServers s;
  26851. auto cli = make_client("anything.test", s);
  26852. auto res = cli->Get("/");
  26853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26854. EXPECT_GE(s.proxy_hits(), 1);
  26855. EXPECT_EQ(0, s.target_hits());
  26856. }
  26857. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26858. ProxyAndTargetServers s;
  26859. auto cli = make_client("example.com", s);
  26860. cli->set_no_proxy({"example.com:8080"});
  26861. auto res = cli->Get("/");
  26862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26863. EXPECT_GE(s.proxy_hits(), 1);
  26864. EXPECT_EQ(0, s.target_hits());
  26865. }
  26866. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26867. ProxyAndTargetServers s;
  26868. auto cli = make_client("anything.test", s);
  26869. cli->set_no_proxy({"", " ", "\t"});
  26870. auto res = cli->Get("/");
  26871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26872. EXPECT_GE(s.proxy_hits(), 1);
  26873. EXPECT_EQ(0, s.target_hits());
  26874. }
  26875. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26876. // An entry with leading/trailing whitespace must still match — env-style
  26877. // values are commonly pasted with stray spaces and an implementation
  26878. // that feeds the raw token directly to inet_pton would fail to match
  26879. // valid CIDRs because of the spaces.
  26880. ProxyAndTargetServers s;
  26881. Client cli("127.0.0.1", s.target_port());
  26882. cli.set_proxy("127.0.0.1", s.proxy_port());
  26883. cli.set_no_proxy({" 127.0.0.0/8 "});
  26884. auto res = cli.Get("/");
  26885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26886. EXPECT_EQ(0, s.proxy_hits());
  26887. EXPECT_EQ(1, s.target_hits());
  26888. }
  26889. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26890. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26891. // go direct and must NOT carry Proxy-Authorization.
  26892. std::atomic<int> proxy_hits{0};
  26893. std::atomic<int> target_hits{0};
  26894. std::atomic<bool> target_saw_authz{false};
  26895. no_proxy_test::ScopedServer proxy_mock, target;
  26896. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26897. proxy_hits++;
  26898. res.status = 302;
  26899. res.set_header("Location", "http://127.0.0.1:" +
  26900. std::to_string(target.port()) + "/landed");
  26901. });
  26902. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26903. target_hits++;
  26904. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26905. res.set_content("direct", "text/plain");
  26906. });
  26907. proxy_mock.listen();
  26908. target.listen();
  26909. Client cli("public.example", target.port());
  26910. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26911. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26912. cli.set_proxy_basic_auth("u", "p");
  26913. cli.set_no_proxy({"127.0.0.1"});
  26914. cli.set_follow_location(true);
  26915. auto res = cli.Get("/redir");
  26916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26917. EXPECT_GE(proxy_hits.load(), 1);
  26918. EXPECT_GE(target_hits.load(), 1);
  26919. EXPECT_FALSE(target_saw_authz.load());
  26920. }
  26921. #ifdef CPPHTTPLIB_SSL_ENABLED
  26922. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26923. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26924. // proxy creds would be sent to the (possibly hostile) origin.
  26925. std::atomic<int> target_hits{0};
  26926. std::atomic<bool> target_saw_proxy_authz{false};
  26927. no_proxy_test::ScopedServer target;
  26928. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26929. target_hits++;
  26930. if (req.has_header("Proxy-Authorization")) {
  26931. target_saw_proxy_authz = true;
  26932. }
  26933. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26934. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26935. "nonce=\"abc\", algorithm=MD5");
  26936. });
  26937. target.listen();
  26938. // The proxy address is set to the target's port: the bypass MUST kick in;
  26939. // if it doesn't, the test still routes "via proxy" to the same server and
  26940. // the Proxy-Authorization assertion below catches the leak.
  26941. Client cli("evil.example", target.port());
  26942. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26943. cli.set_proxy("127.0.0.1", target.port());
  26944. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26945. cli.set_no_proxy({"evil.example"});
  26946. auto res = cli.Get("/x");
  26947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26948. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26949. EXPECT_EQ(1, target_hits.load());
  26950. EXPECT_FALSE(target_saw_proxy_authz.load());
  26951. }
  26952. #endif
  26953. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26954. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26955. std::atomic<int> proxy_hits{0};
  26956. std::atomic<int> bypass_hits{0};
  26957. std::atomic<bool> proxy_saw_c_url{false};
  26958. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26959. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26960. proxy_hits++;
  26961. if (req.path.find("/start") != std::string::npos) {
  26962. res.status = 302;
  26963. res.set_header("Location", "http://127.0.0.1:" +
  26964. std::to_string(bypass_server.port()) +
  26965. "/middle");
  26966. return;
  26967. }
  26968. if (req.path.find("/end") != std::string::npos) {
  26969. proxy_saw_c_url = true;
  26970. res.set_content("c-via-proxy", "text/plain");
  26971. return;
  26972. }
  26973. res.set_content("unexpected", "text/plain");
  26974. });
  26975. // public.example's "advertised" port is arbitrary (the request never lands
  26976. // there — it goes through the proxy), but use a dynamic value to stay
  26977. // friendly with sharded parallel runs.
  26978. int public_port = bypass_server.port();
  26979. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26980. bypass_hits++;
  26981. res.status = 302;
  26982. res.set_header("Location", "http://public.example:" +
  26983. std::to_string(public_port) + "/end");
  26984. });
  26985. proxy_mock.listen();
  26986. bypass_server.listen();
  26987. Client cli("public.example", public_port);
  26988. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26989. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26990. cli.set_no_proxy({"127.0.0.1"});
  26991. cli.set_follow_location(true);
  26992. auto res = cli.Get("/start");
  26993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26994. EXPECT_EQ(StatusCode::OK_200, res->status);
  26995. EXPECT_EQ("c-via-proxy", res->body);
  26996. EXPECT_GE(proxy_hits.load(), 2);
  26997. EXPECT_GE(bypass_hits.load(), 1);
  26998. EXPECT_TRUE(proxy_saw_c_url.load());
  26999. }
  27000. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27001. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27002. // request reconnects to the correct endpoint.
  27003. std::atomic<int> proxy_hits{0};
  27004. std::atomic<int> target_hits{0};
  27005. no_proxy_test::ScopedServer proxy_mock, target;
  27006. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27007. proxy_hits++;
  27008. res.set_content("via-proxy", "text/plain");
  27009. });
  27010. target.svr().Get(".*", [&](const Request &, Response &res) {
  27011. target_hits++;
  27012. res.set_content("direct", "text/plain");
  27013. });
  27014. proxy_mock.listen();
  27015. target.listen();
  27016. Client cli("public.example", target.port());
  27017. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27018. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27019. cli.set_keep_alive(true);
  27020. auto res1 = cli.Get("/a");
  27021. ASSERT_TRUE(res1);
  27022. EXPECT_EQ("via-proxy", res1->body);
  27023. EXPECT_EQ(1, proxy_hits.load());
  27024. EXPECT_EQ(0, target_hits.load());
  27025. cli.set_no_proxy({"public.example"});
  27026. auto res2 = cli.Get("/b");
  27027. ASSERT_TRUE(res2);
  27028. EXPECT_EQ("direct", res2->body);
  27029. EXPECT_EQ(1, proxy_hits.load());
  27030. EXPECT_EQ(1, target_hits.load());
  27031. }
  27032. // Forward declarations (see the base64_encode note).
  27033. namespace httplib {
  27034. namespace detail {
  27035. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27036. int shutdown_socket(socket_t sock) noexcept;
  27037. } // namespace detail
  27038. } // namespace httplib
  27039. namespace proxy_tunnel_test {
  27040. const char *const kTunnelEstablished =
  27041. "HTTP/1.1 200 Connection established\r\n\r\n";
  27042. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27043. using ConnectReply = std::function<std::string(const std::string &head)>;
  27044. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27045. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27046. class ScopedConnectProxy {
  27047. public:
  27048. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27049. : forward_port_(forward_port), reply_(std::move(reply)) {
  27050. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27051. if (listen_sock_ == INVALID_SOCKET) { return; }
  27052. auto a = loopback(0);
  27053. auto addr = reinterpret_cast<sockaddr *>(&a);
  27054. socklen_t alen = sizeof(a);
  27055. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27056. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27057. ::listen(listen_sock_, 4) != 0) {
  27058. return;
  27059. }
  27060. port_ = ntohs(a.sin_port);
  27061. th_ = std::thread([this] { run(); });
  27062. }
  27063. ~ScopedConnectProxy() {
  27064. if (th_.joinable()) {
  27065. stop_ = true;
  27066. auto wake = connect_to(port_);
  27067. th_.join();
  27068. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27069. }
  27070. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27071. }
  27072. int port() const { return port_; }
  27073. int connect_hits() const { return connect_hits_.load(); }
  27074. // Head of the last CONNECT request, as the proxy saw it on the wire.
  27075. std::string connect_request() const {
  27076. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27077. return connect_request_;
  27078. }
  27079. private:
  27080. static sockaddr_in loopback(int port) {
  27081. sockaddr_in a{};
  27082. a.sin_family = AF_INET;
  27083. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  27084. a.sin_port = htons(static_cast<unsigned short>(port));
  27085. return a;
  27086. }
  27087. static socket_t connect_to(int port) {
  27088. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  27089. if (sock == INVALID_SOCKET) { return sock; }
  27090. auto a = loopback(port);
  27091. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  27092. detail::close_socket(sock);
  27093. return INVALID_SOCKET;
  27094. }
  27095. return sock;
  27096. }
  27097. static bool send_all(socket_t sock, const char *data, size_t size) {
  27098. while (size > 0) {
  27099. auto n = detail::send_socket(sock, data, size, 0);
  27100. if (n <= 0) { return false; }
  27101. data += n;
  27102. size -= static_cast<size_t>(n);
  27103. }
  27104. return true;
  27105. }
  27106. void run() {
  27107. for (;;) {
  27108. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27109. if (stop_) {
  27110. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27111. return;
  27112. }
  27113. if (client == INVALID_SOCKET) { continue; }
  27114. serve(client);
  27115. detail::close_socket(client);
  27116. }
  27117. }
  27118. void serve(socket_t client) {
  27119. std::string head;
  27120. char buf[2048];
  27121. while (head.find("\r\n\r\n") == std::string::npos) {
  27122. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27123. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27124. if (n <= 0) { return; }
  27125. head.append(buf, static_cast<size_t>(n));
  27126. }
  27127. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27128. connect_hits_++;
  27129. {
  27130. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27131. connect_request_ = head;
  27132. }
  27133. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27134. if (!send_all(client, res.data(), res.size()) ||
  27135. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27136. return;
  27137. }
  27138. auto origin = connect_to(forward_port_);
  27139. if (origin == INVALID_SOCKET) { return; }
  27140. // When either side stops, shut both down so the other pump returns too.
  27141. auto pump = [&](socket_t from, socket_t to) {
  27142. char b[8192];
  27143. for (;;) {
  27144. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27145. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27146. }
  27147. detail::shutdown_socket(client);
  27148. detail::shutdown_socket(origin);
  27149. };
  27150. std::thread up([&] { pump(client, origin); });
  27151. pump(origin, client);
  27152. up.join();
  27153. detail::close_socket(origin);
  27154. }
  27155. int forward_port_;
  27156. ConnectReply reply_;
  27157. socket_t listen_sock_ = INVALID_SOCKET;
  27158. int port_ = 0;
  27159. std::thread th_;
  27160. std::atomic<bool> stop_{false};
  27161. std::atomic<int> connect_hits_{0};
  27162. mutable std::mutex connect_request_mutex_;
  27163. std::string connect_request_;
  27164. };
  27165. } // namespace proxy_tunnel_test
  27166. #ifdef CPPHTTPLIB_SSL_ENABLED
  27167. namespace proxy_tunnel_test {
  27168. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27169. class ScopedSSLServer {
  27170. public:
  27171. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27172. port_ = svr_.bind_to_any_port("127.0.0.1");
  27173. }
  27174. ~ScopedSSLServer() {
  27175. svr_.stop();
  27176. if (th_.joinable()) { th_.join(); }
  27177. }
  27178. SSLServer &svr() { return svr_; }
  27179. int port() const { return port_; }
  27180. void listen() {
  27181. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27182. svr_.wait_until_ready();
  27183. }
  27184. private:
  27185. SSLServer svr_;
  27186. std::thread th_;
  27187. int port_ = 0;
  27188. };
  27189. // Sends one request through the CONNECT proxy to the TLS origin with a
  27190. // credential configured for each hop, and checks that each credential reaches
  27191. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27192. // origin's (every header in origin_headers) on the tunnelled request.
  27193. void CredentialsStayWithTheirHop(
  27194. const std::function<void(SSLClient &)> &set_credentials,
  27195. const std::string &scheme,
  27196. const std::vector<std::string> &origin_headers = {"Authorization"},
  27197. bool stream = false) {
  27198. std::atomic<int> origin_hits{0};
  27199. std::atomic<bool> origin_saw_proxy_authz{false};
  27200. std::atomic<bool> origin_saw_headers{false};
  27201. ScopedSSLServer origin;
  27202. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27203. origin_hits++;
  27204. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27205. origin_saw_headers =
  27206. std::all_of(origin_headers.begin(), origin_headers.end(),
  27207. [&](const std::string &h) { return req.has_header(h); });
  27208. res.set_content("ok", "text/plain");
  27209. });
  27210. origin.listen();
  27211. ScopedConnectProxy proxy(origin.port());
  27212. ASSERT_NE(0, proxy.port());
  27213. // Pinned to 127.0.0.1 for the same reason as the test below.
  27214. SSLClient cli("127.0.0.1", origin.port());
  27215. cli.enable_server_certificate_verification(false);
  27216. cli.set_proxy("127.0.0.1", proxy.port());
  27217. set_credentials(cli);
  27218. if (stream) {
  27219. auto handle = cli.open_stream("GET", "/x");
  27220. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27221. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27222. } else {
  27223. auto res = cli.Get("/x");
  27224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27225. EXPECT_EQ(StatusCode::OK_200, res->status);
  27226. }
  27227. EXPECT_EQ(1, origin_hits.load());
  27228. EXPECT_EQ(1, proxy.connect_hits());
  27229. EXPECT_TRUE(origin_saw_headers.load());
  27230. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27231. << "Proxy-Authorization must not be sent inside the tunnel";
  27232. auto connect_req = proxy.connect_request();
  27233. EXPECT_NE(std::string::npos,
  27234. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27235. for (const auto &h : origin_headers) {
  27236. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27237. << h << " must not be sent to the proxy on CONNECT";
  27238. }
  27239. }
  27240. } // namespace proxy_tunnel_test
  27241. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27242. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27243. [](SSLClient &cli) {
  27244. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27245. cli.set_basic_auth("origin-user", "origin-pass");
  27246. },
  27247. "Basic");
  27248. }
  27249. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27250. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27251. [](SSLClient &cli) {
  27252. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27253. cli.set_basic_auth("origin-user", "origin-pass");
  27254. },
  27255. "Basic", {"Authorization"}, true);
  27256. }
  27257. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27258. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27259. [](SSLClient &cli) {
  27260. cli.set_proxy_bearer_token_auth("proxy-token");
  27261. cli.set_bearer_token_auth("origin-token");
  27262. },
  27263. "Bearer");
  27264. }
  27265. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27266. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27267. [](SSLClient &cli) {
  27268. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27269. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27270. {"Cookie", "sid=origin-session"},
  27271. {"X-Api-Key", "origin-key"}});
  27272. },
  27273. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27274. }
  27275. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27276. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27277. // retry; otherwise proxy creds would be sent to the origin.
  27278. std::atomic<int> origin_hits{0};
  27279. std::atomic<bool> origin_saw_proxy_authz{false};
  27280. proxy_tunnel_test::ScopedSSLServer origin;
  27281. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27282. origin_hits++;
  27283. if (req.has_header("Proxy-Authorization")) {
  27284. origin_saw_proxy_authz = true;
  27285. }
  27286. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27287. res.set_header("Proxy-Authenticate",
  27288. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27289. "algorithm=MD5");
  27290. });
  27291. origin.listen();
  27292. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27293. ASSERT_NE(0, proxy.port());
  27294. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27295. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27296. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27297. // and answer with its own status, making this test flaky.
  27298. SSLClient cli("127.0.0.1", origin.port());
  27299. cli.enable_server_certificate_verification(false);
  27300. cli.set_proxy("127.0.0.1", proxy.port());
  27301. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27302. auto res = cli.Get("/x");
  27303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27304. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27305. EXPECT_EQ(1, origin_hits.load());
  27306. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27307. EXPECT_EQ(1, proxy.connect_hits());
  27308. }
  27309. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27310. std::string origin_sni;
  27311. std::string origin_host;
  27312. proxy_tunnel_test::ScopedSSLServer origin;
  27313. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27314. origin_sni = req.sni();
  27315. origin_host = req.get_header_value("Host");
  27316. res.set_content("ok", "text/plain");
  27317. });
  27318. origin.listen();
  27319. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27320. ASSERT_NE(0, proxy.port());
  27321. SSLClient cli("origin.example", origin.port());
  27322. cli.enable_server_certificate_verification(false);
  27323. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27324. cli.set_proxy("127.0.0.1", proxy.port());
  27325. auto res = cli.Get("/x");
  27326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27327. EXPECT_EQ(StatusCode::OK_200, res->status);
  27328. auto port = std::to_string(origin.port());
  27329. auto target = "127.0.0.1:" + port;
  27330. auto connect_req = proxy.connect_request();
  27331. EXPECT_EQ(1, proxy.connect_hits());
  27332. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27333. EXPECT_NE(std::string::npos,
  27334. connect_req.find("\r\nHost: " + target + "\r\n"));
  27335. EXPECT_EQ("origin.example", origin_sni);
  27336. EXPECT_EQ("origin.example:" + port, origin_host);
  27337. }
  27338. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27339. proxy_tunnel_test::ScopedSSLServer origin;
  27340. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27341. res.set_content("ok", "text/plain");
  27342. });
  27343. origin.listen();
  27344. proxy_tunnel_test::ScopedConnectProxy proxy(
  27345. origin.port(), [](const std::string &head) -> std::string {
  27346. if (head.find(
  27347. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27348. std::string::npos) {
  27349. return proxy_tunnel_test::kTunnelEstablished;
  27350. }
  27351. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27352. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27353. "nonce=\"abc\", algorithm=MD5\r\n"
  27354. "Content-Length: 0\r\n\r\n";
  27355. });
  27356. ASSERT_NE(0, proxy.port());
  27357. SSLClient cli("origin.example", origin.port());
  27358. cli.enable_server_certificate_verification(false);
  27359. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27360. cli.set_proxy("127.0.0.1", proxy.port());
  27361. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27362. auto res = cli.Get("/x");
  27363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27364. EXPECT_EQ(StatusCode::OK_200, res->status);
  27365. // The retried CONNECT is the one the proxy saw last.
  27366. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27367. auto connect_req = proxy.connect_request();
  27368. EXPECT_EQ(2, proxy.connect_hits());
  27369. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27370. EXPECT_NE(std::string::npos,
  27371. connect_req.find("\r\nHost: " + target + "\r\n"));
  27372. }
  27373. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27374. proxy_tunnel_test::ScopedSSLServer origin;
  27375. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27376. res.set_content("ok", "text/plain");
  27377. });
  27378. origin.listen();
  27379. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27380. ASSERT_NE(0, proxy.port());
  27381. SSLClient cli("origin.example", origin.port());
  27382. cli.enable_server_certificate_verification(false);
  27383. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27384. cli.set_proxy("127.0.0.1", proxy.port());
  27385. auto res = cli.Get("/x");
  27386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27387. EXPECT_EQ(StatusCode::OK_200, res->status);
  27388. auto target = "origin.example:" + std::to_string(origin.port());
  27389. auto connect_req = proxy.connect_request();
  27390. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27391. EXPECT_NE(std::string::npos,
  27392. connect_req.find("\r\nHost: " + target + "\r\n"));
  27393. }
  27394. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27395. proxy_tunnel_test::ScopedSSLServer origin;
  27396. auto port = std::to_string(origin.port());
  27397. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27398. res.set_redirect("https://next.example:" + port + "/y");
  27399. });
  27400. origin.svr().Get("/y", [](const Request &, Response &res) {
  27401. res.set_content("ok", "text/plain");
  27402. });
  27403. origin.listen();
  27404. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27405. ASSERT_NE(0, proxy.port());
  27406. SSLClient cli("origin.example", origin.port());
  27407. cli.enable_server_certificate_verification(false);
  27408. cli.set_tunnel_hostname_addr_map(
  27409. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27410. cli.set_proxy("127.0.0.1", proxy.port());
  27411. cli.set_follow_location(true);
  27412. auto res = cli.Get("/x");
  27413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27414. EXPECT_EQ("ok", res->body);
  27415. // The last CONNECT is the redirect client's.
  27416. ASSERT_EQ(2, proxy.connect_hits());
  27417. auto target = "127.0.0.1:" + port;
  27418. auto connect_req = proxy.connect_request();
  27419. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27420. EXPECT_NE(std::string::npos,
  27421. connect_req.find("\r\nHost: " + target + "\r\n"));
  27422. }
  27423. #endif
  27424. namespace proxy_tunnel_test {
  27425. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27426. // anything else gets a 407 with `challenge`.
  27427. ConnectReply require_proxy_auth(const std::string &expected,
  27428. const std::string &challenge) {
  27429. return [=](const std::string &head) -> std::string {
  27430. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27431. std::string::npos) {
  27432. return kTunnelEstablished;
  27433. }
  27434. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27435. "Proxy-Authenticate: " +
  27436. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27437. };
  27438. }
  27439. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27440. // request, then echoes.
  27441. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27442. ws.send(
  27443. "authorization:" + req.get_header_value("Authorization") +
  27444. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27445. std::string msg;
  27446. while (ws.read(msg)) {
  27447. ws.send(msg);
  27448. }
  27449. }
  27450. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27451. class ScopedWebSocketOrigin {
  27452. public:
  27453. ScopedWebSocketOrigin() {
  27454. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27455. server_.listen();
  27456. }
  27457. int port() const { return server_.port(); }
  27458. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27459. std::string url() const {
  27460. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27461. }
  27462. private:
  27463. no_proxy_test::ScopedServer server_;
  27464. };
  27465. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27466. // passed as a constructor header, and checks that each reaches only its hop.
  27467. void WebSocketCredentialsStayWithTheirHop(
  27468. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27469. const std::string &proxy_authz, const std::string &origin_authz) {
  27470. ScopedWebSocketOrigin origin;
  27471. ScopedConnectProxy proxy(
  27472. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27473. ASSERT_NE(0, proxy.port());
  27474. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27475. client.set_proxy("127.0.0.1", proxy.port());
  27476. set_proxy_credentials(client);
  27477. auto res = client.connect();
  27478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27479. std::string msg;
  27480. ASSERT_TRUE(client.read(msg));
  27481. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27482. client.close();
  27483. EXPECT_EQ(1, proxy.connect_hits());
  27484. EXPECT_EQ(std::string::npos,
  27485. proxy.connect_request().find("\r\nAuthorization: "))
  27486. << "origin credentials must not be sent to the proxy";
  27487. }
  27488. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  27489. void WebSocketSetterCredentialsStayWithTheirHop(
  27490. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  27491. const std::string &proxy_authz, const std::string &origin_authz) {
  27492. ScopedWebSocketOrigin origin;
  27493. ScopedConnectProxy proxy(
  27494. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27495. ASSERT_NE(0, proxy.port());
  27496. ws::WebSocketClient client(origin.url());
  27497. client.set_proxy("127.0.0.1", proxy.port());
  27498. set_credentials(client);
  27499. auto res = client.connect();
  27500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27501. std::string msg;
  27502. ASSERT_TRUE(client.read(msg));
  27503. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27504. client.close();
  27505. EXPECT_EQ(1, proxy.connect_hits());
  27506. EXPECT_EQ(std::string::npos,
  27507. proxy.connect_request().find("\r\nAuthorization: "))
  27508. << "origin credentials must not be sent to the proxy";
  27509. }
  27510. } // namespace proxy_tunnel_test
  27511. namespace {
  27512. // Connects `client` and returns the Authorization header its upgrade
  27513. // request carried, or "<failed>" when the connection could not be opened.
  27514. std::string websocket_authorization(ws::WebSocketClient &client) {
  27515. if (!client.connect()) { return "<failed>"; }
  27516. std::string msg;
  27517. if (!client.read(msg)) { return "<failed>"; }
  27518. client.close();
  27519. auto prefix = std::string("authorization:");
  27520. auto end = msg.find("|proxy-authorization:");
  27521. return msg.substr(prefix.size(), end - prefix.size());
  27522. }
  27523. } // namespace
  27524. TEST(WebSocketClientAuthTest, BasicAuth) {
  27525. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27526. ws::WebSocketClient client(origin.url());
  27527. client.set_basic_auth("user", "pass");
  27528. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27529. websocket_authorization(client));
  27530. }
  27531. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  27532. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27533. ws::WebSocketClient client(origin.url());
  27534. client.set_basic_auth("user", "");
  27535. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  27536. websocket_authorization(client));
  27537. }
  27538. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  27539. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27540. ws::WebSocketClient client(origin.url());
  27541. client.set_bearer_token_auth("token123");
  27542. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  27543. }
  27544. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  27545. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27546. ws::WebSocketClient client(origin.url());
  27547. client.set_bearer_token_auth("token123");
  27548. client.set_basic_auth("user", "pass");
  27549. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27550. websocket_authorization(client));
  27551. }
  27552. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  27553. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27554. ws::WebSocketClient client(origin.url(),
  27555. {{"Authorization", "Bearer from-header"}});
  27556. client.set_bearer_token_auth("from-setter");
  27557. client.set_basic_auth("user", "pass");
  27558. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  27559. }
  27560. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  27561. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27562. ws::WebSocketClient client(origin.url());
  27563. EXPECT_EQ("", websocket_authorization(client));
  27564. client.set_bearer_token_auth("first");
  27565. EXPECT_EQ("Bearer first", websocket_authorization(client));
  27566. client.set_bearer_token_auth("second");
  27567. EXPECT_EQ("Bearer second", websocket_authorization(client));
  27568. client.set_bearer_token_auth("");
  27569. EXPECT_EQ("", websocket_authorization(client));
  27570. }
  27571. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27572. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27573. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27574. ASSERT_NE(0, proxy.port());
  27575. ws::WebSocketClient client(origin.url());
  27576. client.set_proxy("127.0.0.1", proxy.port());
  27577. auto res = client.connect();
  27578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27579. std::string msg;
  27580. ASSERT_TRUE(client.read(msg));
  27581. ASSERT_TRUE(client.send("hello"));
  27582. ASSERT_TRUE(client.read(msg));
  27583. EXPECT_EQ("hello", msg);
  27584. client.close();
  27585. EXPECT_EQ(1, proxy.connect_hits());
  27586. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27587. auto connect_req = proxy.connect_request();
  27588. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27589. EXPECT_NE(std::string::npos,
  27590. connect_req.find("\r\nHost: " + target + "\r\n"));
  27591. }
  27592. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27593. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27594. [](ws::WebSocketClient &cli) {
  27595. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27596. },
  27597. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27598. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27599. }
  27600. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27601. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27602. [](ws::WebSocketClient &cli) {
  27603. cli.set_proxy_bearer_token_auth("proxy-token");
  27604. },
  27605. "Bearer proxy-token", "Bearer origin-token");
  27606. }
  27607. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  27608. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27609. [](ws::WebSocketClient &cli) {
  27610. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27611. cli.set_basic_auth("origin-user", "origin-pass");
  27612. },
  27613. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27614. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27615. }
  27616. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  27617. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27618. [](ws::WebSocketClient &cli) {
  27619. cli.set_proxy_bearer_token_auth("proxy-token");
  27620. cli.set_bearer_token_auth("origin-token");
  27621. },
  27622. "Bearer proxy-token", "Bearer origin-token");
  27623. }
  27624. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27625. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27626. proxy_tunnel_test::ScopedConnectProxy proxy(
  27627. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27628. "Basic " + detail::base64_encode("proxy-user:"),
  27629. "Basic realm=\"proxy\""));
  27630. ASSERT_NE(0, proxy.port());
  27631. ws::WebSocketClient client(origin.url());
  27632. client.set_proxy("127.0.0.1", proxy.port());
  27633. client.set_proxy_basic_auth("proxy-user", "");
  27634. auto res = client.connect();
  27635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27636. client.close();
  27637. EXPECT_EQ(1, proxy.connect_hits());
  27638. }
  27639. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27640. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27641. proxy_tunnel_test::ScopedConnectProxy proxy(
  27642. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27643. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27644. ASSERT_NE(0, proxy.port());
  27645. ws::WebSocketClient client(origin.url());
  27646. client.set_proxy("127.0.0.1", proxy.port());
  27647. auto res = client.connect();
  27648. EXPECT_FALSE(res);
  27649. EXPECT_EQ(Error::ProxyConnection, res.error());
  27650. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27651. EXPECT_EQ("Basic realm=\"proxy\"",
  27652. res.get_header_value("Proxy-Authenticate"));
  27653. EXPECT_FALSE(client.is_open());
  27654. }
  27655. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27656. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27657. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27658. ASSERT_NE(0, proxy.port());
  27659. ws::WebSocketClient client(origin.url());
  27660. client.set_proxy("127.0.0.1", proxy.port());
  27661. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27662. client.set_no_proxy({"127.0.0.1"});
  27663. auto res = client.connect();
  27664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27665. std::string msg;
  27666. ASSERT_TRUE(client.read(msg));
  27667. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27668. << "proxy credentials must not reach a bypassed origin";
  27669. client.close();
  27670. EXPECT_EQ(0, proxy.connect_hits());
  27671. }
  27672. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27673. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27674. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27675. ASSERT_NE(0, proxy.port());
  27676. ws::WebSocketClient client(origin.url());
  27677. client.set_proxy("127.0.0.1", proxy.port());
  27678. ASSERT_TRUE(client.connect());
  27679. ASSERT_TRUE(client.connect());
  27680. client.close();
  27681. EXPECT_EQ(2, proxy.connect_hits());
  27682. }
  27683. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27684. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27685. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27686. ASSERT_NE(0, proxy.port());
  27687. auto port = std::to_string(origin.port());
  27688. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27689. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27690. client.set_proxy("127.0.0.1", proxy.port());
  27691. auto res = client.connect();
  27692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27693. std::string msg;
  27694. ASSERT_TRUE(client.read(msg));
  27695. client.close();
  27696. EXPECT_EQ(1, proxy.connect_hits());
  27697. auto target = "127.0.0.1:" + port;
  27698. auto connect_req = proxy.connect_request();
  27699. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27700. EXPECT_NE(std::string::npos,
  27701. connect_req.find("\r\nHost: " + target + "\r\n"));
  27702. }
  27703. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27704. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27705. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27706. ASSERT_NE(0, proxy.port());
  27707. auto port = std::to_string(origin.port());
  27708. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27709. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27710. client.set_proxy("127.0.0.1", proxy.port());
  27711. auto res = client.connect();
  27712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27713. client.close();
  27714. auto target = "origin.example:" + port;
  27715. auto connect_req = proxy.connect_request();
  27716. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27717. EXPECT_NE(std::string::npos,
  27718. connect_req.find("\r\nHost: " + target + "\r\n"));
  27719. }
  27720. #ifdef CPPHTTPLIB_SSL_ENABLED
  27721. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27722. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27723. proxy_tunnel_test::ScopedConnectProxy proxy(
  27724. origin.port(), [](const std::string &head) -> std::string {
  27725. if (head.find(
  27726. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27727. std::string::npos) {
  27728. return proxy_tunnel_test::kTunnelEstablished;
  27729. }
  27730. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27731. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27732. "nonce=\"abc\", algorithm=MD5\r\n"
  27733. "Content-Length: 0\r\n\r\n";
  27734. });
  27735. ASSERT_NE(0, proxy.port());
  27736. ws::WebSocketClient client(origin.url());
  27737. client.set_proxy("127.0.0.1", proxy.port());
  27738. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27739. auto res = client.connect();
  27740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27741. std::string msg;
  27742. ASSERT_TRUE(client.read(msg));
  27743. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27744. client.close();
  27745. EXPECT_EQ(2, proxy.connect_hits());
  27746. }
  27747. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27748. proxy_tunnel_test::ScopedSSLServer origin;
  27749. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27750. origin.listen();
  27751. proxy_tunnel_test::ScopedConnectProxy proxy(
  27752. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27753. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27754. ASSERT_NE(0, proxy.port());
  27755. ws::WebSocketClient client(
  27756. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27757. client.enable_server_certificate_verification(false);
  27758. client.set_proxy("127.0.0.1", proxy.port());
  27759. client.set_proxy_bearer_token_auth("proxy-token");
  27760. auto res = client.connect();
  27761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27762. std::string msg;
  27763. ASSERT_TRUE(client.read(msg));
  27764. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27765. << "Proxy-Authorization must not be sent inside the tunnel";
  27766. client.close();
  27767. EXPECT_EQ(1, proxy.connect_hits());
  27768. }
  27769. #endif