1
0

test.cc 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  253. // Another socket in the working directory, which a Location can name as
  254. // its host
  255. const auto other_path = "other-" + pathname_.substr(2);
  256. httplib::Server svr;
  257. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  258. // An absolute Location naming the Host this client sends
  259. res.set_redirect("http://localhost" + pattern_);
  260. });
  261. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  262. res.set_redirect("http://" + other_path + pattern_);
  263. });
  264. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  265. res.set_redirect("http://mapped.test" + pattern_);
  266. });
  267. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  268. res.set_header("X-Auth", req.get_header_value("Authorization"));
  269. res.set_content(content_, "text/plain");
  270. });
  271. httplib::Server other;
  272. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  273. res.set_content("other", "text/plain");
  274. });
  275. std::thread t{[&] {
  276. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  277. }};
  278. std::thread t2{[&] {
  279. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  280. }};
  281. auto se = detail::scope_exit([&] {
  282. svr.stop();
  283. other.stop();
  284. t.join();
  285. t2.join();
  286. std::remove(other_path.c_str());
  287. });
  288. svr.wait_until_ready();
  289. other.wait_until_ready();
  290. httplib::Client cli{pathname_};
  291. cli.set_address_family(AF_UNIX);
  292. cli.set_follow_location(true);
  293. cli.set_bearer_token_auth("token");
  294. // Another host: the same socket, without the credentials
  295. auto res = cli.Get("/cross");
  296. ASSERT_TRUE(res) << "error: " << res.error();
  297. EXPECT_EQ(StatusCode::OK_200, res->status);
  298. EXPECT_EQ(content_, res->body);
  299. EXPECT_EQ("", res->get_header_value("X-Auth"));
  300. // localhost is this client's own host
  301. res = cli.Get("/redirect");
  302. ASSERT_TRUE(res) << "error: " << res.error();
  303. EXPECT_EQ(StatusCode::OK_200, res->status);
  304. EXPECT_EQ(content_, res->body);
  305. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  306. // A host the caller mapped to a socket goes there
  307. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  308. res = cli.Get("/mapped");
  309. ASSERT_TRUE(res) << "error: " << res.error();
  310. EXPECT_EQ(StatusCode::OK_200, res->status);
  311. EXPECT_EQ("other", res->body);
  312. }
  313. #ifndef _WIN32
  314. TEST(SocketStream, wait_writable_UNIX) {
  315. int fds[2];
  316. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  317. const auto asSocketStream = [&](socket_t fd,
  318. std::function<bool(Stream &)> func) {
  319. return detail::process_client_socket(
  320. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  321. };
  322. asSocketStream(fds[0], [&](Stream &s0) {
  323. EXPECT_EQ(s0.socket(), fds[0]);
  324. EXPECT_TRUE(s0.wait_writable());
  325. EXPECT_TRUE(s0.is_peer_alive());
  326. EXPECT_EQ(0, close(fds[1]));
  327. EXPECT_FALSE(s0.is_peer_alive());
  328. return true;
  329. });
  330. EXPECT_EQ(0, close(fds[0]));
  331. }
  332. TEST(SocketStream, wait_writable_INET) {
  333. sockaddr_in addr;
  334. memset(&addr, 0, sizeof(addr));
  335. addr.sin_family = AF_INET;
  336. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  337. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  338. int disconnected_svr_sock = -1;
  339. std::thread svr{[&] {
  340. const int s = socket(AF_INET, SOCK_STREAM, 0);
  341. ASSERT_LE(0, s);
  342. // PORT + 1 is shared with the SSL redirect tests and with
  343. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  344. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  345. // because that happens on a worker thread the ASSERT does not stop the
  346. // test: it runs on and fails at the disconnected_svr_sock check instead.
  347. default_socket_options(s);
  348. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  349. ASSERT_EQ(0, listen(s, 1));
  350. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  351. ASSERT_EQ(0, close(s));
  352. }};
  353. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  354. std::thread cli{[&] {
  355. const int s = socket(AF_INET, SOCK_STREAM, 0);
  356. ASSERT_LE(0, s);
  357. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  358. ASSERT_EQ(0, close(s));
  359. }};
  360. cli.join();
  361. svr.join();
  362. ASSERT_NE(disconnected_svr_sock, -1);
  363. const auto asSocketStream = [&](socket_t fd,
  364. std::function<bool(Stream &)> func) {
  365. return detail::process_client_socket(
  366. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  367. };
  368. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  369. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  370. // wait_writable() returns true because select_write() only checks if the
  371. // send buffer has space. Peer disconnection is detected later by send().
  372. EXPECT_TRUE(ss.wait_writable());
  373. return true;
  374. });
  375. ASSERT_EQ(0, close(disconnected_svr_sock));
  376. }
  377. #endif // #ifndef _WIN32
  378. TEST(SetSocketOptTest, TcpNoDelay) {
  379. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  380. ASSERT_NE(sock, INVALID_SOCKET);
  381. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  382. int val = 0;
  383. socklen_t len = sizeof(val);
  384. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  385. reinterpret_cast<char *>(&val), &len));
  386. EXPECT_NE(val, 0);
  387. detail::close_socket(sock);
  388. }
  389. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  390. // accept() reports failures through WSAGetLastError() on Windows and through
  391. // errno everywhere else. Asking the wrong one is what made the accept loop
  392. // treat every recoverable failure as fatal on Windows.
  393. struct Classification {
  394. bool resource;
  395. bool transient;
  396. };
  397. auto classify = [](int err) {
  398. #ifdef _WIN32
  399. WSASetLastError(err);
  400. #else
  401. errno = err;
  402. #endif
  403. // Read both before asserting: an assertion may clobber the error slot.
  404. Classification c;
  405. c.resource = detail::is_accept_resource_error();
  406. c.transient = detail::is_accept_transient_error();
  407. return c;
  408. };
  409. #ifdef _WIN32
  410. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  411. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  412. WSAECONNRESET, WSAECONNABORTED};
  413. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  414. #else
  415. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  416. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  417. ECONNABORTED};
  418. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  419. #endif
  420. for (auto err : resource_errors) {
  421. const auto c = classify(err);
  422. EXPECT_TRUE(c.resource) << "error " << err;
  423. EXPECT_FALSE(c.transient) << "error " << err;
  424. }
  425. for (auto err : transient_errors) {
  426. const auto c = classify(err);
  427. EXPECT_TRUE(c.transient) << "error " << err;
  428. EXPECT_FALSE(c.resource) << "error " << err;
  429. }
  430. for (auto err : fatal_errors) {
  431. const auto c = classify(err);
  432. EXPECT_FALSE(c.resource) << "error " << err;
  433. EXPECT_FALSE(c.transient) << "error " << err;
  434. }
  435. #ifdef _WIN32
  436. WSASetLastError(0);
  437. #else
  438. errno = 0;
  439. #endif
  440. }
  441. TEST(ClientTest, MoveConstructible) {
  442. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  443. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  444. }
  445. TEST(ClientTest, MoveAssignable) {
  446. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  447. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  448. }
  449. #ifdef _WIN32
  450. TEST(StartupTest, WSAStartup) {
  451. WSADATA wsaData;
  452. int ret = WSAStartup(0x0002, &wsaData);
  453. ASSERT_EQ(0, ret);
  454. }
  455. #endif
  456. TEST(DecodePathTest, PercentCharacter) {
  457. EXPECT_EQ(
  458. decode_path_component(
  459. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  460. U8("descrip=Gastos áéíóúñÑ 6"));
  461. }
  462. TEST(DecodePathTest, PercentCharacterNUL) {
  463. string expected;
  464. expected.push_back('x');
  465. expected.push_back('\0');
  466. expected.push_back('x');
  467. EXPECT_EQ(decode_path_component("x%00x"), expected);
  468. }
  469. TEST(DecodePathTest, UnicodeEncoding) {
  470. // %u0041 = 'A' (1-byte UTF-8)
  471. EXPECT_EQ("A", decode_path_component("%u0041"));
  472. // %u00E9 = 'é' (2-byte UTF-8)
  473. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  474. // %u3042 = 'あ' (3-byte UTF-8)
  475. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  476. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  477. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  478. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  479. // neighbours)
  480. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  481. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  482. }
  483. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  484. // A sign or whitespace inside the two-character escape window must not be
  485. // accepted as a valid percent-encoding; the sequence is passed through
  486. // literally, matching decode_uri_component / decode_path_component.
  487. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  488. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  489. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  490. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  491. // Well-formed escapes still decode.
  492. EXPECT_EQ("-", decode_query_component("%2D", false));
  493. EXPECT_EQ("A", decode_query_component("%41", false));
  494. }
  495. TEST(SanitizeFilenameTest, VariousPatterns) {
  496. // Path traversal
  497. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  498. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  499. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  500. // Normal and edge cases
  501. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  502. EXPECT_EQ("filename.txt",
  503. httplib::sanitize_filename("/path/to/filename.txt"));
  504. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  505. EXPECT_EQ("", httplib::sanitize_filename(".."));
  506. EXPECT_EQ("", httplib::sanitize_filename(""));
  507. // Null bytes stripped
  508. EXPECT_EQ("safe.txt",
  509. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  510. // Whitespace-only rejected
  511. EXPECT_EQ("", httplib::sanitize_filename(" "));
  512. }
  513. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  514. // before it is dropped; anywhere else it is an ordinary file name character.
  515. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  516. #ifdef _WIN32
  517. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  518. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  519. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  520. #else
  521. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  522. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  523. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  524. #endif
  525. }
  526. // Forward declaration (see the base64_encode note below): split builds move the
  527. // definition into httplib.cc, so re-declaring it here lets the test link.
  528. namespace httplib {
  529. namespace detail {
  530. bool is_chunked_transfer_encoding(const Headers &headers);
  531. } // namespace detail
  532. } // namespace httplib
  533. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  534. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  535. auto make = [](std::initializer_list<const char *> lines) {
  536. Headers h;
  537. for (auto te : lines) {
  538. if (te) { h.emplace("Transfer-Encoding", te); }
  539. }
  540. return h;
  541. };
  542. // Sole coding, matched case-insensitively.
  543. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  544. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  545. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  546. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  547. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  548. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  549. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  550. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  551. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  552. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  553. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  554. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  555. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  556. // were received, into one list. Headers preserves that order, so the answer
  557. // is decided by the last coding of the last line and the order the lines
  558. // arrived in is significant.
  559. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  560. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  561. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  562. // The split can fall anywhere in the list.
  563. EXPECT_TRUE(
  564. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  565. EXPECT_FALSE(
  566. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  567. // A trailing line naming no coding leaves the list ending in nothing, so it
  568. // must not inherit the chunked from the line before it.
  569. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  570. }
  571. // Forward declarations (see the base64_encode note below).
  572. namespace httplib {
  573. namespace detail {
  574. bool parse_status_line(const char *line, std::string &version, int &status,
  575. std::string &reason);
  576. std::string file_extension(const std::string &path);
  577. std::string
  578. find_content_type(const std::string &path,
  579. const std::map<std::string, std::string> &user_data,
  580. const std::string &default_content_type);
  581. bool can_compress_content_type(const std::string &content_type);
  582. bool is_prohibited_header_name(const std::string &name);
  583. bool is_valid_path(const std::string &path);
  584. #ifdef CPPHTTPLIB_SSL_ENABLED
  585. bool match_hostname(const std::string &pattern, const std::string &hostname);
  586. #endif
  587. } // namespace detail
  588. } // namespace httplib
  589. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  590. struct {
  591. const char *line;
  592. const char *version;
  593. int status;
  594. const char *reason;
  595. } cases[] = {
  596. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  597. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  598. // The reason phrase may be empty, or left out along with its space.
  599. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  600. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  601. };
  602. for (const auto &c : cases) {
  603. std::string version;
  604. int status = 0;
  605. std::string reason = "unset";
  606. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  607. << c.line;
  608. EXPECT_EQ(c.version, version);
  609. EXPECT_EQ(c.status, status);
  610. EXPECT_EQ(c.reason, reason);
  611. }
  612. }
  613. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  614. const char *lines[] = {
  615. "HTTP/2 200 OK\r\n",
  616. "HTTP/1.2 200 OK\r\n",
  617. "HTTP/1.1 20 OK\r\n",
  618. "HTTP/1.1 2000 OK\r\n",
  619. "HTTP/1.1 2x0 OK\r\n",
  620. "HTTP/1.1 200 OK\r\n",
  621. "HTTP/1.1 200OK\r\n",
  622. "HTTP/1.1 200 O\rK\r\n",
  623. "HTTP/1.1 200 OK",
  624. "HTTP/1.1 200 OK\r\nX",
  625. "",
  626. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  627. "HTTP/1.1 200 OK\n",
  628. #endif
  629. };
  630. for (auto line : lines) {
  631. std::string version;
  632. int status = 0;
  633. std::string reason;
  634. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  635. << line;
  636. }
  637. }
  638. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  639. // Long enough to overflow the stack when matched with std::regex.
  640. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  641. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  642. std::string version;
  643. int status = 0;
  644. std::string reason;
  645. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  646. EXPECT_EQ(200, status);
  647. EXPECT_EQ(long_reason, reason);
  648. }
  649. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  650. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  651. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  652. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  653. EXPECT_EQ("", detail::file_extension("noext"));
  654. EXPECT_EQ("", detail::file_extension("a."));
  655. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  656. EXPECT_EQ("", detail::file_extension("a.b-c"));
  657. // Long enough to overflow the stack when matched with std::regex.
  658. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  659. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  660. }
  661. #ifdef CPPHTTPLIB_SSL_ENABLED
  662. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  663. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  664. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  665. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  666. // A wildcard needs two labels after it, in the leftmost label only
  667. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  668. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  669. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  670. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  671. EXPECT_FALSE(
  672. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  673. // No name may have an empty label
  674. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  675. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  676. }
  677. #endif
  678. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  679. detail::case_ignore::hash hash;
  680. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  681. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  682. // Long enough to overflow the stack if hashed one call per character.
  683. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  684. }
  685. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  686. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  687. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  688. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  689. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  690. // Same 26-bit hash as html, svg and js.
  691. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  692. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  693. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  694. }
  695. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  696. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  697. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  698. }
  699. }
  700. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  701. // name anywhere else.
  702. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  703. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  704. #ifdef _WIN32
  705. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  706. #else
  707. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  708. #endif
  709. }
  710. }
  711. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  712. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  713. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  714. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  715. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  716. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  717. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  718. // Same 26-bit hash as application/json.
  719. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  720. }
  721. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  722. Request req;
  723. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  724. EXPECT_TRUE(req.is_multipart_form_data());
  725. std::string boundary;
  726. EXPECT_TRUE(detail::parse_multipart_boundary(
  727. req.get_header_value("Content-Type"), boundary));
  728. EXPECT_EQ("x", boundary);
  729. }
  730. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  731. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  732. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  733. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  734. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  735. // Same 26-bit hash as REMOTE_ADDR.
  736. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  737. }
  738. // Forward declaration: in split builds split.py strips `inline` and moves the
  739. // definition into httplib.cc, so detail::base64_encode is not visible from the
  740. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  741. // in both header-only and split builds.
  742. namespace httplib {
  743. namespace detail {
  744. std::string base64_encode(const std::string &in);
  745. } // namespace detail
  746. } // namespace httplib
  747. TEST(Base64EncodeTest, KnownAnswers) {
  748. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  749. // where the accumulator's top bit is already set before the next shift.
  750. EXPECT_EQ("", detail::base64_encode(""));
  751. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  752. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  753. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  754. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  755. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  756. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  757. // High bytes keep the top bit set across several rounds.
  758. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  759. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  760. }
  761. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  762. string unescapedCharacters = "-_.!~*'()";
  763. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  764. }
  765. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  766. string reservedCharacters = ";,/?:@&=+$";
  767. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  768. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  769. }
  770. TEST(ClientQueryOrder, PreserveOrder) {
  771. // This test reproduces Issue #2259: client may reorder query parameters
  772. // when sending a GET request. The expected behavior is that the client
  773. // preserves the original query string order when the caller supplied it
  774. // as part of the path.
  775. Server svr;
  776. svr.Get("/", [&](const Request &req, Response &res) {
  777. // Echo back the raw target so the test can assert ordering
  778. res.set_content(req.target, "text/plain");
  779. });
  780. std::thread t{[&] { svr.listen(HOST, PORT); }};
  781. auto se = detail::scope_exit([&] {
  782. svr.stop();
  783. t.join();
  784. ASSERT_FALSE(svr.is_running());
  785. });
  786. svr.wait_until_ready();
  787. Client cli(HOST, PORT);
  788. ASSERT_TRUE(cli.is_valid());
  789. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  790. auto res = cli.Get(original);
  791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  792. // Expect the echoed target to exactly match the original path (order
  793. // preserved)
  794. EXPECT_EQ(res->body, original);
  795. }
  796. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  797. string chineseCharacters = U8("中国語");
  798. string russianCharacters = U8("дом");
  799. string brazilianCharacters = U8("óculos");
  800. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  801. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  802. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  803. "%D0%B4%D0%BE%D0%BC");
  804. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  805. }
  806. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  807. string unescapedCharacters = "-_.!~*'()";
  808. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  809. }
  810. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  811. string reservedCharacters = ";,/?:@&=+$";
  812. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  813. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  814. }
  815. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  816. string chineseCharacters = U8("中国語");
  817. string russianCharacters = U8("дом");
  818. string brazilianCharacters = U8("óculos");
  819. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  820. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  821. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  822. "%D0%B4%D0%BE%D0%BC");
  823. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  824. }
  825. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  826. // Issue #2082 use case: encoding path component with ampersand
  827. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  828. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  829. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  830. }
  831. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  832. string unescapedCharacters = "-_.!~*'()";
  833. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  834. }
  835. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  836. string reservedCharacters = ";,/?:@&=+$#";
  837. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  838. }
  839. TEST(EncodeUriTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  846. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  847. }
  848. TEST(EncodeUriTest, TestCompleteUri) {
  849. string uri =
  850. "https://example.com/path/to/resource?query=value&param=test#fragment";
  851. EXPECT_EQ(
  852. httplib::encode_uri(uri),
  853. "https://example.com/path/to/resource?query=value&param=test#fragment");
  854. }
  855. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  856. string uri =
  857. "https://example.com/path with spaces/file name.html?q=hello world";
  858. EXPECT_EQ(httplib::encode_uri(uri),
  859. "https://example.com/path%20with%20spaces/"
  860. "file%20name.html?q=hello%20world");
  861. }
  862. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  863. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  864. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  865. }
  866. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  867. string unescapedCharacters = "-_.!~*'()";
  868. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  869. }
  870. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  871. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  872. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  873. string encodedBrazilian = "%C3%B3culos";
  874. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  875. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  876. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  877. }
  878. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  879. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  880. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  881. "Piri Tommy Villiers - on & on");
  882. }
  883. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  884. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  885. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  886. }
  887. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  888. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  889. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  890. }
  891. TEST(DecodeUriTest, TestUTF8Characters) {
  892. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  893. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  894. string encodedBrazilian = "%C3%B3culos";
  895. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  896. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  897. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  898. }
  899. TEST(DecodeUriTest, TestCompleteUri) {
  900. string encodedUri = "https://example.com/path%20with%20spaces/"
  901. "file%20name.html?q=hello%20world";
  902. EXPECT_EQ(
  903. httplib::decode_uri(encodedUri),
  904. "https://example.com/path with spaces/file name.html?q=hello world");
  905. }
  906. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  907. string original =
  908. "https://example.com/path with spaces/file name.html?q=hello world";
  909. string encoded = httplib::encode_uri(original);
  910. string decoded = httplib::decode_uri(encoded);
  911. EXPECT_EQ(decoded, original);
  912. }
  913. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  914. // decode_uri is the inverse of encode_uri: an escaped reserved character
  915. // stays encoded so it is not promoted into a real delimiter, while
  916. // non-reserved escapes still decode (like JS decodeURI).
  917. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  918. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  919. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  920. "%3F%3A%40%26%3D%2B%24%2C%3B");
  921. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  922. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  923. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  924. "http://example.com/a%2Fb");
  925. // decode_uri_component still decodes the reserved character.
  926. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  927. }
  928. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  929. string original = "Piri Tommy Villiers - on & on";
  930. string encoded = httplib::encode_uri_component(original);
  931. string decoded = httplib::decode_uri_component(encoded);
  932. EXPECT_EQ(decoded, original);
  933. }
  934. TEST(TrimTests, TrimStringTests) {
  935. EXPECT_EQ("abc", detail::trim_copy("abc"));
  936. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  937. EXPECT_TRUE(detail::trim_copy("").empty());
  938. }
  939. TEST(AsciiTest, LocaleIndependentClassification) {
  940. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  941. // which consult the global C locale: std::isalnum(0xC5) can return true
  942. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  943. // helpers must classify every byte by the ASCII grammar alone.
  944. for (int i = 0; i < 256; i++) {
  945. auto c = static_cast<char>(i);
  946. auto is_digit = i >= '0' && i <= '9';
  947. auto is_upper = i >= 'A' && i <= 'Z';
  948. auto is_lower = i >= 'a' && i <= 'z';
  949. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  950. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  951. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  952. << "byte " << i;
  953. }
  954. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  955. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  956. // Non-ASCII bytes must be percent-encoded, never passed through as
  957. // alphanumeric.
  958. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  959. }
  960. TEST(FromCharsTest, Double) {
  961. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  962. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  963. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  964. auto parse = [](const std::string &s, double &v) {
  965. return detail::from_chars(s.data(), s.data() + s.size(), v);
  966. };
  967. double v = -1.0;
  968. // Representative quality values.
  969. EXPECT_EQ(parse("0", v).ec, std::errc{});
  970. EXPECT_DOUBLE_EQ(v, 0.0);
  971. EXPECT_EQ(parse("1", v).ec, std::errc{});
  972. EXPECT_DOUBLE_EQ(v, 1.0);
  973. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  974. EXPECT_DOUBLE_EQ(v, 0.8);
  975. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  976. EXPECT_DOUBLE_EQ(v, 0.001);
  977. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  978. EXPECT_DOUBLE_EQ(v, 1.0);
  979. // A missing integer or fractional part is tolerated.
  980. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  981. EXPECT_DOUBLE_EQ(v, 0.5);
  982. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  983. EXPECT_DOUBLE_EQ(v, 5.0);
  984. // Values outside [0, 1] still parse; the caller range-checks them.
  985. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  986. EXPECT_DOUBLE_EQ(v, 123.456);
  987. // Stops at the first byte that is not part of the number and reports where.
  988. std::string trailing = "0.9, text/html";
  989. auto r = parse(trailing, v);
  990. EXPECT_EQ(r.ec, std::errc{});
  991. EXPECT_DOUBLE_EQ(v, 0.9);
  992. EXPECT_EQ(*r.ptr, ',');
  993. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  994. // outright, and an 'e'/'E' simply ends the number.
  995. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  996. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  997. std::string exp_input = "1.5e3";
  998. r = parse(exp_input, v);
  999. EXPECT_EQ(r.ec, std::errc{});
  1000. EXPECT_DOUBLE_EQ(v, 1.5);
  1001. EXPECT_EQ(*r.ptr, 'e');
  1002. // Invalid inputs.
  1003. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1004. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1005. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1006. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1007. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1008. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1009. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1010. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1011. std::errc{});
  1012. EXPECT_DOUBLE_EQ(v, 0.0);
  1013. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1014. std::errc{});
  1015. EXPECT_GE(v, 0.0);
  1016. EXPECT_LE(v, 1.0);
  1017. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1018. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1019. }
  1020. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1021. // Simple case without quality values
  1022. std::vector<std::string> result1;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "text/html,application/json,text/plain", result1));
  1025. EXPECT_EQ(result1.size(), 3U);
  1026. EXPECT_EQ(result1[0], "text/html");
  1027. EXPECT_EQ(result1[1], "application/json");
  1028. EXPECT_EQ(result1[2], "text/plain");
  1029. // With quality values
  1030. std::vector<std::string> result2;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1033. EXPECT_EQ(result2.size(), 3U);
  1034. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1035. EXPECT_EQ(result2[1], "text/html");
  1036. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1037. }
  1038. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1039. // Mixed with and without quality values
  1040. std::vector<std::string> result;
  1041. EXPECT_TRUE(detail::parse_accept_header(
  1042. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1043. EXPECT_EQ(result.size(), 3U);
  1044. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1045. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1046. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1047. }
  1048. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1049. // Empty header
  1050. std::vector<std::string> empty_result;
  1051. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1052. EXPECT_TRUE(empty_result.empty());
  1053. // Single type
  1054. std::vector<std::string> single_result;
  1055. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1056. EXPECT_EQ(single_result.size(), 1U);
  1057. EXPECT_EQ(single_result[0], "application/json");
  1058. // Wildcard types
  1059. std::vector<std::string> wildcard_result;
  1060. EXPECT_TRUE(detail::parse_accept_header(
  1061. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1062. EXPECT_EQ(wildcard_result.size(), 3U);
  1063. EXPECT_EQ(wildcard_result[0], "application/json");
  1064. EXPECT_EQ(wildcard_result[1], "text/*");
  1065. EXPECT_EQ(wildcard_result[2], "*/*");
  1066. }
  1067. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1068. // Common browser Accept header
  1069. std::vector<std::string> browser_result;
  1070. EXPECT_TRUE(
  1071. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1072. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1073. browser_result));
  1074. EXPECT_EQ(browser_result.size(), 6U);
  1075. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1076. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1077. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1078. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1079. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1080. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1081. // API client header
  1082. std::vector<std::string> api_result;
  1083. EXPECT_TRUE(detail::parse_accept_header(
  1084. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1085. api_result));
  1086. EXPECT_EQ(api_result.size(), 3U);
  1087. EXPECT_EQ(api_result[0], "application/json");
  1088. EXPECT_EQ(api_result[1], "application/xml");
  1089. EXPECT_EQ(api_result[2], "text/plain");
  1090. }
  1091. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1092. // Quality value with 3 decimal places
  1093. std::vector<std::string> decimal_result;
  1094. EXPECT_TRUE(detail::parse_accept_header(
  1095. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1096. EXPECT_EQ(decimal_result.size(), 2U);
  1097. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1098. EXPECT_EQ(decimal_result[1], "text/html");
  1099. // Zero quality (should still be included but with lowest priority)
  1100. std::vector<std::string> zero_q_result;
  1101. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1102. zero_q_result));
  1103. EXPECT_EQ(zero_q_result.size(), 2U);
  1104. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1105. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1106. // No spaces around commas
  1107. std::vector<std::string> no_space_result;
  1108. EXPECT_TRUE(detail::parse_accept_header(
  1109. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1110. no_space_result));
  1111. EXPECT_EQ(no_space_result.size(), 3U);
  1112. EXPECT_EQ(no_space_result[0], "text/html");
  1113. EXPECT_EQ(no_space_result[1], "application/json");
  1114. EXPECT_EQ(no_space_result[2], "text/plain");
  1115. }
  1116. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1117. // Quality values always use '.' as the decimal separator, so parsing must
  1118. // not depend on the process locale. An embedding application may have
  1119. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1120. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1121. std::string saved = cur ? cur : "C";
  1122. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1123. "fr_FR.UTF-8"};
  1124. bool switched = false;
  1125. for (const auto loc : comma_locales) {
  1126. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1127. std::localeconv()->decimal_point[0] == ',') {
  1128. switched = true;
  1129. break;
  1130. }
  1131. }
  1132. if (!switched) {
  1133. std::setlocale(LC_NUMERIC, saved.c_str());
  1134. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1135. }
  1136. // The higher-weighted type appears later in the list, so a correct parse
  1137. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1138. // sensitive parse reads both weights as 0 and leaves the original order.
  1139. std::vector<std::string> result;
  1140. EXPECT_TRUE(detail::parse_accept_header(
  1141. "application/json;q=0.1,text/html;q=0.9", result));
  1142. ASSERT_EQ(result.size(), 2U);
  1143. EXPECT_EQ(result[0], "text/html");
  1144. EXPECT_EQ(result[1], "application/json");
  1145. std::setlocale(LC_NUMERIC, saved.c_str());
  1146. }
  1147. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1148. std::vector<std::string> result;
  1149. // Invalid quality value (> 1.0)
  1150. EXPECT_FALSE(
  1151. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1152. // Invalid quality value (< 0.0)
  1153. EXPECT_FALSE(
  1154. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1155. // Invalid quality value (not a number)
  1156. EXPECT_FALSE(detail::parse_accept_header(
  1157. "text/html;q=invalid,application/json", result));
  1158. // A valid numeric prefix does not make the entire quality value valid.
  1159. EXPECT_FALSE(detail::parse_accept_header(
  1160. "text/html;q=0.5junk,application/json", result));
  1161. // Empty quality value
  1162. EXPECT_FALSE(
  1163. detail::parse_accept_header("text/html;q=,application/json", result));
  1164. // Invalid media type format (no slash and not wildcard)
  1165. EXPECT_FALSE(
  1166. detail::parse_accept_header("invalidtype,application/json", result));
  1167. // Valid cases should still work
  1168. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1169. EXPECT_EQ(result.size(), 1U);
  1170. EXPECT_EQ(result[0], "*/*");
  1171. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1172. EXPECT_EQ(result.size(), 1U);
  1173. EXPECT_EQ(result[0], "*");
  1174. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1175. EXPECT_EQ(result.size(), 1U);
  1176. EXPECT_EQ(result[0], "text/*");
  1177. }
  1178. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1179. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1180. // and must not be answered with 400 Bad Request.
  1181. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1182. struct {
  1183. const char *value;
  1184. std::vector<std::string> expected;
  1185. } cases[] = {
  1186. {",application/json", {"application/json"}},
  1187. {"text/html,", {"text/html"}},
  1188. {"text/html,,*/*", {"text/html", "*/*"}},
  1189. // An empty element may be spelled with whitespace in it
  1190. {"text/html, , application/json", {"text/html", "application/json"}},
  1191. // Nothing but empty elements is an empty list, which means the same
  1192. // thing as no Accept header at all
  1193. {",,,", {}},
  1194. // Quality values still apply across ignored empty elements
  1195. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1196. };
  1197. for (const auto &c : cases) {
  1198. std::vector<std::string> result;
  1199. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1200. << "value: " << c.value;
  1201. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1202. }
  1203. // An invalid entry is still rejected when empty elements surround it
  1204. std::vector<std::string> result;
  1205. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1206. }
  1207. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1208. // or ';' inside one does not end the list element or the parameter. Section
  1209. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1210. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1211. struct {
  1212. const char *value;
  1213. std::vector<std::string> expected;
  1214. } cases[] = {
  1215. {"text/html;profile=\"a,b\",application/json",
  1216. {"text/html", "application/json"}},
  1217. // A "q=" inside a quoted value is not the weight
  1218. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1219. {"text/html", "application/json"}},
  1220. // The weight after a quoted value still applies
  1221. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1222. {"application/json", "text/html"}},
  1223. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1224. {"application/json", "text/html"}},
  1225. {"text/html;profile=\"a\\\"b\",application/json",
  1226. {"text/html", "application/json"}},
  1227. // An escaped backslash does not escape the '"' after it
  1228. {"text/html;profile=\"a\\\\\",application/json",
  1229. {"text/html", "application/json"}},
  1230. };
  1231. for (const auto &c : cases) {
  1232. std::vector<std::string> result;
  1233. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1234. << "value: " << c.value;
  1235. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1236. }
  1237. }
  1238. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1239. Server svr;
  1240. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1241. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1242. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1243. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1244. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1245. res.set_content("ok", "text/plain");
  1246. });
  1247. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1248. EXPECT_TRUE(false);
  1249. res.set_content("bad request", "text/plain");
  1250. });
  1251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1252. auto se = detail::scope_exit([&] {
  1253. svr.stop();
  1254. listen_thread.join();
  1255. ASSERT_FALSE(svr.is_running());
  1256. });
  1257. svr.wait_until_ready();
  1258. Client cli("localhost", PORT);
  1259. {
  1260. auto res = cli.Get(
  1261. "/accept_ok",
  1262. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1264. EXPECT_EQ(StatusCode::OK_200, res->status);
  1265. }
  1266. {
  1267. auto res = cli.Get("/accept_bad_request",
  1268. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1271. }
  1272. }
  1273. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1274. Server svr;
  1275. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1276. res.set_content("ok", "text/plain");
  1277. });
  1278. std::atomic<int> start_count{0};
  1279. std::atomic<bool> running_when_called{false};
  1280. svr.set_start_handler([&]() {
  1281. running_when_called = svr.is_running();
  1282. start_count++;
  1283. });
  1284. auto port = svr.bind_to_any_port(HOST);
  1285. std::thread t([&]() { svr.listen_after_bind(); });
  1286. auto se = detail::scope_exit([&] {
  1287. svr.stop();
  1288. t.join();
  1289. ASSERT_FALSE(svr.is_running());
  1290. });
  1291. svr.wait_until_ready();
  1292. // A successful request proves the accept loop is running, which the start
  1293. // handler precedes; so by now the handler must have run exactly once.
  1294. Client cli(HOST, port);
  1295. cli.set_connection_timeout(std::chrono::seconds(5));
  1296. auto res = cli.Get("/");
  1297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1298. EXPECT_EQ(StatusCode::OK_200, res->status);
  1299. EXPECT_EQ(1, start_count.load());
  1300. EXPECT_TRUE(running_when_called.load());
  1301. }
  1302. TEST(DivideTest, DivideStringTests) {
  1303. auto divide = [](const std::string &str, char d) {
  1304. std::string lhs;
  1305. std::string rhs;
  1306. detail::divide(str, d,
  1307. [&](const char *lhs_data, std::size_t lhs_size,
  1308. const char *rhs_data, std::size_t rhs_size) {
  1309. lhs.assign(lhs_data, lhs_size);
  1310. rhs.assign(rhs_data, rhs_size);
  1311. });
  1312. return std::make_pair(std::move(lhs), std::move(rhs));
  1313. };
  1314. {
  1315. const auto res = divide("", '=');
  1316. EXPECT_EQ(res.first, "");
  1317. EXPECT_EQ(res.second, "");
  1318. }
  1319. {
  1320. const auto res = divide("=", '=');
  1321. EXPECT_EQ(res.first, "");
  1322. EXPECT_EQ(res.second, "");
  1323. }
  1324. {
  1325. const auto res = divide(" ", '=');
  1326. EXPECT_EQ(res.first, " ");
  1327. EXPECT_EQ(res.second, "");
  1328. }
  1329. {
  1330. const auto res = divide("a", '=');
  1331. EXPECT_EQ(res.first, "a");
  1332. EXPECT_EQ(res.second, "");
  1333. }
  1334. {
  1335. const auto res = divide("a=", '=');
  1336. EXPECT_EQ(res.first, "a");
  1337. EXPECT_EQ(res.second, "");
  1338. }
  1339. {
  1340. const auto res = divide("=b", '=');
  1341. EXPECT_EQ(res.first, "");
  1342. EXPECT_EQ(res.second, "b");
  1343. }
  1344. {
  1345. const auto res = divide("a=b", '=');
  1346. EXPECT_EQ(res.first, "a");
  1347. EXPECT_EQ(res.second, "b");
  1348. }
  1349. {
  1350. const auto res = divide("a=b=", '=');
  1351. EXPECT_EQ(res.first, "a");
  1352. EXPECT_EQ(res.second, "b=");
  1353. }
  1354. {
  1355. const auto res = divide("a=b=c", '=');
  1356. EXPECT_EQ(res.first, "a");
  1357. EXPECT_EQ(res.second, "b=c");
  1358. }
  1359. }
  1360. TEST(SplitTest, ParseQueryString) {
  1361. string s = "key1=val1&key2=val2&key3=val3";
  1362. Params dic;
  1363. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1364. [&](const char *b, const char *e) {
  1365. string key, val;
  1366. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1367. if (key.empty()) {
  1368. key.assign(b2, e2);
  1369. } else {
  1370. val.assign(b2, e2);
  1371. }
  1372. });
  1373. dic.emplace(key, val);
  1374. });
  1375. EXPECT_EQ("val1", dic.find("key1")->second);
  1376. EXPECT_EQ("val2", dic.find("key2")->second);
  1377. EXPECT_EQ("val3", dic.find("key3")->second);
  1378. }
  1379. TEST(SplitTest, ParseInvalidQueryTests) {
  1380. {
  1381. string s = " ";
  1382. Params dict;
  1383. detail::parse_query_text(s, dict);
  1384. EXPECT_TRUE(dict.empty());
  1385. }
  1386. {
  1387. string s = " = =";
  1388. Params dict;
  1389. detail::parse_query_text(s, dict);
  1390. EXPECT_TRUE(dict.empty());
  1391. }
  1392. }
  1393. TEST(ParseQueryTest, ParseQueryString) {
  1394. {
  1395. std::string s = "key1=val1&key2=val2&key3=val3";
  1396. Params dic;
  1397. detail::parse_query_text(s, dic);
  1398. EXPECT_EQ("val1", dic.find("key1")->second);
  1399. EXPECT_EQ("val2", dic.find("key2")->second);
  1400. EXPECT_EQ("val3", dic.find("key3")->second);
  1401. }
  1402. {
  1403. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1404. Params dic;
  1405. detail::parse_query_text(s, dic);
  1406. EXPECT_EQ("", dic.find("key1")->second);
  1407. EXPECT_EQ("val1", dic.find("key2")->second);
  1408. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1409. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1410. }
  1411. }
  1412. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1413. Params dic;
  1414. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1415. dic.emplace("key1", "val1");
  1416. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1417. dic.emplace("key2", "val2");
  1418. dic.emplace("key3", "val3");
  1419. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1420. }
  1421. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1422. Params params;
  1423. params.emplace("a", "1");
  1424. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1425. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1426. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1427. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1428. // Long enough to overflow the stack when matched with std::regex.
  1429. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1430. EXPECT_EQ("/p?" + long_query + "&a=1",
  1431. append_query_params("/p?" + long_query, params));
  1432. }
  1433. // Joins every entry of a Headers or Params into "key=value " so a whole
  1434. // traversal can be compared in one assertion. Both are instantiations of the
  1435. // same insertion-ordered container, so one helper serves both.
  1436. template <typename Map> static std::string entries_to_string(const Map &m) {
  1437. std::string s;
  1438. for (const auto &entry : m) {
  1439. s += entry.first + "=" + entry.second + " ";
  1440. }
  1441. return s;
  1442. }
  1443. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1444. // Params used to be a std::multimap, which sorted by name and handed the
  1445. // caller's query back alphabetised. A client signing its query string could
  1446. // not reproduce the order it asked for.
  1447. Params dic;
  1448. dic.emplace("zulu", "1");
  1449. dic.emplace("alpha", "2");
  1450. dic.emplace("mike", "3");
  1451. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1452. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1453. }
  1454. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1455. Params dic;
  1456. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1457. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1458. }
  1459. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1460. Request req;
  1461. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1462. req.params);
  1463. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1464. EXPECT_EQ("first", req.get_param_value("tag"));
  1465. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1466. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1467. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1468. EXPECT_EQ("", req.get_param_value("tag", 3));
  1469. }
  1470. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1471. // Params shares its container with Headers, which matches field names
  1472. // case-insensitively. Parameter names must not pick that up.
  1473. Params dic;
  1474. dic.emplace("Key", "upper");
  1475. dic.emplace("key", "lower");
  1476. EXPECT_EQ(2U, dic.size());
  1477. EXPECT_EQ(1U, dic.count("Key"));
  1478. EXPECT_EQ(1U, dic.count("key"));
  1479. EXPECT_EQ("upper", dic.find("Key")->second);
  1480. EXPECT_EQ("lower", dic.find("key")->second);
  1481. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1482. }
  1483. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1484. Server svr;
  1485. std::string order;
  1486. svr.Get("/order", [&](const Request &req, Response &res) {
  1487. order = entries_to_string(req.params);
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, port);
  1499. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1502. }
  1503. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1504. Server svr;
  1505. std::string field_order, file_order;
  1506. svr.Post("/order", [&](const Request &req, Response &res) {
  1507. for (const auto &field : req.form.fields) {
  1508. field_order += field.first + "=" + field.second.content + " ";
  1509. }
  1510. for (const auto &file : req.form.files) {
  1511. file_order += file.first + "=" + file.second.filename + " ";
  1512. }
  1513. res.set_content("ok", "text/plain");
  1514. });
  1515. auto port = svr.bind_to_any_port(HOST);
  1516. thread t = thread([&] { svr.listen_after_bind(); });
  1517. auto se = detail::scope_exit([&] {
  1518. svr.stop();
  1519. t.join();
  1520. ASSERT_FALSE(svr.is_running());
  1521. });
  1522. svr.wait_until_ready();
  1523. UploadFormDataItems items = {
  1524. {"zulu", "1", "", ""},
  1525. {"alpha", "2", "", ""},
  1526. {"mike", "3", "", ""},
  1527. {"zebra", "z", "z.txt", "text/plain"},
  1528. {"apple", "a", "a.txt", "text/plain"},
  1529. };
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/order", items);
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1534. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1535. }
  1536. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1537. Server svr;
  1538. std::vector<std::string> values;
  1539. std::string first, second, out_of_range, order;
  1540. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1541. values = req.form.get_fields("tag");
  1542. first = req.form.get_field("tag", 0);
  1543. second = req.form.get_field("tag", 1);
  1544. out_of_range = req.form.get_field("tag", 2);
  1545. for (const auto &field : req.form.fields) {
  1546. order += field.first + "=" + field.second.content + " ";
  1547. }
  1548. res.set_content("ok", "text/plain");
  1549. });
  1550. auto port = svr.bind_to_any_port(HOST);
  1551. thread t = thread([&] { svr.listen_after_bind(); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. t.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1559. // not adjacent in the container.
  1560. UploadFormDataItems items = {
  1561. {"tag", "first", "", ""},
  1562. {"other", "x", "", ""},
  1563. {"tag", "second", "", ""},
  1564. };
  1565. Client cli(HOST, port);
  1566. auto res = cli.Post("/repeated", items);
  1567. ASSERT_TRUE(res);
  1568. ASSERT_EQ(2U, values.size());
  1569. EXPECT_EQ("first", values[0]);
  1570. EXPECT_EQ("second", values[1]);
  1571. EXPECT_EQ("first", first);
  1572. EXPECT_EQ("second", second);
  1573. // std::multimap already kept entries sharing a name in insertion order, so
  1574. // everything above passes without this change too. The whole traversal is
  1575. // what tells the two apart: sorting by name would hoist "other" to the front
  1576. // and the two "tag" parts would end up adjacent.
  1577. EXPECT_EQ("tag=first other=x tag=second ", order);
  1578. // Advancing past the last entry of a name used to run off the container;
  1579. // the container's saturating increment makes it return the default instead.
  1580. EXPECT_EQ("", out_of_range);
  1581. }
  1582. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1583. Server svr;
  1584. std::string file_names;
  1585. svr.Post("/upload", [&](const Request &req, Response &res) {
  1586. for (const auto &file : req.form.files) {
  1587. file_names += file.first + "|" + file.second.filename + " ";
  1588. }
  1589. res.set_content("ok", "text/plain");
  1590. });
  1591. auto port = svr.bind_to_any_port(HOST);
  1592. thread t = thread([&] { svr.listen_after_bind(); });
  1593. auto se = detail::scope_exit([&] {
  1594. svr.stop();
  1595. t.join();
  1596. ASSERT_FALSE(svr.is_running());
  1597. });
  1598. svr.wait_until_ready();
  1599. // A trailing backslash would otherwise escape the closing quote.
  1600. UploadFormDataItems items = {
  1601. {"dir\\", "x", "a.txt", "text/plain"},
  1602. {"b", "y", "a\\\\b.txt", "text/plain"},
  1603. };
  1604. Client cli(HOST, port);
  1605. auto res = cli.Post("/upload", items);
  1606. ASSERT_TRUE(res);
  1607. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1608. }
  1609. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1610. // Server::read_content() keeps a FormFields::iterator alive across the
  1611. // content callbacks that fill the part it points at. The container is
  1612. // vector-backed, so a later emplace can reallocate and invalidate an older
  1613. // iterator; 64 parts grow the vector through seven reallocations, which
  1614. // checks that every part's content still lands in its own entry.
  1615. const size_t part_count = 64;
  1616. // One formula for both the parts sent and the values expected back, so the
  1617. // two cannot drift apart.
  1618. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1619. auto content_of = [](size_t i) {
  1620. return std::string(64, static_cast<char>('a' + (i % 26)));
  1621. };
  1622. Server svr;
  1623. std::vector<std::pair<std::string, std::string>> received;
  1624. svr.Post("/many", [&](const Request &req, Response &res) {
  1625. for (const auto &field : req.form.fields) {
  1626. received.emplace_back(field.first, field.second.content);
  1627. }
  1628. res.set_content("ok", "text/plain");
  1629. });
  1630. auto port = svr.bind_to_any_port(HOST);
  1631. thread t = thread([&] { svr.listen_after_bind(); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. t.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. UploadFormDataItems items;
  1639. for (size_t i = 0; i < part_count; i++) {
  1640. items.push_back({name_of(i), content_of(i), "", ""});
  1641. }
  1642. Client cli(HOST, port);
  1643. auto res = cli.Post("/many", items);
  1644. ASSERT_TRUE(res);
  1645. ASSERT_EQ(part_count, received.size());
  1646. for (size_t i = 0; i < part_count; i++) {
  1647. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1648. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1649. }
  1650. }
  1651. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1652. string content_type = "multipart/form-data; boundary=something";
  1653. string boundary;
  1654. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(boundary, "something");
  1657. }
  1658. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1659. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1660. string boundary;
  1661. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1662. EXPECT_TRUE(ret);
  1663. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1666. string content_type =
  1667. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1668. string boundary;
  1669. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1670. EXPECT_TRUE(ret);
  1671. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1672. }
  1673. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1674. string content_type =
  1675. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1676. string boundary;
  1677. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1678. EXPECT_TRUE(ret);
  1679. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1680. }
  1681. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1682. const string boundary(70, 'a');
  1683. string content_type = "multipart/form-data; boundary=" + boundary;
  1684. string parsed;
  1685. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1686. EXPECT_TRUE(ret);
  1687. EXPECT_EQ(parsed, boundary);
  1688. }
  1689. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1690. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1691. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1692. string parsed;
  1693. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1694. EXPECT_FALSE(ret);
  1695. }
  1696. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1697. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1698. // is 72 characters on the wire and still valid.
  1699. const string boundary(70, 'a');
  1700. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1701. string parsed;
  1702. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1703. EXPECT_EQ(parsed, boundary);
  1704. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1705. parsed.clear();
  1706. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1709. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1710. // The parameter parser must not treat that '=' as the key/value separator.
  1711. string content_type =
  1712. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1713. "charset=UTF-8";
  1714. string parsed;
  1715. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1716. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1717. }
  1718. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1719. // A ';' inside the quoted-string is part of the value, not a parameter
  1720. // separator, so it must not truncate the boundary.
  1721. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1722. string parsed;
  1723. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1724. EXPECT_EQ(parsed, "a;b");
  1725. }
  1726. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1727. string parsed;
  1728. EXPECT_TRUE(detail::parse_multipart_boundary(
  1729. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1730. EXPECT_EQ("a\\b", parsed);
  1731. EXPECT_TRUE(detail::parse_multipart_boundary(
  1732. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1733. EXPECT_EQ("a\"b", parsed);
  1734. }
  1735. TEST(ParseDispositionParamsTest, QuotedValues) {
  1736. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1737. // ';' and '=' are ordinary characters inside one.
  1738. struct {
  1739. const char *value;
  1740. std::vector<std::pair<const char *, const char *>> expected;
  1741. } cases[] = {
  1742. {"name=\"file1\"; filename=\"a.txt\"",
  1743. {{"name", "file1"}, {"filename", "a.txt"}}},
  1744. // Whitespace around '=' and ';' is still trimmed
  1745. {"name=\"file2\" ;filename = \"a.html\"",
  1746. {{"name", "file2"}, {"filename", "a.html"}}},
  1747. // '=' inside the value used to leave only the text after the last one
  1748. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1749. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1750. {"name=\"x=y\"", {{"name", "x=y"}}},
  1751. // ';' inside the value used to truncate the pair and leave a bogus one
  1752. {"name=\"file3\"; filename=\"a;b.txt\"",
  1753. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1754. // An unquoted value keeps working, and so does filename*
  1755. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1756. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1757. // A parameter with no key is dropped rather than turned into one whose
  1758. // key is the value
  1759. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1760. // An escaped quote does not end the value
  1761. {"name=\"a\\\"; filename=evil.php\"",
  1762. {{"name", "a\"; filename=evil.php"}}},
  1763. // Other backslashes, as in a Windows path, are kept
  1764. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1765. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1766. };
  1767. for (const auto &c : cases) {
  1768. Params params;
  1769. detail::parse_disposition_params(c.value, params);
  1770. for (const auto &kv : c.expected) {
  1771. auto it = params.find(kv.first);
  1772. ASSERT_NE(it, params.end())
  1773. << "value: " << c.value << ", key: " << kv.first;
  1774. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1775. }
  1776. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1777. }
  1778. }
  1779. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1780. Server svr;
  1781. std::string filename;
  1782. std::string content;
  1783. svr.Post("/upload", [&](const Request &req, Response &) {
  1784. const auto &file = req.form.get_file("file");
  1785. filename = file.filename;
  1786. content = file.content;
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. std::string body = "--B\r\n"
  1796. "Content-Disposition: form-data; name=\"file\"; "
  1797. "filename=\"a.txt\"\r\n"
  1798. "Content-Type: text/plain\r\n"
  1799. "\r\n"
  1800. "hello\r\n"
  1801. "--B--\r\n";
  1802. Client cli(HOST, PORT);
  1803. auto res = cli.Post(
  1804. "/upload",
  1805. [&](size_t offset, DataSink &sink) {
  1806. if (offset < body.size()) {
  1807. sink.write(&body[offset], 1);
  1808. } else {
  1809. sink.done();
  1810. }
  1811. return true;
  1812. },
  1813. "multipart/form-data; boundary=B");
  1814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1815. EXPECT_EQ(StatusCode::OK_200, res->status);
  1816. EXPECT_EQ("a.txt", filename);
  1817. EXPECT_EQ("hello", content);
  1818. }
  1819. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1820. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1821. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1822. Server svr;
  1823. std::string field_value, file_name, file_filename;
  1824. bool has_field = false, has_file = false;
  1825. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1826. has_field = req.form.has_field("x=y");
  1827. field_value = req.form.get_field("x=y");
  1828. has_file = req.form.has_file("file1");
  1829. const auto &file = req.form.get_file("file1");
  1830. file_name = file.name;
  1831. file_filename = file.filename;
  1832. res.set_content("ok", "text/plain");
  1833. });
  1834. auto port = svr.bind_to_any_port(HOST);
  1835. thread t = thread([&] { svr.listen_after_bind(); });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. t.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. UploadFormDataItems items = {
  1843. {"x=y", "field-value", "", ""},
  1844. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1845. };
  1846. Client cli(HOST, port);
  1847. auto res = cli.Post("/quoted", items);
  1848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1849. ASSERT_EQ(StatusCode::OK_200, res->status);
  1850. EXPECT_TRUE(has_field);
  1851. EXPECT_EQ("field-value", field_value);
  1852. EXPECT_TRUE(has_file);
  1853. EXPECT_EQ("file1", file_name);
  1854. EXPECT_EQ("a;b=report.pdf", file_filename);
  1855. }
  1856. TEST(GetHeaderValueTest, DefaultValue) {
  1857. Headers headers = {{"Dummy", "Dummy"}};
  1858. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1859. EXPECT_STREQ("text/plain", val);
  1860. }
  1861. TEST(GetHeaderValueTest, DefaultValueInt) {
  1862. Headers headers = {{"Dummy", "Dummy"}};
  1863. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1864. EXPECT_EQ(100ull, val);
  1865. }
  1866. TEST(GetHeaderValueTest, RegularValue) {
  1867. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1868. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1869. EXPECT_STREQ("text/html", val);
  1870. }
  1871. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1872. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1873. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1874. EXPECT_STREQ("text/html", val);
  1875. }
  1876. TEST(GetHeaderValueTest, SetContent) {
  1877. Response res;
  1878. res.set_content("html", "text/html");
  1879. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1880. res.set_content("text", "text/plain");
  1881. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1882. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1883. }
  1884. TEST(GetHeaderValueTest, RegularValueInt) {
  1885. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1887. EXPECT_EQ(100ull, val);
  1888. }
  1889. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1890. Headers headers = {{"Content-Length", "x"}};
  1891. auto is_invalid_value = false;
  1892. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1893. is_invalid_value);
  1894. EXPECT_EQ(0ull, val);
  1895. EXPECT_TRUE(is_invalid_value);
  1896. }
  1897. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1898. // An all-digit value that overflows size_t must be reported as invalid, not
  1899. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1900. // a large length to a small one on 32-bit builds, leaving the framing length
  1901. // wrong while is_invalid_value stayed false.
  1902. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1903. auto is_invalid_value = false;
  1904. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1905. is_invalid_value);
  1906. EXPECT_TRUE(is_invalid_value);
  1907. // A well-formed length is unaffected.
  1908. Headers ok = {{"Content-Length", "1234"}};
  1909. is_invalid_value = false;
  1910. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1911. is_invalid_value);
  1912. EXPECT_EQ(1234ull, val);
  1913. EXPECT_FALSE(is_invalid_value);
  1914. }
  1915. TEST(GetHeaderValueTest, Range) {
  1916. {
  1917. Headers headers = {make_range_header({{1, -1}})};
  1918. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1919. EXPECT_STREQ("bytes=1-", val);
  1920. }
  1921. {
  1922. Headers headers = {make_range_header({{-1, 1}})};
  1923. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1924. EXPECT_STREQ("bytes=-1", val);
  1925. }
  1926. {
  1927. Headers headers = {make_range_header({{1, 10}})};
  1928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1929. EXPECT_STREQ("bytes=1-10", val);
  1930. }
  1931. {
  1932. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1934. EXPECT_STREQ("bytes=1-10, 100-", val);
  1935. }
  1936. {
  1937. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1938. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1939. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1940. }
  1941. {
  1942. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1943. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1944. EXPECT_STREQ("bytes=0-0, -1", val);
  1945. }
  1946. }
  1947. TEST(BearerTokenAuthTest, SchemeValidation) {
  1948. // A value shorter than "Bearer " must not throw from the fixed-length
  1949. // substr, and a non-Bearer scheme must not be reported as a token.
  1950. struct {
  1951. const char *value;
  1952. const char *expected;
  1953. } cases[] = {
  1954. {"x", ""},
  1955. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1956. {"Bearer abc123", "abc123"},
  1957. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1958. };
  1959. for (const auto &c : cases) {
  1960. Request req;
  1961. req.set_header("Authorization", c.value);
  1962. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1963. }
  1964. }
  1965. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1966. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1967. // to depend on the standard library (libstdc++ handed back duplicates in
  1968. // reverse insertion order, libc++ in insertion order).
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "gzip");
  1971. req.set_header("Accept-Encoding", "deflate");
  1972. req.set_header("Accept-Encoding", "br");
  1973. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1974. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1975. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1976. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1977. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1978. }
  1979. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1980. Request req;
  1981. req.set_header("X-Test", "only");
  1982. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1983. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1984. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1985. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1986. }
  1987. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1988. Request req;
  1989. req.set_header("X-First", "1");
  1990. req.set_header("X-Test", "2");
  1991. req.params.emplace("first", "1");
  1992. req.params.emplace("test", "2");
  1993. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1994. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1995. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1996. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1997. // The second one is negative when read as a signed value
  1998. const auto max_id = (std::numeric_limits<size_t>::max)();
  1999. for (auto id : {max_id / 2, max_id}) {
  2000. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2001. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2002. EXPECT_EQ("", req.get_param_value("test", id));
  2003. EXPECT_EQ("", req.form.get_field("test", id));
  2004. EXPECT_EQ("", req.form.get_file("test", id).content);
  2005. }
  2006. }
  2007. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2008. Headers headers;
  2009. headers.emplace("Host", "example.com");
  2010. headers.emplace("Accept-Encoding", "gzip");
  2011. headers.emplace("User-Agent", "test");
  2012. headers.emplace("Accept-Encoding", "deflate");
  2013. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2014. "Accept-Encoding=deflate ",
  2015. entries_to_string(headers));
  2016. }
  2017. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2018. Headers headers = {{"Content-Type", "text/html"},
  2019. {"CONTENT-TYPE", "text/xml"}};
  2020. EXPECT_EQ(2U, headers.count("content-type"));
  2021. auto it = headers.find("content-type");
  2022. ASSERT_TRUE(it != headers.end());
  2023. EXPECT_EQ("text/html", it->second);
  2024. }
  2025. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2026. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2027. // drop only those fields and leave everything positioned between them.
  2028. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2029. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2030. auto rng = headers.equal_range("a");
  2031. headers.erase(rng.first, rng.second);
  2032. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2033. }
  2034. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2035. Headers headers = {
  2036. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2037. EXPECT_EQ(3U, headers.erase("A"));
  2038. EXPECT_EQ(0U, headers.count("A"));
  2039. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2040. }
  2041. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2042. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2043. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2044. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2045. }
  2046. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2047. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2048. headers.emplace_front("Host", "example.com");
  2049. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2050. entries_to_string(headers));
  2051. }
  2052. TEST(ParseHeaderValueTest, Range) {
  2053. {
  2054. Ranges ranges;
  2055. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2056. EXPECT_TRUE(ret);
  2057. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2058. }
  2059. {
  2060. Ranges ranges;
  2061. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2062. EXPECT_TRUE(ret);
  2063. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2064. }
  2065. {
  2066. Ranges ranges;
  2067. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2068. EXPECT_TRUE(ret);
  2069. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2070. }
  2071. {
  2072. Ranges ranges;
  2073. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2074. EXPECT_FALSE(ret);
  2075. }
  2076. {
  2077. Ranges ranges;
  2078. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2079. EXPECT_TRUE(ret);
  2080. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2081. }
  2082. {
  2083. Ranges ranges;
  2084. auto ret =
  2085. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2086. EXPECT_TRUE(ret);
  2087. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2088. }
  2089. {
  2090. Ranges ranges;
  2091. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2092. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2093. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2094. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2095. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2096. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2097. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2098. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2099. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2100. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2101. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2102. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2103. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2104. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2105. EXPECT_FALSE(
  2106. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2107. EXPECT_TRUE(ranges.empty());
  2108. }
  2109. {
  2110. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2111. // remainder of the representation, so it stays accepted.
  2112. Ranges ranges;
  2113. auto ret =
  2114. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2115. EXPECT_TRUE(ret);
  2116. ASSERT_EQ(1u, ranges.size());
  2117. EXPECT_EQ(0, ranges[0].first);
  2118. EXPECT_EQ(-1, ranges[0].second);
  2119. }
  2120. // RFC 9110 14.1: range unit names are case-insensitive.
  2121. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2122. Ranges ranges;
  2123. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2124. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2125. }
  2126. }
  2127. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2128. Request req;
  2129. req.set_header("Accept-Encoding", "gzip");
  2130. Response res;
  2131. res.set_header("Content-Type", "text/plain");
  2132. auto ret = detail::encoding_type(req, res);
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #else
  2136. EXPECT_TRUE(ret == detail::EncodingType::None);
  2137. #endif
  2138. }
  2139. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2140. Request req;
  2141. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2142. Response res;
  2143. res.set_header("Content-Type", "text/plain");
  2144. auto ret = detail::encoding_type(req, res);
  2145. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2146. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2147. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2149. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2151. #else
  2152. EXPECT_TRUE(ret == detail::EncodingType::None);
  2153. #endif
  2154. }
  2155. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2156. Request req;
  2157. req.set_header("Accept-Encoding",
  2158. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2159. Response res;
  2160. res.set_header("Content-Type", "text/plain");
  2161. auto ret = detail::encoding_type(req, res);
  2162. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2163. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2164. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2165. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2166. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2168. #else
  2169. EXPECT_TRUE(ret == detail::EncodingType::None);
  2170. #endif
  2171. }
  2172. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2173. // All supported encodings rejected with q=0 should return None
  2174. Request req;
  2175. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2176. Response res;
  2177. res.set_header("Content-Type", "text/plain");
  2178. auto ret = detail::encoding_type(req, res);
  2179. EXPECT_TRUE(ret == detail::EncodingType::None);
  2180. }
  2181. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2182. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2183. Request req;
  2184. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2185. Response res;
  2186. res.set_header("Content-Type", "text/plain");
  2187. auto ret = detail::encoding_type(req, res);
  2188. EXPECT_TRUE(ret == detail::EncodingType::None);
  2189. }
  2190. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2191. Request req;
  2192. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2193. Response res;
  2194. res.set_header("Content-Type", "text/plain");
  2195. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2196. }
  2197. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2198. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2199. Request req;
  2200. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2201. Response res;
  2202. res.set_header("Content-Type", "text/plain");
  2203. auto ret = detail::encoding_type(req, res);
  2204. EXPECT_TRUE(ret == detail::EncodingType::None);
  2205. }
  2206. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2207. // RFC 7231: Accept-Encoding values are case-insensitive
  2208. Request req;
  2209. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2210. Response res;
  2211. res.set_header("Content-Type", "text/plain");
  2212. auto ret = detail::encoding_type(req, res);
  2213. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2214. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2215. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2216. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2217. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2218. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2219. #else
  2220. EXPECT_TRUE(ret == detail::EncodingType::None);
  2221. #endif
  2222. }
  2223. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2224. // q value should determine priority, not hardcoded order
  2225. Request req;
  2226. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2227. Response res;
  2228. res.set_header("Content-Type", "text/plain");
  2229. auto ret = detail::encoding_type(req, res);
  2230. // gzip has highest q=1.0, so it should be selected even though
  2231. // br and zstd are also supported
  2232. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2233. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2234. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2235. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2236. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2237. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2238. #else
  2239. EXPECT_TRUE(ret == detail::EncodingType::None);
  2240. #endif
  2241. }
  2242. TEST(BufferStreamTest, read) {
  2243. detail::BufferStream strm1;
  2244. Stream &strm = strm1;
  2245. EXPECT_EQ(5, strm.write("hello"));
  2246. char buf[512];
  2247. EXPECT_EQ(2, strm.read(buf, 2));
  2248. EXPECT_EQ('h', buf[0]);
  2249. EXPECT_EQ('e', buf[1]);
  2250. EXPECT_EQ(2, strm.read(buf, 2));
  2251. EXPECT_EQ('l', buf[0]);
  2252. EXPECT_EQ('l', buf[1]);
  2253. EXPECT_EQ(1, strm.read(buf, 1));
  2254. EXPECT_EQ('o', buf[0]);
  2255. EXPECT_EQ(0, strm.read(buf, 1));
  2256. }
  2257. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2258. auto host = "www.httpwatch.com";
  2259. auto ip = hosted_at(host);
  2260. EXPECT_EQ("23.96.13.243", ip);
  2261. std::vector<std::string> addrs;
  2262. hosted_at(host, addrs);
  2263. EXPECT_EQ(1u, addrs.size());
  2264. }
  2265. #if 0 // It depends on each test environment...
  2266. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2267. auto host = "www.youtube.com";
  2268. std::vector<std::string> addrs;
  2269. hosted_at(host, addrs);
  2270. EXPECT_EQ(20u, addrs.size());
  2271. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2272. EXPECT_TRUE(it != addrs.end());
  2273. }
  2274. #endif
  2275. class ChunkedEncodingTest : public ::testing::Test {
  2276. protected:
  2277. ChunkedEncodingTest()
  2278. : cli_(HOST, PORT)
  2279. #ifdef CPPHTTPLIB_SSL_ENABLED
  2280. ,
  2281. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2282. #endif
  2283. {
  2284. cli_.set_connection_timeout(2);
  2285. #ifdef CPPHTTPLIB_SSL_ENABLED
  2286. cli_.enable_server_certificate_verification(false);
  2287. #endif
  2288. }
  2289. virtual void SetUp() {
  2290. read_file("./image.jpg", image_data_);
  2291. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2292. res.set_content("Hello World!", "text/plain");
  2293. });
  2294. svr_.Get(
  2295. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2296. res.set_chunked_content_provider(
  2297. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2298. size_t remaining = image_data_.size() - offset;
  2299. if (remaining == 0) {
  2300. sink.done();
  2301. } else {
  2302. constexpr size_t CHUNK_SIZE = 1024;
  2303. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2304. sink.write(&image_data_[offset], send_size);
  2305. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2306. }
  2307. return true;
  2308. });
  2309. });
  2310. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2311. svr_.wait_until_ready();
  2312. }
  2313. virtual void TearDown() {
  2314. svr_.stop();
  2315. if (!request_threads_.empty()) {
  2316. std::this_thread::sleep_for(std::chrono::seconds(1));
  2317. for (auto &t : request_threads_) {
  2318. t.join();
  2319. }
  2320. }
  2321. t_.join();
  2322. }
  2323. #ifdef CPPHTTPLIB_SSL_ENABLED
  2324. SSLClient cli_;
  2325. SSLServer svr_;
  2326. #else
  2327. Client cli_;
  2328. Server svr_;
  2329. #endif
  2330. thread t_;
  2331. std::vector<thread> request_threads_;
  2332. std::string image_data_;
  2333. };
  2334. TEST_F(ChunkedEncodingTest, NormalGet) {
  2335. auto res = cli_.Get("/chunked");
  2336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2337. std::string out;
  2338. read_file("./image.jpg", out);
  2339. EXPECT_EQ(StatusCode::OK_200, res->status);
  2340. EXPECT_EQ(out, res->body);
  2341. }
  2342. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2343. std::string body;
  2344. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2345. body.append(data, data_length);
  2346. return true;
  2347. });
  2348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2349. std::string out;
  2350. read_file("./image.jpg", out);
  2351. EXPECT_EQ(StatusCode::OK_200, res->status);
  2352. EXPECT_EQ(out, body);
  2353. }
  2354. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2355. std::string body;
  2356. auto res = cli_.Get(
  2357. "/chunked",
  2358. [&](const Response &response) {
  2359. EXPECT_EQ(StatusCode::OK_200, response.status);
  2360. return true;
  2361. },
  2362. [&](const char *data, size_t data_length) {
  2363. body.append(data, data_length);
  2364. return true;
  2365. });
  2366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2367. std::string out;
  2368. read_file("./image.jpg", out);
  2369. EXPECT_EQ(StatusCode::OK_200, res->status);
  2370. EXPECT_EQ(out, body);
  2371. }
  2372. TEST(RangeTest, FromHTTPBin_Online) {
  2373. auto host = "httpbingo.org";
  2374. auto path = std::string{"/range/32"};
  2375. #ifdef CPPHTTPLIB_SSL_ENABLED
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. #else
  2379. auto port = 80;
  2380. Client cli(host, port);
  2381. #endif
  2382. cli.set_connection_timeout(5);
  2383. {
  2384. auto res = cli.Get(path);
  2385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2386. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2387. EXPECT_EQ(StatusCode::OK_200, res->status);
  2388. }
  2389. {
  2390. Headers headers = {make_range_header({{1, -1}})};
  2391. auto res = cli.Get(path, headers);
  2392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2393. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2395. }
  2396. {
  2397. Headers headers = {make_range_header({{1, 10}})};
  2398. auto res = cli.Get(path, headers);
  2399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2400. EXPECT_EQ("bcdefghijk", res->body);
  2401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2402. }
  2403. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2404. // entire resource, while the original httpbin returned 200. Both are
  2405. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2406. {
  2407. Headers headers = {make_range_header({{0, 31}})};
  2408. auto res = cli.Get(path, headers);
  2409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2410. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2411. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2412. res->status == StatusCode::PartialContent_206);
  2413. }
  2414. {
  2415. Headers headers = {make_range_header({{0, -1}})};
  2416. auto res = cli.Get(path, headers);
  2417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2418. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2419. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2420. res->status == StatusCode::PartialContent_206);
  2421. }
  2422. // go-httpbin returns 206 with clamped range for over-range requests,
  2423. // while the original httpbin returned 416. Both behaviors are observed
  2424. // in real servers, so we only verify the request succeeds.
  2425. {
  2426. Headers headers = {make_range_header({{0, 32}})};
  2427. auto res = cli.Get(path, headers);
  2428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2429. }
  2430. }
  2431. TEST(RangeTest, IgnoredForPost) {
  2432. Server svr;
  2433. svr.Post("/", [](const Request &, Response &res) {
  2434. res.set_content("abcdefg", "text/plain");
  2435. });
  2436. auto port = svr.bind_to_any_port(HOST);
  2437. ASSERT_GT(port, 0);
  2438. thread t = thread([&] { svr.listen_after_bind(); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. t.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, port);
  2446. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2447. auto res = cli.Post("/", Headers{{"Range", range}});
  2448. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2449. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2450. EXPECT_EQ("abcdefg", res->body) << range;
  2451. }
  2452. }
  2453. TEST(RangeTest, IgnoredForUnknownUnit) {
  2454. Server svr;
  2455. svr.Get("/", [](const Request &, Response &res) {
  2456. res.set_content("abcdefg", "text/plain");
  2457. });
  2458. auto port = svr.bind_to_any_port(HOST);
  2459. ASSERT_GT(port, 0);
  2460. thread t = thread([&] { svr.listen_after_bind(); });
  2461. auto se = detail::scope_exit([&] {
  2462. svr.stop();
  2463. t.join();
  2464. ASSERT_FALSE(svr.is_running());
  2465. });
  2466. svr.wait_until_ready();
  2467. Client cli(HOST, port);
  2468. for (auto range : {"items=1-2", "none=x"}) {
  2469. auto res = cli.Get("/", Headers{{"Range", range}});
  2470. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2471. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2472. EXPECT_EQ("abcdefg", res->body) << range;
  2473. }
  2474. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2475. ASSERT_TRUE(res) << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2477. }
  2478. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2479. auto host = "unresolvableaddress.local";
  2480. auto path = std::string{"/"};
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. auto port = 443;
  2483. SSLClient cli(host, port);
  2484. #else
  2485. auto port = 80;
  2486. Client cli(host, port);
  2487. #endif
  2488. cli.set_connection_timeout(1);
  2489. {
  2490. auto res = cli.Get(path);
  2491. ASSERT_FALSE(res);
  2492. }
  2493. std::this_thread::sleep_for(std::chrono::seconds(8));
  2494. }
  2495. #if defined(__linux__) && defined(__GLIBC__) && \
  2496. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2497. // Forward declaration: in split builds split.py strips `inline` and moves the
  2498. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2499. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2500. // against the symbol in both header-only and split builds.
  2501. namespace httplib {
  2502. namespace detail {
  2503. int getaddrinfo_with_timeout(const char *node, const char *service,
  2504. const struct addrinfo *hints,
  2505. struct addrinfo **res, time_t timeout_sec);
  2506. } // namespace detail
  2507. } // namespace httplib
  2508. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2509. //
  2510. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2511. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2512. // gai_suspend() call hits the connection timeout the function calls
  2513. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2514. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2515. // still alive and still references the now-destroyed stack frame.
  2516. //
  2517. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2518. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2519. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2520. // and runs them in a container.
  2521. namespace {
  2522. bool should_run_issue_2431_tests() {
  2523. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2524. return v && *v && std::string(v) != "0";
  2525. }
  2526. std::string unique_unresolvable_host(int n) {
  2527. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2528. // glibc still asks the configured nameserver — which is exactly the path
  2529. // we want to exercise. A unique label per call avoids the resolver cache.
  2530. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2531. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2532. std::to_string(n) + ".invalid";
  2533. }
  2534. } // namespace
  2535. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2536. if (!should_run_issue_2431_tests()) {
  2537. GTEST_SKIP()
  2538. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2539. }
  2540. for (int i = 0; i < 8; ++i) {
  2541. struct addrinfo hints;
  2542. memset(&hints, 0, sizeof(hints));
  2543. hints.ai_family = AF_UNSPEC;
  2544. hints.ai_socktype = SOCK_STREAM;
  2545. auto host = unique_unresolvable_host(i);
  2546. struct addrinfo *result = nullptr;
  2547. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2548. &result, /*timeout_sec=*/1);
  2549. if (rc == 0 && result) { freeaddrinfo(result); }
  2550. }
  2551. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2552. // stack region they still believe holds their gaicb.
  2553. std::this_thread::sleep_for(std::chrono::seconds(3));
  2554. }
  2555. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2556. if (!should_run_issue_2431_tests()) {
  2557. GTEST_SKIP()
  2558. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2559. }
  2560. std::atomic<bool> stop{false};
  2561. std::vector<std::thread> threads;
  2562. for (int t = 0; t < 8; ++t) {
  2563. threads.emplace_back([t, &stop] {
  2564. int i = 0;
  2565. while (!stop.load(std::memory_order_relaxed)) {
  2566. struct addrinfo hints;
  2567. memset(&hints, 0, sizeof(hints));
  2568. hints.ai_family = AF_UNSPEC;
  2569. hints.ai_socktype = SOCK_STREAM;
  2570. auto host = unique_unresolvable_host(t * 100000 + i++);
  2571. struct addrinfo *result = nullptr;
  2572. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2573. &result, /*timeout_sec=*/1);
  2574. if (rc == 0 && result) { freeaddrinfo(result); }
  2575. }
  2576. });
  2577. }
  2578. std::this_thread::sleep_for(std::chrono::seconds(8));
  2579. stop.store(true, std::memory_order_relaxed);
  2580. for (auto &th : threads) {
  2581. th.join();
  2582. }
  2583. std::this_thread::sleep_for(std::chrono::seconds(3));
  2584. }
  2585. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2586. if (!should_run_issue_2431_tests()) {
  2587. GTEST_SKIP()
  2588. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2589. }
  2590. std::atomic<bool> stop{false};
  2591. std::vector<std::thread> threads;
  2592. for (int t = 0; t < 8; ++t) {
  2593. threads.emplace_back([t, &stop] {
  2594. int i = 0;
  2595. while (!stop.load(std::memory_order_relaxed)) {
  2596. auto host = unique_unresolvable_host(t * 100000 + i++);
  2597. Client cli(host, 80);
  2598. cli.set_connection_timeout(1, 0);
  2599. cli.set_read_timeout(1, 0);
  2600. cli.set_write_timeout(1, 0);
  2601. (void)cli.Get("/");
  2602. }
  2603. });
  2604. }
  2605. std::this_thread::sleep_for(std::chrono::seconds(8));
  2606. stop.store(true, std::memory_order_relaxed);
  2607. for (auto &th : threads) {
  2608. th.join();
  2609. }
  2610. std::this_thread::sleep_for(std::chrono::seconds(3));
  2611. }
  2612. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2613. TEST(ConnectionErrorTest, InvalidHost) {
  2614. auto host = "-abcde.com";
  2615. #ifdef CPPHTTPLIB_SSL_ENABLED
  2616. auto port = 443;
  2617. SSLClient cli(host, port);
  2618. #else
  2619. auto port = 80;
  2620. Client cli(host, port);
  2621. #endif
  2622. cli.set_connection_timeout(std::chrono::seconds(2));
  2623. auto res = cli.Get("/");
  2624. ASSERT_TRUE(!res);
  2625. EXPECT_EQ(Error::Connection, res.error());
  2626. }
  2627. TEST(ConnectionErrorTest, InvalidHost2) {
  2628. auto host = "httpcan.org/";
  2629. #ifdef CPPHTTPLIB_SSL_ENABLED
  2630. SSLClient cli(host);
  2631. #else
  2632. Client cli(host);
  2633. #endif
  2634. cli.set_connection_timeout(std::chrono::seconds(2));
  2635. auto res = cli.Get("/");
  2636. ASSERT_TRUE(!res);
  2637. EXPECT_EQ(Error::Connection, res.error());
  2638. }
  2639. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2640. auto host = "httpcan.org/";
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. SSLClient cli(host);
  2643. #else
  2644. Client cli(host);
  2645. #endif
  2646. cli.set_connection_timeout(std::chrono::seconds(2));
  2647. auto res = cli.Get("/");
  2648. ASSERT_TRUE(!res);
  2649. stringstream s;
  2650. s << "error code: " << res.error();
  2651. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2652. }
  2653. TEST(ConnectionErrorTest, InvalidPort) {
  2654. auto host = "localhost";
  2655. auto port = 44380;
  2656. #ifdef CPPHTTPLIB_SSL_ENABLED
  2657. SSLClient cli(host, port);
  2658. #else
  2659. Client cli(host, port);
  2660. #endif
  2661. cli.set_connection_timeout(std::chrono::seconds(2));
  2662. auto res = cli.Get("/");
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_TRUE(Error::Connection == res.error() ||
  2665. Error::ConnectionTimeout == res.error());
  2666. }
  2667. TEST(ConnectionErrorTest, Timeout_Online) {
  2668. auto host = "google.com";
  2669. #ifdef CPPHTTPLIB_SSL_ENABLED
  2670. auto port = 44380;
  2671. SSLClient cli(host, port);
  2672. #else
  2673. auto port = 8080;
  2674. Client cli(host, port);
  2675. #endif
  2676. cli.set_connection_timeout(std::chrono::seconds(2));
  2677. // only probe one address type so that the error reason
  2678. // correlates to the timed-out IPv4, not the unsupported
  2679. // IPv6 connection attempt
  2680. cli.set_address_family(AF_INET);
  2681. auto res = cli.Get("/");
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2684. }
  2685. TEST(CancelTest, NoCancel_Online) {
  2686. auto host = "httpbingo.org";
  2687. auto path = std::string{"/range/32"};
  2688. #ifdef CPPHTTPLIB_SSL_ENABLED
  2689. auto port = 443;
  2690. SSLClient cli(host, port);
  2691. #else
  2692. auto port = 80;
  2693. Client cli(host, port);
  2694. #endif
  2695. cli.set_connection_timeout(std::chrono::seconds(5));
  2696. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2698. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2699. EXPECT_EQ(StatusCode::OK_200, res->status);
  2700. }
  2701. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2702. // Use /bytes with a large payload so that the DownloadProgress callback
  2703. // (which only fires for Content-Length responses) is invoked before the
  2704. // entire body is received, giving cancellation a chance to fire.
  2705. auto host = "httpbingo.org";
  2706. auto path = std::string{"/bytes/524288"};
  2707. #ifdef CPPHTTPLIB_SSL_ENABLED
  2708. auto port = 443;
  2709. SSLClient cli(host, port);
  2710. #else
  2711. auto port = 80;
  2712. Client cli(host, port);
  2713. #endif
  2714. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2715. cli.set_connection_timeout(std::chrono::seconds(5));
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_EQ(Error::Canceled, res.error());
  2718. }
  2719. TEST(CancelTest, WithCancelLargePayload_Online) {
  2720. auto host = "httpbingo.org";
  2721. auto path = std::string{"/bytes/524288"};
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. auto port = 443;
  2724. SSLClient cli(host, port);
  2725. #else
  2726. auto port = 80;
  2727. Client cli(host, port);
  2728. #endif
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. uint32_t count = 0;
  2731. auto res =
  2732. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelPost) {
  2737. Server svr;
  2738. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2758. Server svr;
  2759. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadPost) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. TEST(CancelTest, NoCancelPut) {
  2800. Server svr;
  2801. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("Hello World!", "text/plain");
  2803. });
  2804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2805. auto se = detail::scope_exit([&] {
  2806. svr.stop();
  2807. thread.join();
  2808. ASSERT_FALSE(svr.is_running());
  2809. });
  2810. svr.wait_until_ready();
  2811. Client cli(HOST, PORT);
  2812. cli.set_connection_timeout(std::chrono::seconds(5));
  2813. auto res =
  2814. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2815. "application/json", [](uint64_t, uint64_t) { return true; });
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ("Hello World!", res->body);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. }
  2820. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2821. Server svr;
  2822. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2823. res.set_content("Hello World!", "text/plain");
  2824. });
  2825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2826. auto se = detail::scope_exit([&] {
  2827. svr.stop();
  2828. thread.join();
  2829. ASSERT_FALSE(svr.is_running());
  2830. });
  2831. svr.wait_until_ready();
  2832. Client cli(HOST, PORT);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. TEST(CancelTest, WithCancelLargePayloadPut) {
  2841. Server svr;
  2842. svr.set_payload_max_length(200 * 1024 * 1024);
  2843. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2844. res.set_content(LARGE_DATA, "text/plain");
  2845. });
  2846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(HOST, PORT);
  2854. cli.set_payload_max_length(200 * 1024 * 1024);
  2855. cli.set_connection_timeout(std::chrono::seconds(5));
  2856. auto res =
  2857. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2858. "application/json", [](uint64_t, uint64_t) { return false; });
  2859. ASSERT_TRUE(!res);
  2860. EXPECT_EQ(Error::Canceled, res.error());
  2861. }
  2862. TEST(CancelTest, NoCancelPatch) {
  2863. Server svr;
  2864. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2865. res.set_content("Hello World!", "text/plain");
  2866. });
  2867. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2868. auto se = detail::scope_exit([&] {
  2869. svr.stop();
  2870. thread.join();
  2871. ASSERT_FALSE(svr.is_running());
  2872. });
  2873. svr.wait_until_ready();
  2874. Client cli(HOST, PORT);
  2875. cli.set_connection_timeout(std::chrono::seconds(5));
  2876. auto res =
  2877. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2878. "application/json", [](uint64_t, uint64_t) { return true; });
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ("Hello World!", res->body);
  2881. EXPECT_EQ(StatusCode::OK_200, res->status);
  2882. }
  2883. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2884. Server svr;
  2885. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. thread.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. Client cli(HOST, PORT);
  2896. cli.set_connection_timeout(std::chrono::seconds(5));
  2897. auto res =
  2898. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2899. "application/json", [](uint64_t, uint64_t) { return false; });
  2900. ASSERT_TRUE(!res);
  2901. EXPECT_EQ(Error::Canceled, res.error());
  2902. }
  2903. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2904. Server svr;
  2905. svr.set_payload_max_length(200 * 1024 * 1024);
  2906. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2907. res.set_content(LARGE_DATA, "text/plain");
  2908. });
  2909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2910. auto se = detail::scope_exit([&] {
  2911. svr.stop();
  2912. thread.join();
  2913. ASSERT_FALSE(svr.is_running());
  2914. });
  2915. svr.wait_until_ready();
  2916. Client cli(HOST, PORT);
  2917. cli.set_payload_max_length(200 * 1024 * 1024);
  2918. cli.set_connection_timeout(std::chrono::seconds(5));
  2919. auto res =
  2920. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2921. "application/json", [](uint64_t, uint64_t) { return false; });
  2922. ASSERT_TRUE(!res);
  2923. EXPECT_EQ(Error::Canceled, res.error());
  2924. }
  2925. TEST(CancelTest, NoCancelDelete) {
  2926. Server svr;
  2927. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2928. res.set_content("Hello World!", "text/plain");
  2929. });
  2930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2931. auto se = detail::scope_exit([&] {
  2932. svr.stop();
  2933. thread.join();
  2934. ASSERT_FALSE(svr.is_running());
  2935. });
  2936. svr.wait_until_ready();
  2937. Client cli(HOST, PORT);
  2938. cli.set_connection_timeout(std::chrono::seconds(5));
  2939. auto res =
  2940. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2941. "application/json", [](uint64_t, uint64_t) { return true; });
  2942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2943. EXPECT_EQ("Hello World!", res->body);
  2944. EXPECT_EQ(StatusCode::OK_200, res->status);
  2945. }
  2946. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2947. Server svr;
  2948. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2949. res.set_content("Hello World!", "text/plain");
  2950. });
  2951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2952. auto se = detail::scope_exit([&] {
  2953. svr.stop();
  2954. thread.join();
  2955. ASSERT_FALSE(svr.is_running());
  2956. });
  2957. svr.wait_until_ready();
  2958. Client cli(HOST, PORT);
  2959. cli.set_connection_timeout(std::chrono::seconds(5));
  2960. auto res =
  2961. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2962. "application/json", [](uint64_t, uint64_t) { return false; });
  2963. ASSERT_TRUE(!res);
  2964. EXPECT_EQ(Error::Canceled, res.error());
  2965. }
  2966. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2967. Server svr;
  2968. svr.set_payload_max_length(200 * 1024 * 1024);
  2969. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2970. res.set_content(LARGE_DATA, "text/plain");
  2971. });
  2972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2973. auto se = detail::scope_exit([&] {
  2974. svr.stop();
  2975. thread.join();
  2976. ASSERT_FALSE(svr.is_running());
  2977. });
  2978. svr.wait_until_ready();
  2979. Client cli(HOST, PORT);
  2980. cli.set_payload_max_length(200 * 1024 * 1024);
  2981. cli.set_connection_timeout(std::chrono::seconds(5));
  2982. auto res =
  2983. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2984. "application/json", [](uint64_t, uint64_t) { return false; });
  2985. ASSERT_TRUE(!res);
  2986. EXPECT_EQ(Error::Canceled, res.error());
  2987. }
  2988. // One stop() from another thread ends a request that waits for the response
  2989. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2990. Server svr;
  2991. std::atomic<bool> received{false};
  2992. std::atomic<bool> done{false};
  2993. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2994. received.store(true);
  2995. while (!done.load()) {
  2996. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2997. }
  2998. res.set_content("Hello World!", "text/plain");
  2999. });
  3000. auto port = svr.bind_to_any_port(HOST);
  3001. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3002. Client cli(HOST, port);
  3003. cli.set_read_timeout(std::chrono::seconds(30));
  3004. std::future<Result> request;
  3005. auto se = detail::scope_exit([&] {
  3006. done.store(true);
  3007. svr.stop();
  3008. thread.join();
  3009. ASSERT_FALSE(svr.is_running());
  3010. });
  3011. svr.wait_until_ready();
  3012. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3013. for (int i = 0; i < 500 && !received.load(); ++i) {
  3014. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3015. }
  3016. ASSERT_TRUE(received.load());
  3017. // Let the client block in the wait for the response
  3018. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3019. auto start = std::chrono::steady_clock::now();
  3020. cli.stop();
  3021. ASSERT_EQ(std::future_status::ready,
  3022. request.wait_for(std::chrono::seconds(5)));
  3023. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3024. auto res = request.get();
  3025. ASSERT_TRUE(!res);
  3026. EXPECT_EQ(Error::Read, res.error());
  3027. }
  3028. static std::string remove_whitespace(const std::string &input) {
  3029. std::string output;
  3030. output.reserve(input.size());
  3031. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3032. [](unsigned char c) { return !std::isspace(c); });
  3033. return output;
  3034. }
  3035. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3036. auto host = "httpbingo.org";
  3037. auto path = std::string{"/basic-auth/hello/world"};
  3038. #ifdef CPPHTTPLIB_SSL_ENABLED
  3039. auto port = 443;
  3040. SSLClient cli(host, port);
  3041. #else
  3042. auto port = 80;
  3043. Client cli(host, port);
  3044. #endif
  3045. {
  3046. auto res = cli.Get(path);
  3047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3048. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3049. }
  3050. {
  3051. auto res = cli.Get(
  3052. path, Headers{make_basic_authentication_header("hello", "world")});
  3053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3054. auto body = remove_whitespace(res->body);
  3055. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3056. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. }
  3059. {
  3060. cli.set_basic_auth("hello", "world");
  3061. auto res = cli.Get(path);
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. auto body = remove_whitespace(res->body);
  3064. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3065. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3066. EXPECT_EQ(StatusCode::OK_200, res->status);
  3067. }
  3068. {
  3069. cli.set_basic_auth("hello", "bad");
  3070. auto res = cli.Get(path);
  3071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3072. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3073. }
  3074. {
  3075. cli.set_basic_auth("bad", "world");
  3076. auto res = cli.Get(path);
  3077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3078. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3079. }
  3080. }
  3081. #ifdef CPPHTTPLIB_SSL_ENABLED
  3082. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3083. auto host = "httpbingo.org";
  3084. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3085. auto paths = std::vector<std::string>{
  3086. "/digest-auth/auth/hello/world/MD5",
  3087. "/digest-auth/auth/hello/world/SHA-256",
  3088. };
  3089. auto port = 443;
  3090. SSLClient cli(host, port);
  3091. {
  3092. auto res = cli.Get(unauth_path);
  3093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3094. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3095. }
  3096. {
  3097. cli.set_digest_auth("hello", "world");
  3098. for (const auto &path : paths) {
  3099. auto res = cli.Get(path.c_str());
  3100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3101. auto body = remove_whitespace(res->body);
  3102. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3103. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3104. EXPECT_EQ(StatusCode::OK_200, res->status);
  3105. }
  3106. cli.set_digest_auth("hello", "bad");
  3107. for (const auto &path : paths) {
  3108. auto res = cli.Get(path.c_str());
  3109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3110. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3111. }
  3112. }
  3113. }
  3114. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3115. // comma-separated list of challenges, and each challenge may itself carry a
  3116. // comma-separated auth-param list, so a server can legally offer Basic
  3117. // before Digest, either as two field lines or packed into one. Runs one 401
  3118. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3119. // value() joins them in receipt order) and checks that the retry carries a
  3120. // well-formed Digest Authorization header naming expected_realm.
  3121. static void
  3122. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3123. const std::string &expected_realm) {
  3124. std::atomic<int> hits{0};
  3125. Server svr;
  3126. svr.Get("/x", [&](const Request &req, Response &res) {
  3127. if (++hits == 1) {
  3128. res.status = StatusCode::Unauthorized_401;
  3129. for (const auto &challenge : challenges) {
  3130. res.set_header("WWW-Authenticate", challenge);
  3131. }
  3132. } else {
  3133. auto authorization = req.get_header_value("Authorization");
  3134. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3135. EXPECT_NE(std::string::npos,
  3136. authorization.find("realm=\"" + expected_realm + "\""));
  3137. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3138. res.set_content("ok", "text/plain");
  3139. }
  3140. });
  3141. auto port = svr.bind_to_any_port(HOST);
  3142. std::thread t([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. t.join();
  3146. });
  3147. svr.wait_until_ready();
  3148. Client cli(HOST, port);
  3149. cli.set_digest_auth("hello", "world");
  3150. auto res = cli.Get("/x");
  3151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3152. EXPECT_EQ(2, hits.load());
  3153. }
  3154. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3155. static const char *kDigestChallenge =
  3156. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3157. "algorithm=MD5";
  3158. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3159. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3160. "testrealm");
  3161. }
  3162. // Same challenge list with the schemes in the opposite order, to make sure
  3163. // the fix above didn't just special-case "Basic first".
  3164. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3165. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3166. "testrealm");
  3167. }
  3168. // A comma inside a quoted auth-param value must not be mistaken for the
  3169. // separator between two challenges (or two auth-params).
  3170. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3171. run_digest_challenge_list_test(
  3172. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3173. "algorithm=MD5"},
  3174. "test,realm");
  3175. }
  3176. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3177. // the params and leaves out the fragment.
  3178. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3179. Server svr;
  3180. std::string uri, target;
  3181. svr.Get("/a b", [&](const Request &req, Response &res) {
  3182. auto auth = req.get_header_value("Authorization");
  3183. if (auth.empty()) {
  3184. res.status = StatusCode::Unauthorized_401;
  3185. res.set_header("WWW-Authenticate",
  3186. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3187. return;
  3188. }
  3189. auto b = auth.find("uri=\"") + 5;
  3190. uri = auth.substr(b, auth.find('"', b) - b);
  3191. target = req.target;
  3192. });
  3193. auto port = svr.bind_to_any_port(HOST);
  3194. std::thread t([&]() { svr.listen_after_bind(); });
  3195. auto se = detail::scope_exit([&] {
  3196. svr.stop();
  3197. t.join();
  3198. });
  3199. svr.wait_until_ready();
  3200. Client cli(HOST, port);
  3201. cli.set_digest_auth("hello", "world");
  3202. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3204. EXPECT_EQ("/a%20b?x=1", target);
  3205. EXPECT_EQ(target, uri);
  3206. }
  3207. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3208. // make_digest_authentication_header() dereferences both unconditionally, so
  3209. // a server sending a challenge missing either one must not be treated as
  3210. // usable -- doing so used to crash the client with std::out_of_range.
  3211. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3212. Server svr;
  3213. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3214. res.status = StatusCode::Unauthorized_401;
  3215. res.set_header("WWW-Authenticate", challenge);
  3216. });
  3217. auto port = svr.bind_to_any_port(HOST);
  3218. std::thread t([&]() { svr.listen_after_bind(); });
  3219. auto se = detail::scope_exit([&] {
  3220. svr.stop();
  3221. t.join();
  3222. });
  3223. svr.wait_until_ready();
  3224. Client cli(HOST, port);
  3225. cli.set_digest_auth("hello", "world");
  3226. auto res = cli.Get("/x");
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3229. }
  3230. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3231. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3232. }
  3233. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3234. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3235. }
  3236. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3237. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3238. }
  3239. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3240. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3241. // when storing the values, so the header builder has to re-escape them (and
  3242. // keep algorithm a bare token); otherwise the value breaks out of its
  3243. // quoted-string and injects extra auth-params into the client's Authorization.
  3244. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3245. std::atomic<int> hits{0};
  3246. std::string authorization;
  3247. Server svr;
  3248. svr.Get("/x", [&](const Request &req, Response &res) {
  3249. if (++hits == 1) {
  3250. res.status = StatusCode::Unauthorized_401;
  3251. // On the wire the quotes embedded in the values are backslash-escaped.
  3252. res.set_header("WWW-Authenticate",
  3253. "Digest realm=\"testrealm\", "
  3254. "nonce=\"n\\\"; injected=\\\"x\", "
  3255. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3256. } else {
  3257. authorization = req.get_header_value("Authorization");
  3258. res.set_content("ok", "text/plain");
  3259. }
  3260. });
  3261. auto port = svr.bind_to_any_port(HOST);
  3262. std::thread t([&]() { svr.listen_after_bind(); });
  3263. auto se = detail::scope_exit([&] {
  3264. svr.stop();
  3265. t.join();
  3266. });
  3267. svr.wait_until_ready();
  3268. Client cli(HOST, port);
  3269. cli.set_digest_auth("hello", "world");
  3270. auto res = cli.Get("/x");
  3271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3272. EXPECT_EQ(2, hits.load());
  3273. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3274. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3275. // inside its quoted-string rather than starting an "injected" auth-param.
  3276. EXPECT_NE(std::string::npos,
  3277. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3278. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3279. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3280. }
  3281. #endif
  3282. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3283. auto host = "google.com";
  3284. auto another_host = "example.com";
  3285. auto wrong_ip = "0.0.0.0";
  3286. #ifdef CPPHTTPLIB_SSL_ENABLED
  3287. SSLClient cli(host);
  3288. #else
  3289. Client cli(host);
  3290. #endif
  3291. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3292. auto res = cli.Get("/");
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3295. }
  3296. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3297. auto host = "google.com";
  3298. auto wrong_ip = "0.0.0.0";
  3299. #ifdef CPPHTTPLIB_SSL_ENABLED
  3300. SSLClient cli(host);
  3301. #else
  3302. Client cli(host);
  3303. #endif
  3304. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3305. auto res = cli.Get("/");
  3306. ASSERT_TRUE(!res);
  3307. EXPECT_EQ(Error::Connection, res.error());
  3308. }
  3309. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3310. // A mapped value that is not an IP literal must be resolved. "localhost"
  3311. // resolves from the hosts file, so this test needs no external DNS.
  3312. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3313. auto host = "target.invalid";
  3314. Server svr;
  3315. std::string received_host;
  3316. svr.Get("/hi", [&](const Request &req, Response &res) {
  3317. received_host = req.get_header_value("Host");
  3318. res.set_content("Hello World!", "text/plain");
  3319. });
  3320. auto port = svr.bind_to_any_port(HOST);
  3321. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3322. auto se = detail::scope_exit([&] {
  3323. svr.stop();
  3324. thread.join();
  3325. ASSERT_FALSE(svr.is_running());
  3326. });
  3327. svr.wait_until_ready();
  3328. Client cli(host, port);
  3329. cli.set_direct_hostname_addr_map({{host, HOST}});
  3330. auto res = cli.Get("/hi");
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::OK_200, res->status);
  3333. // The mapping only redirects the connection; the identity stays host_.
  3334. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3335. }
  3336. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3337. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3338. auto host = "target.invalid";
  3339. Server svr;
  3340. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3341. res.set_content("Hello World!", "text/plain");
  3342. });
  3343. auto port = svr.bind_to_any_port("127.0.0.1");
  3344. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3345. auto se = detail::scope_exit([&] {
  3346. svr.stop();
  3347. thread.join();
  3348. ASSERT_FALSE(svr.is_running());
  3349. });
  3350. svr.wait_until_ready();
  3351. Client cli(host, port);
  3352. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3353. auto res = cli.Get("/hi");
  3354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3355. EXPECT_EQ(StatusCode::OK_200, res->status);
  3356. }
  3357. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3358. // An empty mapped value must leave host_ as the connection target. Without
  3359. // that guard the empty value would become the host argument, getaddrinfo
  3360. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3361. // loopback - silently connecting somewhere the caller never asked for.
  3362. // The server listens on loopback, so such a fallback would succeed and is
  3363. // therefore observable as a failure of this test.
  3364. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3365. Server svr;
  3366. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3367. res.set_content("Hello World!", "text/plain");
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. thread.join();
  3374. ASSERT_FALSE(svr.is_running());
  3375. });
  3376. svr.wait_until_ready();
  3377. Client cli(blackhole, port);
  3378. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3379. cli.set_connection_timeout(1);
  3380. auto res = cli.Get("/hi");
  3381. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3382. }
  3383. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3384. auto host = "target.invalid";
  3385. Server svr;
  3386. std::string received_host;
  3387. svr.Get("/hi", [&](const Request &req, Response &res) {
  3388. received_host = req.get_header_value("Host");
  3389. res.set_content("Hello World!", "text/plain");
  3390. });
  3391. auto port = svr.bind_to_any_port("127.0.0.1");
  3392. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3393. auto se = detail::scope_exit([&] {
  3394. svr.stop();
  3395. thread.join();
  3396. ASSERT_FALSE(svr.is_running());
  3397. });
  3398. svr.wait_until_ready();
  3399. Client cli(host, port);
  3400. #pragma GCC diagnostic push
  3401. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3402. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3403. #pragma GCC diagnostic pop
  3404. auto res = cli.Get("/hi");
  3405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3406. EXPECT_EQ(StatusCode::OK_200, res->status);
  3407. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3408. }
  3409. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3410. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3411. Server svr;
  3412. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3413. res.set_content("Hello World!", "text/plain");
  3414. });
  3415. auto port = svr.bind_to_any_port("127.0.0.1");
  3416. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. thread.join();
  3420. ASSERT_FALSE(svr.is_running());
  3421. });
  3422. svr.wait_until_ready();
  3423. Client cli("127.0.0.1", port);
  3424. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3425. cli.set_connection_timeout(1);
  3426. auto res = cli.Get("/hi");
  3427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3428. EXPECT_EQ(StatusCode::OK_200, res->status);
  3429. }
  3430. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3431. auto host = "httpbingo.org";
  3432. auto path = std::string{"/absolute-redirect/3"};
  3433. #ifdef CPPHTTPLIB_SSL_ENABLED
  3434. SSLClient cli(host);
  3435. #else
  3436. Client cli(host);
  3437. #endif
  3438. cli.set_follow_location(true);
  3439. auto res = cli.Get(path);
  3440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3441. EXPECT_EQ(StatusCode::OK_200, res->status);
  3442. }
  3443. TEST(RedirectTest, Redirect_Online) {
  3444. auto host = "httpbingo.org";
  3445. auto path = std::string{"/redirect/3"};
  3446. #ifdef CPPHTTPLIB_SSL_ENABLED
  3447. SSLClient cli(host);
  3448. #else
  3449. Client cli(host);
  3450. #endif
  3451. cli.set_follow_location(true);
  3452. auto res = cli.Get(path);
  3453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. }
  3456. TEST(RelativeRedirectTest, Redirect_Online) {
  3457. auto host = "httpbingo.org";
  3458. auto path = std::string{"/relative-redirect/3"};
  3459. #ifdef CPPHTTPLIB_SSL_ENABLED
  3460. SSLClient cli(host);
  3461. #else
  3462. Client cli(host);
  3463. #endif
  3464. cli.set_follow_location(true);
  3465. auto res = cli.Get(path);
  3466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. }
  3469. TEST(TooManyRedirectTest, Redirect_Online) {
  3470. auto host = "httpbingo.org";
  3471. auto path = std::string{"/redirect/21"};
  3472. #ifdef CPPHTTPLIB_SSL_ENABLED
  3473. SSLClient cli(host);
  3474. #else
  3475. Client cli(host);
  3476. #endif
  3477. cli.set_follow_location(true);
  3478. auto res = cli.Get(path);
  3479. ASSERT_TRUE(!res);
  3480. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3481. }
  3482. #ifdef CPPHTTPLIB_SSL_ENABLED
  3483. TEST(YahooRedirectTest, Redirect_Online) {
  3484. Client cli("yahoo.com");
  3485. auto res = cli.Get("/");
  3486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3487. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3488. cli.set_follow_location(true);
  3489. res = cli.Get("/");
  3490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3491. EXPECT_EQ(StatusCode::OK_200, res->status);
  3492. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3493. }
  3494. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3495. #define REDIR_HOST "httpbingo.org"
  3496. #define REDIR_PATH "/redirect-to"
  3497. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3498. SSLClient cli(REDIR_HOST);
  3499. cli.set_follow_location(true);
  3500. auto res =
  3501. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3503. EXPECT_EQ(StatusCode::OK_200, res->status);
  3504. }
  3505. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3506. SSLClient cli(REDIR_HOST);
  3507. cli.set_follow_location(true);
  3508. Params params;
  3509. params.emplace("url", "http://example.com");
  3510. params.emplace("status_code", "302");
  3511. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3513. EXPECT_EQ(StatusCode::OK_200, res->status);
  3514. }
  3515. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3516. SSLClient cli(REDIR_HOST);
  3517. cli.set_follow_location(true);
  3518. Params params;
  3519. params.emplace("url", "http://example.com");
  3520. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. }
  3524. TEST(UrlWithSpace, Redirect_Online) {
  3525. SSLClient cli("edge.forgecdn.net");
  3526. cli.set_follow_location(true);
  3527. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3531. }
  3532. #endif
  3533. #if !defined(_WIN32) && !defined(_WIN64)
  3534. TEST(ReceiveSignals, Signal) {
  3535. auto setupSignalHandlers = []() {
  3536. struct sigaction act;
  3537. sigemptyset(&act.sa_mask);
  3538. act.sa_flags = SA_SIGINFO;
  3539. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3540. switch (sig) {
  3541. case SIGINT:
  3542. default: break;
  3543. }
  3544. };
  3545. ::sigaction(SIGINT, &act, nullptr);
  3546. };
  3547. Server svr;
  3548. int port = 0;
  3549. auto thread = std::thread([&]() {
  3550. setupSignalHandlers();
  3551. port = svr.bind_to_any_port(HOST);
  3552. svr.listen_after_bind();
  3553. });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. ASSERT_TRUE(svr.is_running());
  3561. pthread_kill(thread.native_handle(), SIGINT);
  3562. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3563. ASSERT_TRUE(svr.is_running());
  3564. }
  3565. #endif
  3566. TEST(RedirectToDifferentPort, Redirect) {
  3567. Server svr1;
  3568. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3569. res.set_content("Hello World!", "text/plain");
  3570. });
  3571. int svr1_port = 0;
  3572. auto thread1 = std::thread([&]() {
  3573. svr1_port = svr1.bind_to_any_port(HOST);
  3574. svr1.listen_after_bind();
  3575. });
  3576. Server svr2;
  3577. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3578. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3579. });
  3580. int svr2_port = 0;
  3581. auto thread2 = std::thread([&]() {
  3582. svr2_port = svr2.bind_to_any_port(HOST);
  3583. svr2.listen_after_bind();
  3584. });
  3585. auto se = detail::scope_exit([&] {
  3586. svr2.stop();
  3587. thread2.join();
  3588. svr1.stop();
  3589. thread1.join();
  3590. ASSERT_FALSE(svr2.is_running());
  3591. ASSERT_FALSE(svr1.is_running());
  3592. });
  3593. svr1.wait_until_ready();
  3594. svr2.wait_until_ready();
  3595. Client cli("localhost", svr2_port);
  3596. cli.set_follow_location(true);
  3597. auto res = cli.Get("/2");
  3598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("Hello World!", res->body);
  3601. }
  3602. // GET /redir on one server redirects to /target on another port, so the
  3603. // client follows it with a new client.
  3604. static Result
  3605. GetThroughRedirectToDifferentPort(Server::Handler target,
  3606. const std::function<void(Client &)> &setup,
  3607. const Headers &headers = Headers()) {
  3608. Server target_svr;
  3609. target_svr.Get("/target", target);
  3610. int target_port = 0;
  3611. auto target_thread = std::thread([&]() {
  3612. target_port = target_svr.bind_to_any_port(HOST);
  3613. target_svr.listen_after_bind();
  3614. });
  3615. Server origin_svr;
  3616. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3617. res.set_redirect(
  3618. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3619. });
  3620. int origin_port = 0;
  3621. auto origin_thread = std::thread([&]() {
  3622. origin_port = origin_svr.bind_to_any_port(HOST);
  3623. origin_svr.listen_after_bind();
  3624. });
  3625. auto se = detail::scope_exit([&] {
  3626. origin_svr.stop();
  3627. origin_thread.join();
  3628. target_svr.stop();
  3629. target_thread.join();
  3630. });
  3631. target_svr.wait_until_ready();
  3632. origin_svr.wait_until_ready();
  3633. Client cli("localhost", origin_port);
  3634. cli.set_follow_location(true);
  3635. setup(cli);
  3636. return cli.Get("/redir", headers);
  3637. }
  3638. static void
  3639. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3640. std::string captured_authorization;
  3641. auto result = GetThroughRedirectToDifferentPort(
  3642. [&](const Request &req, Response &res) {
  3643. captured_authorization = req.get_header_value("Authorization");
  3644. res.set_content("OK", "text/plain");
  3645. },
  3646. set_auth);
  3647. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3648. EXPECT_EQ(StatusCode::OK_200, result->status);
  3649. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3650. EXPECT_TRUE(captured_authorization.empty());
  3651. }
  3652. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3653. TestDoNotForwardCredentialsOnRedirect(
  3654. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3655. }
  3656. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3657. TestDoNotForwardCredentialsOnRedirect(
  3658. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3659. }
  3660. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3661. std::string captured_cookie;
  3662. auto result = GetThroughRedirectToDifferentPort(
  3663. [&](const Request &req, Response &res) {
  3664. captured_cookie = req.get_header_value("Cookie");
  3665. res.set_content("OK", "text/plain");
  3666. },
  3667. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3668. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3669. EXPECT_EQ(StatusCode::OK_200, result->status);
  3670. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3671. EXPECT_TRUE(captured_cookie.empty());
  3672. }
  3673. TEST(RedirectToSamePort, ForwardCookie) {
  3674. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3675. // header so that ordinary session flows keep working.
  3676. Server svr;
  3677. std::string captured_cookie;
  3678. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3679. res.set_redirect("/target", 302);
  3680. });
  3681. svr.Get("/target", [&](const Request &req, Response &res) {
  3682. captured_cookie = req.get_header_value("Cookie");
  3683. res.set_content("OK", "text/plain");
  3684. });
  3685. auto port = svr.bind_to_any_port(HOST);
  3686. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3687. auto se = detail::scope_exit([&] {
  3688. svr.stop();
  3689. thread.join();
  3690. ASSERT_FALSE(svr.is_running());
  3691. });
  3692. svr.wait_until_ready();
  3693. Client cli(HOST, port);
  3694. cli.set_follow_location(true);
  3695. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3696. auto res = cli.Get("/redir", headers);
  3697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3698. EXPECT_EQ(StatusCode::OK_200, res->status);
  3699. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3700. }
  3701. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3702. // The Location alone names the next target, on any origin.
  3703. Server target_svr;
  3704. std::string cross_target;
  3705. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3706. cross_target = req.target;
  3707. res.set_content("OK", "text/plain");
  3708. });
  3709. auto target_port = target_svr.bind_to_any_port(HOST);
  3710. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3711. Server origin_svr;
  3712. std::string same_target;
  3713. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3714. res.set_redirect(
  3715. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3716. });
  3717. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3718. res.set_redirect("/landing", 302);
  3719. });
  3720. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3721. same_target = req.target;
  3722. res.set_content("OK", "text/plain");
  3723. });
  3724. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3725. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3726. auto se = detail::scope_exit([&] {
  3727. origin_svr.stop();
  3728. origin_thread.join();
  3729. target_svr.stop();
  3730. target_thread.join();
  3731. });
  3732. target_svr.wait_until_ready();
  3733. origin_svr.wait_until_ready();
  3734. Client cli("localhost", origin_port);
  3735. cli.set_follow_location(true);
  3736. Request req;
  3737. req.method = "GET";
  3738. req.params = {{"api_key", "SECRET"}};
  3739. req.path = "/cross";
  3740. auto res = cli.send(req);
  3741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3742. EXPECT_EQ("/landing", cross_target);
  3743. req.path = "/same";
  3744. res = cli.send(req);
  3745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3746. EXPECT_EQ("/landing", same_target);
  3747. }
  3748. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3749. std::string authorization;
  3750. std::string trace_id;
  3751. auto result = GetThroughRedirectToDifferentPort(
  3752. [&](const Request &req, Response &res) {
  3753. authorization = req.get_header_value("Authorization");
  3754. trace_id = req.get_header_value("X-Trace-Id");
  3755. res.set_content("OK", "text/plain");
  3756. },
  3757. [](Client &cli) {
  3758. cli.set_default_headers(
  3759. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3760. });
  3761. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3762. EXPECT_EQ(StatusCode::OK_200, result->status);
  3763. // Like a header given with the request, a default one goes along unless it
  3764. // carries credentials (RFC 9110 15.4).
  3765. EXPECT_TRUE(authorization.empty());
  3766. EXPECT_EQ("42", trace_id);
  3767. }
  3768. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3769. auto result = GetThroughRedirectToDifferentPort(
  3770. [](const Request &, Response &res) {
  3771. res.set_content(std::string(2048, 'x'), "text/plain");
  3772. },
  3773. [](Client &cli) { cli.set_payload_max_length(1024); });
  3774. EXPECT_FALSE(result);
  3775. }
  3776. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3777. auto result = GetThroughRedirectToDifferentPort(
  3778. [](const Request &req, Response &res) {
  3779. // Answer after a second, or once the client gives up.
  3780. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3781. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3782. }
  3783. res.set_content("late", "text/plain");
  3784. },
  3785. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3786. ASSERT_FALSE(result);
  3787. EXPECT_EQ(Error::Read, result.error());
  3788. }
  3789. #ifdef CPPHTTPLIB_SSL_ENABLED
  3790. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3791. auto result = GetThroughRedirectToDifferentPort(
  3792. [](const Request &, Response &res) {
  3793. res.status = StatusCode::Unauthorized_401;
  3794. res.set_header("WWW-Authenticate",
  3795. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3796. },
  3797. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3798. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3799. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3800. }
  3801. #endif
  3802. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3803. Server svr;
  3804. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3805. // Port number that overflows int — should not crash
  3806. res.set_redirect("http://localhost:99999999999999999999/target");
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. Client cli(HOST, port);
  3817. cli.set_follow_location(true);
  3818. auto res = cli.Get("/redir");
  3819. // Should fail gracefully, not crash (no valid response due to bad port)
  3820. EXPECT_FALSE(res);
  3821. }
  3822. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3823. Server svr;
  3824. auto port = svr.bind_to_any_port(HOST);
  3825. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3826. // The server's own port followed by junk must not be followed
  3827. res.set_redirect("http://" + std::string(HOST) + ":" +
  3828. std::to_string(port) + "junk/target");
  3829. });
  3830. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3831. res.set_content("target", "text/plain");
  3832. });
  3833. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. Client cli(HOST, port);
  3841. cli.set_follow_location(true);
  3842. auto res = cli.Get("/redir");
  3843. EXPECT_FALSE(res);
  3844. }
  3845. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3846. Server svr;
  3847. std::atomic<bool> followed{false};
  3848. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3849. res.status = StatusCode::NotModified_304;
  3850. res.set_header("Location", "/target");
  3851. });
  3852. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3853. res.status = StatusCode::UseProxy_305;
  3854. res.set_header("Location", "/target");
  3855. });
  3856. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3857. followed = true;
  3858. res.set_content("target", "text/plain");
  3859. });
  3860. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3861. auto se = detail::scope_exit([&] {
  3862. svr.stop();
  3863. th.join();
  3864. ASSERT_FALSE(svr.is_running());
  3865. });
  3866. svr.wait_until_ready();
  3867. Client cli("localhost", PORT);
  3868. cli.set_follow_location(true);
  3869. auto res = cli.Get("/304");
  3870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3871. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3872. res = cli.Get("/305");
  3873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3874. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3875. EXPECT_FALSE(followed);
  3876. }
  3877. TEST(RedirectFromPageWithContent, Redirect) {
  3878. Server svr;
  3879. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3880. res.set_content("___", "text/plain");
  3881. res.set_redirect("/2");
  3882. });
  3883. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3884. res.set_content("Hello World!", "text/plain");
  3885. });
  3886. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. th.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. Client cli("localhost", PORT);
  3895. cli.set_follow_location(true);
  3896. std::string body;
  3897. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3898. body.append(data, data_length);
  3899. return true;
  3900. });
  3901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3902. EXPECT_EQ(StatusCode::OK_200, res->status);
  3903. EXPECT_EQ("Hello World!", body);
  3904. }
  3905. {
  3906. Client cli("localhost", PORT);
  3907. std::string body;
  3908. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3909. body.append(data, data_length);
  3910. return true;
  3911. });
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::Found_302, res->status);
  3914. EXPECT_EQ("___", body);
  3915. }
  3916. }
  3917. // A server can close the connection after a request with "Connection: close"
  3918. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3919. // redirected request must go out on a new connection.
  3920. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3921. #ifndef _WIN32
  3922. signal(SIGPIPE, SIG_IGN);
  3923. #endif
  3924. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3925. default_socket_options(srv);
  3926. sockaddr_in addr{};
  3927. addr.sin_family = AF_INET;
  3928. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3929. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3930. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3931. ASSERT_EQ(0, ::listen(srv, 2));
  3932. auto send_text = [](socket_t sock, const std::string &text) {
  3933. ::send(sock,
  3934. #ifdef _WIN32
  3935. static_cast<const char *>(text.c_str()),
  3936. static_cast<int>(text.size()),
  3937. #else
  3938. text.c_str(), text.size(),
  3939. #endif
  3940. 0);
  3941. };
  3942. auto reused = false;
  3943. auto server_thread = std::thread([&] {
  3944. char buf[4096];
  3945. auto first = ::accept(srv, nullptr, nullptr);
  3946. if (first == INVALID_SOCKET) { return; }
  3947. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3948. ::recv(first, buf, sizeof(buf), 0);
  3949. send_text(
  3950. first,
  3951. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3952. auto next = first;
  3953. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3954. reused = true;
  3955. } else {
  3956. detail::close_socket(first);
  3957. next = ::accept(srv, nullptr, nullptr);
  3958. if (next == INVALID_SOCKET) { return; }
  3959. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3960. ::recv(next, buf, sizeof(buf), 0);
  3961. }
  3962. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3963. "Connection: close\r\n\r\nok");
  3964. detail::close_socket(next);
  3965. });
  3966. Client cli("127.0.0.1", PORT + 2);
  3967. cli.set_follow_location(true);
  3968. cli.set_read_timeout(5, 0);
  3969. auto res = cli.Get("/1");
  3970. server_thread.join();
  3971. detail::close_socket(srv);
  3972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3973. EXPECT_EQ(StatusCode::OK_200, res->status);
  3974. EXPECT_EQ("ok", res->body);
  3975. EXPECT_FALSE(reused);
  3976. }
  3977. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3978. Server svr;
  3979. auto port_str = std::to_string(PORT);
  3980. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3981. auto expected_host = "[::1]:" + port_str;
  3982. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3983. res.set_content("___", "text/plain");
  3984. // res.set_redirect("/2");
  3985. res.set_redirect(redirect_url);
  3986. });
  3987. svr.Get("/2", [&](const Request &req, Response &res) {
  3988. auto host_header = req.headers.find("Host");
  3989. ASSERT_TRUE(host_header != req.headers.end());
  3990. EXPECT_EQ(expected_host, host_header->second);
  3991. res.set_content("Hello World!", "text/plain");
  3992. });
  3993. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3994. auto se = detail::scope_exit([&] {
  3995. svr.stop();
  3996. th.join();
  3997. ASSERT_FALSE(svr.is_running());
  3998. });
  3999. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4000. // actually starts anything, so the condition !svr.is_running() will
  4001. // always remain true, and the loop never stops.
  4002. // This basically counts how many milliseconds have passed since the
  4003. // call to svr.listen(), and if after 5 seconds nothing started yet
  4004. // aborts the test.
  4005. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4006. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4007. ASSERT_LT(milliseconds, 5000U);
  4008. }
  4009. {
  4010. Client cli("::1", PORT);
  4011. cli.set_follow_location(true);
  4012. std::string body;
  4013. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4014. body.append(data, data_length);
  4015. return true;
  4016. });
  4017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4018. EXPECT_EQ(StatusCode::OK_200, res->status);
  4019. EXPECT_EQ("Hello World!", body);
  4020. }
  4021. {
  4022. Client cli("::1", PORT);
  4023. std::string body;
  4024. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4025. body.append(data, data_length);
  4026. return true;
  4027. });
  4028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4029. EXPECT_EQ(StatusCode::Found_302, res->status);
  4030. EXPECT_EQ("___", body);
  4031. }
  4032. }
  4033. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4034. Server svr;
  4035. svr.Get("/foo", [](const Request &req, Response &res) {
  4036. auto a = req.params.find("a");
  4037. if (a != req.params.end()) {
  4038. res.set_content((*a).second, "text/plain");
  4039. res.status = StatusCode::OK_200;
  4040. } else {
  4041. res.status = StatusCode::BadRequest_400;
  4042. }
  4043. });
  4044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4045. auto se = detail::scope_exit([&] {
  4046. svr.stop();
  4047. thread.join();
  4048. ASSERT_FALSE(svr.is_running());
  4049. });
  4050. svr.wait_until_ready();
  4051. {
  4052. Client cli(HOST, PORT);
  4053. cli.set_path_encode(false);
  4054. auto res = cli.Get("/foo?a=explicitly+encoded");
  4055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4056. EXPECT_EQ(StatusCode::OK_200, res->status);
  4057. // This expects it back with a space, as the `+` won't have been
  4058. // url-encoded, and server-side the params get decoded turning `+`
  4059. // into spaces.
  4060. EXPECT_EQ("explicitly encoded", res->body);
  4061. }
  4062. }
  4063. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4064. // When path encoding is disabled the client must transmit the supplied
  4065. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4066. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4067. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4068. // than a space (0x20). Assert on the raw wire target to catch this.
  4069. Server svr;
  4070. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4071. svr.Get("/foo", [&](const Request &req, Response &res) {
  4072. EXPECT_EQ(expected_target, req.target);
  4073. res.status = StatusCode::OK_200;
  4074. });
  4075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4076. auto se = detail::scope_exit([&] {
  4077. svr.stop();
  4078. thread.join();
  4079. ASSERT_FALSE(svr.is_running());
  4080. });
  4081. svr.wait_until_ready();
  4082. {
  4083. Client cli(HOST, PORT);
  4084. cli.set_path_encode(false);
  4085. auto res = cli.Get(expected_target.c_str());
  4086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4087. EXPECT_EQ(StatusCode::OK_200, res->status);
  4088. }
  4089. }
  4090. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4091. // `open_stream()` used to skip the path encoding that the buffered send
  4092. // path applies, so the same `path` produced different bytes in the request
  4093. // line depending on which API was used. Assert the two agree.
  4094. Server svr;
  4095. std::string target;
  4096. svr.Get(".*", [&](const Request &req, Response &res) {
  4097. target = req.target;
  4098. res.status = StatusCode::OK_200;
  4099. });
  4100. auto port = svr.bind_to_any_port(HOST);
  4101. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. thread.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. struct {
  4109. const char *path;
  4110. const char *expected;
  4111. } cases[] = {
  4112. {"/a b?x=1", "/a%20b?x=1"},
  4113. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4114. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4115. };
  4116. for (const auto &c : cases) {
  4117. Client cli(HOST, port);
  4118. target.clear();
  4119. auto res = cli.Get(c.path);
  4120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4121. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4122. auto buffered_target = target;
  4123. target.clear();
  4124. auto handle = cli.open_stream("GET", c.path);
  4125. EXPECT_TRUE(handle.is_valid())
  4126. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4127. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4128. }
  4129. }
  4130. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4131. // The `set_path_encode(false)` contract — transmit the supplied target
  4132. // verbatim — must hold for the streaming API too.
  4133. Server svr;
  4134. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4135. std::string target;
  4136. svr.Get("/foo", [&](const Request &req, Response &res) {
  4137. target = req.target;
  4138. res.status = StatusCode::OK_200;
  4139. });
  4140. auto port = svr.bind_to_any_port(HOST);
  4141. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4142. auto se = detail::scope_exit([&] {
  4143. svr.stop();
  4144. thread.join();
  4145. ASSERT_FALSE(svr.is_running());
  4146. });
  4147. svr.wait_until_ready();
  4148. {
  4149. Client cli(HOST, port);
  4150. cli.set_path_encode(false);
  4151. auto handle = cli.open_stream("GET", expected_target);
  4152. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4153. EXPECT_EQ(expected_target, target);
  4154. }
  4155. }
  4156. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4157. // With path encoding enabled a CR/LF in the target is percent-encoded
  4158. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4159. // write_request_line still backstops `set_path_encode(false)`, which is
  4160. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4161. Server svr;
  4162. // Captured before routing: the decoded path contains a newline, which a
  4163. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4164. std::string target;
  4165. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4166. target = req.target;
  4167. res.status = StatusCode::OK_200;
  4168. return Server::HandlerResponse::Handled;
  4169. });
  4170. auto port = svr.bind_to_any_port(HOST);
  4171. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4172. auto se = detail::scope_exit([&] {
  4173. svr.stop();
  4174. thread.join();
  4175. ASSERT_FALSE(svr.is_running());
  4176. });
  4177. svr.wait_until_ready();
  4178. {
  4179. Client cli(HOST, port);
  4180. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4181. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4182. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4183. }
  4184. }
  4185. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4186. // Every control character is percent-encoded, not just CR/LF, so the target
  4187. // passes the request-target check in write_request_line.
  4188. Server svr;
  4189. std::string target;
  4190. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4191. target = req.target;
  4192. res.status = StatusCode::OK_200;
  4193. return Server::HandlerResponse::Handled;
  4194. });
  4195. auto port = svr.bind_to_any_port(HOST);
  4196. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4197. auto se = detail::scope_exit([&] {
  4198. svr.stop();
  4199. thread.join();
  4200. ASSERT_FALSE(svr.is_running());
  4201. });
  4202. svr.wait_until_ready();
  4203. {
  4204. Client cli(HOST, port);
  4205. auto res = cli.Get("/a\tb\x1b\x7f");
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ("/a%09b%1B%7F", target);
  4208. }
  4209. }
  4210. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4211. // Nothing may reach the wire: a raw CR/LF target would split the request
  4212. // line and inject headers.
  4213. Server svr;
  4214. // Pre-routing so that "not called" means nothing reached the server at all,
  4215. // rather than merely failing to match a handler pattern.
  4216. auto handler_called = false;
  4217. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4218. handler_called = true;
  4219. res.status = StatusCode::OK_200;
  4220. return Server::HandlerResponse::Handled;
  4221. });
  4222. auto port = svr.bind_to_any_port(HOST);
  4223. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4224. auto se = detail::scope_exit([&] {
  4225. svr.stop();
  4226. thread.join();
  4227. ASSERT_FALSE(svr.is_running());
  4228. });
  4229. svr.wait_until_ready();
  4230. {
  4231. Client cli(HOST, port);
  4232. cli.set_path_encode(false);
  4233. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4234. EXPECT_FALSE(handle.is_valid());
  4235. EXPECT_EQ(Error::Write, handle.error);
  4236. EXPECT_FALSE(handler_called);
  4237. }
  4238. }
  4239. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4240. // Which of the two branches runs is decided by whether the query component
  4241. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4242. // an empty query and must still fall back to building one from
  4243. // `req.params`, while a non-empty query must win over `req.params`.
  4244. Server svr;
  4245. std::string target;
  4246. svr.Get("/foo", [&](const Request &req, Response &res) {
  4247. target = req.target;
  4248. res.status = StatusCode::OK_200;
  4249. });
  4250. auto port = svr.bind_to_any_port(HOST);
  4251. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4252. auto se = detail::scope_exit([&] {
  4253. svr.stop();
  4254. thread.join();
  4255. ASSERT_FALSE(svr.is_running());
  4256. });
  4257. svr.wait_until_ready();
  4258. {
  4259. // Trailing `?` -> empty query component -> `req.params` is used.
  4260. Client cli(HOST, port);
  4261. Request req;
  4262. req.method = "GET";
  4263. req.path = "/foo?";
  4264. req.params.emplace("a", "1");
  4265. target.clear();
  4266. auto res = cli.send(req);
  4267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4268. EXPECT_EQ("/foo?a=1", target);
  4269. }
  4270. {
  4271. // Non-empty query in `req.path` -> `req.params` is not appended.
  4272. Client cli(HOST, port);
  4273. Request req;
  4274. req.method = "GET";
  4275. req.path = "/foo?b=2";
  4276. req.params.emplace("a", "1");
  4277. target.clear();
  4278. auto res = cli.send(req);
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ("/foo?b=2", target);
  4281. }
  4282. }
  4283. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4284. Server svr;
  4285. svr.Get("/", [](const Request &req, Response &) {
  4286. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4287. });
  4288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. thread.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. {
  4296. Client cli(HOST, PORT);
  4297. cli.set_path_encode(false);
  4298. auto res = cli.Get("/?something=%0A");
  4299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4300. EXPECT_EQ(StatusCode::OK_200, res->status);
  4301. }
  4302. }
  4303. TEST(BindServerTest, BindDualStack) {
  4304. Server svr;
  4305. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4306. res.set_content("Hello World!", "text/plain");
  4307. });
  4308. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4309. auto se = detail::scope_exit([&] {
  4310. svr.stop();
  4311. thread.join();
  4312. ASSERT_FALSE(svr.is_running());
  4313. });
  4314. svr.wait_until_ready();
  4315. {
  4316. Client cli("127.0.0.1", PORT);
  4317. auto res = cli.Get("/1");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. EXPECT_EQ("Hello World!", res->body);
  4321. }
  4322. {
  4323. Client cli("::1", PORT);
  4324. auto res = cli.Get("/1");
  4325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ("Hello World!", res->body);
  4328. }
  4329. }
  4330. TEST(BindServerTest, BindAndListenSeparately) {
  4331. Server svr;
  4332. int port = svr.bind_to_any_port("0.0.0.0");
  4333. ASSERT_TRUE(svr.is_valid());
  4334. ASSERT_TRUE(port > 0);
  4335. svr.stop();
  4336. }
  4337. // Reports whether anything is still listening on a loopback port. A plain
  4338. // connect() is used instead of a Client request because a socket left bound by
  4339. // mistake accepts the connection into its backlog and never answers, which
  4340. // would hang the test instead of failing it.
  4341. static bool is_loopback_port_accepting(int port) {
  4342. sockaddr_in addr{};
  4343. addr.sin_family = AF_INET;
  4344. addr.sin_port = htons(static_cast<uint16_t>(port));
  4345. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4346. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4347. EXPECT_NE(sock, INVALID_SOCKET);
  4348. if (sock == INVALID_SOCKET) { return false; }
  4349. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4350. static_cast<socklen_t>(sizeof(addr)));
  4351. detail::close_socket(sock);
  4352. return ret == 0;
  4353. }
  4354. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4355. Server svr;
  4356. auto port = svr.bind_to_any_port("127.0.0.1");
  4357. ASSERT_TRUE(port > 0);
  4358. svr.stop();
  4359. // bind_to_any_port() already called listen(2), so until stop() closed the
  4360. // descriptor the port kept accepting connections into the backlog. ASSERT
  4361. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4362. // below blocks forever in the accept loop.
  4363. ASSERT_FALSE(is_loopback_port_accepting(port));
  4364. // Nothing is left to accept on, so listen_after_bind() must report failure
  4365. // instead of returning success without ever serving.
  4366. EXPECT_FALSE(svr.listen_after_bind());
  4367. // The failed listen marks the server decommissioned, so a waiter returns
  4368. // instead of spinning forever.
  4369. svr.wait_until_ready();
  4370. }
  4371. #ifdef CPPHTTPLIB_SSL_ENABLED
  4372. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4374. CLIENT_CA_CERT_DIR);
  4375. int port = svr.bind_to_any_port("0.0.0.0");
  4376. ASSERT_TRUE(svr.is_valid());
  4377. ASSERT_TRUE(port > 0);
  4378. svr.stop();
  4379. }
  4380. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4381. // or a rejected CustomRoute() registration would not stop the server binding.
  4382. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4384. CLIENT_CA_CERT_DIR);
  4385. ASSERT_TRUE(svr.is_valid());
  4386. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4387. EXPECT_FALSE(svr.is_valid());
  4388. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4389. }
  4390. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4391. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4392. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4393. int port = svr.bind_to_any_port("0.0.0.0");
  4394. ASSERT_TRUE(svr.is_valid());
  4395. ASSERT_TRUE(port > 0);
  4396. svr.stop();
  4397. }
  4398. TEST(BindServerTest, UpdateCertsPem) {
  4399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4400. int port = svr.bind_to_any_port("0.0.0.0");
  4401. ASSERT_TRUE(svr.is_valid());
  4402. ASSERT_TRUE(port > 0);
  4403. // Read PEM files
  4404. std::string cert_pem, key_pem, ca_pem;
  4405. read_file(SERVER_CERT_FILE, cert_pem);
  4406. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4407. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4408. // Update server certificates using PEM API
  4409. ASSERT_TRUE(
  4410. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4411. ASSERT_TRUE(svr.is_valid());
  4412. svr.stop();
  4413. }
  4414. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4415. // Start server with client CA (enables client auth)
  4416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4417. ASSERT_TRUE(svr.is_valid());
  4418. bool handler_called = false;
  4419. svr.Get("/test", [&](const Request &req, Response &res) {
  4420. handler_called = true;
  4421. // Verify client certificate is present
  4422. auto cert = req.peer_cert();
  4423. EXPECT_TRUE(static_cast<bool>(cert));
  4424. res.set_content("ok", "text/plain");
  4425. });
  4426. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4427. auto se = detail::scope_exit([&] {
  4428. svr.stop();
  4429. t.join();
  4430. ASSERT_FALSE(svr.is_running());
  4431. });
  4432. svr.wait_until_ready();
  4433. // Read PEM files
  4434. std::string cert_pem, key_pem, ca_pem;
  4435. read_file(SERVER_CERT_FILE, cert_pem);
  4436. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4437. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4438. // Update server certificates and client CA using PEM API while server running
  4439. ASSERT_TRUE(
  4440. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4441. // Connect with client certificate
  4442. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4443. cli.enable_server_certificate_verification(false);
  4444. cli.set_connection_timeout(30);
  4445. auto res = cli.Get("/test");
  4446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4447. ASSERT_EQ(StatusCode::OK_200, res->status);
  4448. ASSERT_TRUE(handler_called);
  4449. EXPECT_EQ("ok", res->body);
  4450. }
  4451. // Puts a CA that did not sign the client's certificate in the old one's place.
  4452. static bool replace_client_ca(SSLServer &svr) {
  4453. std::string cert_pem, key_pem, ca_pem;
  4454. read_file(SERVER_CERT_FILE, cert_pem);
  4455. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4456. read_file(SERVER_CERT2_FILE, ca_pem);
  4457. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4458. ca_pem.c_str());
  4459. }
  4460. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4462. ASSERT_TRUE(svr.is_valid());
  4463. svr.Get("/test", [](const Request &, Response &res) {
  4464. res.set_content("ok", "text/plain");
  4465. });
  4466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4467. auto se = detail::scope_exit([&] {
  4468. svr.stop();
  4469. t.join();
  4470. ASSERT_FALSE(svr.is_running());
  4471. });
  4472. svr.wait_until_ready();
  4473. auto get = [] {
  4474. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4475. cli.enable_server_certificate_verification(false);
  4476. return cli.Get("/test");
  4477. };
  4478. ASSERT_TRUE(get());
  4479. ASSERT_TRUE(replace_client_ca(svr));
  4480. EXPECT_FALSE(get());
  4481. }
  4482. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4483. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4485. ASSERT_TRUE(svr.is_valid());
  4486. tls::set_verify_callback(svr.tls_context(),
  4487. [](const tls::VerifyContext &) -> bool {
  4488. throw std::runtime_error("verify");
  4489. });
  4490. svr.Get("/test", [](const Request &, Response &res) {
  4491. res.set_content("ok", "text/plain");
  4492. });
  4493. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4494. auto se = detail::scope_exit([&] {
  4495. svr.stop();
  4496. t.join();
  4497. ASSERT_FALSE(svr.is_running());
  4498. });
  4499. svr.wait_until_ready();
  4500. auto get = [] {
  4501. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4502. cli.enable_server_certificate_verification(false);
  4503. return cli.Get("/test");
  4504. };
  4505. EXPECT_FALSE(get());
  4506. // The handshake is over, so an update does not wait for it.
  4507. std::string cert_pem, key_pem;
  4508. read_file(SERVER_CERT_FILE, cert_pem);
  4509. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4510. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4511. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4512. return v.preverify_ok;
  4513. });
  4514. auto res = get();
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. EXPECT_EQ("ok", res->body);
  4517. }
  4518. #endif
  4519. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4520. // Sends each request over a new connection with a client certificate,
  4521. // resuming the session of the one before when there is one.
  4522. class ResumingClient {
  4523. public:
  4524. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4525. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4526. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4527. SSL_FILETYPE_PEM);
  4528. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4529. // callback, not through SSL_get1_session().
  4530. SSL_CTX_set_app_data(ctx_, this);
  4531. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4532. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4533. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4534. auto self = static_cast<ResumingClient *>(
  4535. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4536. SSL_SESSION_free(self->session_);
  4537. self->session_ = session;
  4538. return 1; // Keeps the reference
  4539. });
  4540. }
  4541. ~ResumingClient() {
  4542. SSL_SESSION_free(session_);
  4543. SSL_CTX_free(ctx_);
  4544. }
  4545. // Tells whether the request was answered.
  4546. bool get() {
  4547. auto error = Error::Success;
  4548. auto sock = detail::create_client_socket(
  4549. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4550. /*connection_timeout_sec=*/5, 0,
  4551. /*read_timeout_sec=*/5, 0,
  4552. /*write_timeout_sec=*/5, 0, std::string(), error);
  4553. if (sock == INVALID_SOCKET) { return false; }
  4554. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4555. auto ssl = SSL_new(ctx_);
  4556. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4557. SSL_set_fd(ssl, static_cast<int>(sock));
  4558. if (session_) { SSL_set_session(ssl, session_); }
  4559. if (SSL_connect(ssl) != 1) { return false; }
  4560. reused_ = SSL_session_reused(ssl) == 1;
  4561. // Reading the response also takes in a TLS 1.3 session ticket.
  4562. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4563. "Connection: close\r\n\r\n";
  4564. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4565. std::string res;
  4566. char buf[256];
  4567. int n;
  4568. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4569. res.append(buf, static_cast<size_t>(n));
  4570. }
  4571. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4572. SSL_shutdown(ssl);
  4573. return res.find("200 OK") != std::string::npos;
  4574. }
  4575. // Whether the last connection resumed a session
  4576. bool reused() const { return reused_; }
  4577. private:
  4578. SSL_CTX *ctx_;
  4579. SSL_SESSION *session_ = nullptr;
  4580. bool reused_ = false;
  4581. };
  4582. // A client that resumes its session gets through, but not once the client CA
  4583. // has changed, as a resumed session does not show the certificate again.
  4584. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4586. ASSERT_TRUE(svr.is_valid());
  4587. svr.Get("/test", [](const Request &, Response &res) {
  4588. res.set_content("ok", "text/plain");
  4589. });
  4590. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4591. auto se = detail::scope_exit([&] {
  4592. svr.stop();
  4593. t.join();
  4594. ASSERT_FALSE(svr.is_running());
  4595. });
  4596. svr.wait_until_ready();
  4597. ResumingClient cli;
  4598. ASSERT_TRUE(cli.get());
  4599. ASSERT_TRUE(cli.get());
  4600. EXPECT_TRUE(cli.reused());
  4601. ASSERT_TRUE(replace_client_ca(svr));
  4602. EXPECT_FALSE(cli.get());
  4603. }
  4604. // A resumed session does not show the certificate again, so the server does
  4605. // not resume one with a verify callback to run on it.
  4606. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4608. ASSERT_TRUE(svr.is_valid());
  4609. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4610. return v.preverify_ok;
  4611. });
  4612. svr.Get("/test", [](const Request &, Response &res) {
  4613. res.set_content("ok", "text/plain");
  4614. });
  4615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4616. auto se = detail::scope_exit([&] {
  4617. svr.stop();
  4618. t.join();
  4619. ASSERT_FALSE(svr.is_running());
  4620. });
  4621. svr.wait_until_ready();
  4622. ResumingClient cli;
  4623. ASSERT_TRUE(cli.get());
  4624. ASSERT_TRUE(cli.get());
  4625. EXPECT_FALSE(cli.reused());
  4626. }
  4627. #endif
  4628. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4629. // wolfSSL shares its session cache between contexts, so a resumed session
  4630. // could carry a client certificate checked against another server's CA, or
  4631. // against a client CA since replaced.
  4632. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4634. ASSERT_TRUE(svr.is_valid());
  4635. // Trusts a CA that did not sign the client's certificate.
  4636. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4637. ASSERT_TRUE(other.is_valid());
  4638. for (auto s : {&svr, &other}) {
  4639. s->Get("/test", [](const Request &, Response &res) {
  4640. res.set_content("ok", "text/plain");
  4641. });
  4642. }
  4643. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4644. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4645. auto se = detail::scope_exit([&] {
  4646. other.stop();
  4647. svr.stop();
  4648. t2.join();
  4649. t.join();
  4650. });
  4651. svr.wait_until_ready();
  4652. other.wait_until_ready();
  4653. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4654. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4655. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4656. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4657. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4658. ASSERT_EQ(WOLFSSL_SUCCESS,
  4659. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4660. WOLFSSL_FILETYPE_PEM));
  4661. WOLFSSL_SESSION *session = nullptr;
  4662. auto session_se = detail::scope_exit([&] {
  4663. if (session) { wolfSSL_SESSION_free(session); }
  4664. });
  4665. // A request over a new connection, resuming `session` when there is one and
  4666. // keeping the connection's own in its place. Tells whether it was answered.
  4667. auto get = [&](int port) {
  4668. auto error = Error::Success;
  4669. auto sock = detail::create_client_socket(
  4670. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4671. /*connection_timeout_sec=*/5, 0,
  4672. /*read_timeout_sec=*/5, 0,
  4673. /*write_timeout_sec=*/5, 0, std::string(), error);
  4674. if (sock == INVALID_SOCKET) { return false; }
  4675. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4676. auto ssl = wolfSSL_new(ctx);
  4677. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4678. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4679. if (session) { wolfSSL_set_session(ssl, session); }
  4680. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4681. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4682. "Connection: close\r\n\r\n";
  4683. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4684. std::string res;
  4685. char buf[256];
  4686. int n;
  4687. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4688. res.append(buf, static_cast<size_t>(n));
  4689. }
  4690. wolfSSL_shutdown(ssl);
  4691. if (session) { wolfSSL_SESSION_free(session); }
  4692. session = wolfSSL_get1_session(ssl);
  4693. return res.find("200 OK") != std::string::npos;
  4694. };
  4695. ASSERT_TRUE(get(PORT));
  4696. EXPECT_FALSE(get(PORT + 1));
  4697. ASSERT_TRUE(get(PORT));
  4698. ASSERT_TRUE(replace_client_ca(svr));
  4699. EXPECT_FALSE(get(PORT));
  4700. }
  4701. #endif
  4702. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4704. ASSERT_TRUE(svr.is_valid());
  4705. svr.Get("/test", [](const Request &, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4709. auto se = detail::scope_exit([&] {
  4710. svr.stop();
  4711. t.join();
  4712. ASSERT_FALSE(svr.is_running());
  4713. });
  4714. svr.wait_until_ready();
  4715. // A connection that sends no ClientHello keeps its handshake in progress,
  4716. // once the server has had a moment to start it.
  4717. auto error = Error::Success;
  4718. auto sock = detail::create_client_socket(
  4719. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4720. /*connection_timeout_sec=*/5, 0,
  4721. /*read_timeout_sec=*/5, 0,
  4722. /*write_timeout_sec=*/5, 0, std::string(), error);
  4723. ASSERT_NE(INVALID_SOCKET, sock);
  4724. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4725. std::string cert_pem, key_pem;
  4726. read_file(SERVER_CERT_FILE, cert_pem);
  4727. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4728. auto update = std::async(std::launch::async, [&]() {
  4729. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4730. });
  4731. EXPECT_EQ(std::future_status::timeout,
  4732. update.wait_for(std::chrono::milliseconds(200)));
  4733. detail::close_socket(sock);
  4734. EXPECT_TRUE(update.get());
  4735. SSLClient cli(HOST, PORT);
  4736. cli.enable_server_certificate_verification(false);
  4737. auto res = cli.Get("/test");
  4738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4739. EXPECT_EQ(StatusCode::OK_200, res->status);
  4740. }
  4741. #endif
  4742. TEST(ErrorHandlerTest, ContentLength) {
  4743. Server svr;
  4744. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4745. res.status = StatusCode::OK_200;
  4746. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4747. "text/html"); // <= Content-Length still 13
  4748. });
  4749. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4750. res.set_content("Hello World!\n", "text/plain");
  4751. res.status = 524;
  4752. });
  4753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4754. auto se = detail::scope_exit([&] {
  4755. svr.stop();
  4756. thread.join();
  4757. ASSERT_FALSE(svr.is_running());
  4758. });
  4759. svr.wait_until_ready();
  4760. {
  4761. Client cli(HOST, PORT);
  4762. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4766. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4767. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4768. }
  4769. }
  4770. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4771. TEST(ExceptionTest, WithoutExceptionHandler) {
  4772. Server svr;
  4773. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4774. throw std::runtime_error("exception...");
  4775. });
  4776. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4777. throw std::runtime_error("exception\r\n...");
  4778. });
  4779. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4780. auto se = detail::scope_exit([&] {
  4781. svr.stop();
  4782. listen_thread.join();
  4783. ASSERT_FALSE(svr.is_running());
  4784. });
  4785. svr.wait_until_ready();
  4786. Client cli("localhost", PORT);
  4787. {
  4788. auto res = cli.Get("/exception");
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4791. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4792. }
  4793. {
  4794. auto res = cli.Get("/unknown");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4797. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4798. }
  4799. }
  4800. TEST(ExceptionTest, WithExceptionHandler) {
  4801. Server svr;
  4802. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4803. std::exception_ptr ep) {
  4804. EXPECT_FALSE(ep == nullptr);
  4805. try {
  4806. std::rethrow_exception(ep);
  4807. } catch (std::exception &e) {
  4808. EXPECT_EQ("abc", std::string(e.what()));
  4809. } catch (...) {}
  4810. res.status = StatusCode::InternalServerError_500;
  4811. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4812. "text/html"); // <= Content-Length still 13 at this point
  4813. });
  4814. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4815. res.set_content("Hello World!\n", "text/plain");
  4816. throw std::runtime_error("abc");
  4817. });
  4818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4819. auto se = detail::scope_exit([&] {
  4820. svr.stop();
  4821. thread.join();
  4822. ASSERT_FALSE(svr.is_running());
  4823. });
  4824. svr.wait_until_ready();
  4825. for (size_t i = 0; i < 10; i++) {
  4826. Client cli(HOST, PORT);
  4827. for (size_t j = 0; j < 100; j++) {
  4828. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4831. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4832. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4833. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4834. }
  4835. cli.set_keep_alive(true);
  4836. for (size_t j = 0; j < 100; j++) {
  4837. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4840. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4841. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4842. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4843. }
  4844. }
  4845. }
  4846. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4847. Server svr;
  4848. svr.set_exception_handler(
  4849. [](const Request &, Response &res, std::exception_ptr) {
  4850. res.set_content("oops", "text/plain");
  4851. });
  4852. svr.Get("/throw", [](const Request &, Response &) {
  4853. throw std::runtime_error("throw");
  4854. });
  4855. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4856. res.status = StatusCode::Created_201;
  4857. throw std::runtime_error("created-then-throw");
  4858. });
  4859. auto port = svr.bind_to_any_port(HOST);
  4860. ASSERT_GT(port, 0);
  4861. thread t = thread([&] { svr.listen_after_bind(); });
  4862. auto se = detail::scope_exit([&] {
  4863. svr.stop();
  4864. t.join();
  4865. ASSERT_FALSE(svr.is_running());
  4866. });
  4867. svr.wait_until_ready();
  4868. Client cli(HOST, port);
  4869. for (auto path : {"/throw", "/created-then-throw"}) {
  4870. auto res = cli.Get(path);
  4871. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4872. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4873. }
  4874. }
  4875. TEST(ExceptionTest, AndErrorHandler) {
  4876. Server svr;
  4877. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4878. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4879. });
  4880. svr.set_exception_handler(
  4881. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4882. EXPECT_FALSE(ep == nullptr);
  4883. try {
  4884. std::rethrow_exception(ep);
  4885. } catch (std::exception &e) {
  4886. res.set_content(e.what(), "text/html");
  4887. } catch (...) {}
  4888. res.status = StatusCode::InternalServerError_500;
  4889. });
  4890. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4891. throw std::runtime_error("EXCEPTION");
  4892. });
  4893. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4894. res.set_content("ERROR", "text/html");
  4895. res.status = StatusCode::InternalServerError_500;
  4896. });
  4897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4898. auto se = detail::scope_exit([&] {
  4899. svr.stop();
  4900. thread.join();
  4901. ASSERT_FALSE(svr.is_running());
  4902. });
  4903. svr.wait_until_ready();
  4904. Client cli(HOST, PORT);
  4905. {
  4906. auto res = cli.Get("/exception");
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("EXCEPTION", res->body);
  4910. }
  4911. {
  4912. auto res = cli.Get("/error");
  4913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4914. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4915. EXPECT_EQ("ERROR", res->body);
  4916. }
  4917. {
  4918. auto res = cli.Get("/invalid");
  4919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4921. EXPECT_EQ("NOT_FOUND", res->body);
  4922. }
  4923. }
  4924. #endif
  4925. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4926. // An exception from a user callback outside process_request()'s try/catch
  4927. // used to unwind into the task queue - which does not catch - and terminate
  4928. // the process. Each test below runs the server on a single worker thread: a
  4929. // guard that catches the exception but still loses the thread would otherwise
  4930. // be hidden by a spare worker serving the follow-up request. Note that a
  4931. // regression here aborts the whole test binary rather than failing one test.
  4932. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4933. Server svr;
  4934. svr.new_task_queue = [] { return new ThreadPool(1); };
  4935. std::atomic<int> reported{0};
  4936. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4937. if (err == Error::UserCallbackException) { reported++; }
  4938. });
  4939. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4940. res.set_content_provider(
  4941. 1024, "text/plain",
  4942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4943. sink.write("hello", 5);
  4944. throw std::runtime_error("from the content provider");
  4945. });
  4946. });
  4947. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4948. res.set_content("ok", "text/plain");
  4949. });
  4950. auto port = svr.bind_to_any_port(HOST);
  4951. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4952. auto se = detail::scope_exit([&] {
  4953. svr.stop();
  4954. listen_thread.join();
  4955. ASSERT_FALSE(svr.is_running());
  4956. });
  4957. svr.wait_until_ready();
  4958. {
  4959. Client cli(HOST, port);
  4960. cli.set_read_timeout(5, 0);
  4961. EXPECT_FALSE(cli.Get("/throw"));
  4962. }
  4963. EXPECT_TRUE(svr.is_running());
  4964. EXPECT_EQ(1, reported.load());
  4965. // A request on a fresh connection is still served.
  4966. {
  4967. Client cli(HOST, port);
  4968. auto res = cli.Get("/ok");
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. EXPECT_EQ(StatusCode::OK_200, res->status);
  4971. EXPECT_EQ("ok", res->body);
  4972. }
  4973. }
  4974. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4975. Server svr;
  4976. svr.new_task_queue = [] { return new ThreadPool(1); };
  4977. std::atomic<bool> should_throw{true};
  4978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4979. res.set_content("hi", "text/plain");
  4980. });
  4981. svr.set_post_routing_handler(
  4982. [&](const Request & /*req*/, Response & /*res*/) {
  4983. if (should_throw) {
  4984. throw std::runtime_error("from the post-routing handler");
  4985. }
  4986. });
  4987. auto port = svr.bind_to_any_port(HOST);
  4988. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4989. auto se = detail::scope_exit([&] {
  4990. svr.stop();
  4991. listen_thread.join();
  4992. ASSERT_FALSE(svr.is_running());
  4993. });
  4994. svr.wait_until_ready();
  4995. {
  4996. Client cli(HOST, port);
  4997. cli.set_read_timeout(5, 0);
  4998. EXPECT_FALSE(cli.Get("/hi"));
  4999. }
  5000. EXPECT_TRUE(svr.is_running());
  5001. should_throw = false;
  5002. {
  5003. Client cli(HOST, port);
  5004. auto res = cli.Get("/hi");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. EXPECT_EQ("hi", res->body);
  5008. }
  5009. }
  5010. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5011. // The guard reports the caught exception through the error logger, which is
  5012. // a user callback too. A logger that throws has to be contained as well, or
  5013. // the process would terminate from inside the catch.
  5014. Server svr;
  5015. svr.new_task_queue = [] { return new ThreadPool(1); };
  5016. std::atomic<int> reported{0};
  5017. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5018. if (err == Error::UserCallbackException) {
  5019. reported++;
  5020. throw std::runtime_error("from the error logger");
  5021. }
  5022. });
  5023. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5024. res.set_content_provider(
  5025. 1024, "text/plain",
  5026. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5027. sink.write("hello", 5);
  5028. throw std::runtime_error("from the content provider");
  5029. });
  5030. });
  5031. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5032. res.set_content("ok", "text/plain");
  5033. });
  5034. auto port = svr.bind_to_any_port(HOST);
  5035. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5036. auto se = detail::scope_exit([&] {
  5037. svr.stop();
  5038. listen_thread.join();
  5039. ASSERT_FALSE(svr.is_running());
  5040. });
  5041. svr.wait_until_ready();
  5042. {
  5043. Client cli(HOST, port);
  5044. cli.set_read_timeout(5, 0);
  5045. EXPECT_FALSE(cli.Get("/throw"));
  5046. }
  5047. EXPECT_TRUE(svr.is_running());
  5048. EXPECT_EQ(1, reported.load());
  5049. {
  5050. Client cli(HOST, port);
  5051. auto res = cli.Get("/ok");
  5052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5053. EXPECT_EQ(StatusCode::OK_200, res->status);
  5054. EXPECT_EQ("ok", res->body);
  5055. }
  5056. }
  5057. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5058. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5059. // so the exception unwinds through the ws::WebSocket object on its way to
  5060. // the guard. None of the HTTP cases above cross that.
  5061. Server svr;
  5062. svr.new_task_queue = [] { return new ThreadPool(1); };
  5063. std::atomic<int> reported{0};
  5064. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5065. if (err == Error::UserCallbackException) { reported++; }
  5066. });
  5067. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5068. throw std::runtime_error("from the WebSocket handler");
  5069. });
  5070. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5071. res.set_content("ok", "text/plain");
  5072. });
  5073. auto port = svr.bind_to_any_port(HOST);
  5074. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5075. auto se = detail::scope_exit([&] {
  5076. svr.stop();
  5077. listen_thread.join();
  5078. ASSERT_FALSE(svr.is_running());
  5079. });
  5080. svr.wait_until_ready();
  5081. {
  5082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5083. "/ws");
  5084. auto res = client.connect();
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. // The server dropped the connection instead of dying.
  5087. std::string msg;
  5088. EXPECT_FALSE(client.read(msg));
  5089. client.close();
  5090. }
  5091. EXPECT_TRUE(svr.is_running());
  5092. EXPECT_EQ(1, reported.load());
  5093. {
  5094. Client cli(HOST, port);
  5095. auto res = cli.Get("/ok");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ("ok", res->body);
  5099. }
  5100. }
  5101. #ifdef CPPHTTPLIB_SSL_ENABLED
  5102. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5103. // SSLServer::process_and_close_socket() is a separate overload with its own
  5104. // guard, so it is exercised on its own.
  5105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5106. ASSERT_TRUE(svr.is_valid());
  5107. svr.new_task_queue = [] { return new ThreadPool(1); };
  5108. std::atomic<int> reported{0};
  5109. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5110. if (err == Error::UserCallbackException) { reported++; }
  5111. });
  5112. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5113. res.set_content_provider(
  5114. 1024, "text/plain",
  5115. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5116. sink.write("hello", 5);
  5117. throw std::runtime_error("from the content provider");
  5118. });
  5119. });
  5120. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5121. res.set_content("ok", "text/plain");
  5122. });
  5123. auto port = svr.bind_to_any_port(HOST);
  5124. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5125. auto se = detail::scope_exit([&] {
  5126. svr.stop();
  5127. listen_thread.join();
  5128. ASSERT_FALSE(svr.is_running());
  5129. });
  5130. svr.wait_until_ready();
  5131. {
  5132. SSLClient cli(HOST, port);
  5133. cli.enable_server_certificate_verification(false);
  5134. cli.set_read_timeout(5, 0);
  5135. EXPECT_FALSE(cli.Get("/throw"));
  5136. }
  5137. EXPECT_TRUE(svr.is_running());
  5138. EXPECT_EQ(1, reported.load());
  5139. {
  5140. SSLClient cli(HOST, port);
  5141. cli.enable_server_certificate_verification(false);
  5142. auto res = cli.Get("/ok");
  5143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("ok", res->body);
  5146. }
  5147. }
  5148. #endif
  5149. #endif
  5150. TEST(NoContentTest, ContentLength) {
  5151. Server svr;
  5152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5153. res.status = StatusCode::NoContent_204;
  5154. });
  5155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5156. auto se = detail::scope_exit([&] {
  5157. svr.stop();
  5158. thread.join();
  5159. ASSERT_FALSE(svr.is_running());
  5160. });
  5161. svr.wait_until_ready();
  5162. {
  5163. Client cli(HOST, PORT);
  5164. auto res = cli.Get("/hi");
  5165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5166. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5167. // RFC 9110 8.6: none in a 204 response
  5168. EXPECT_FALSE(res->has_header("Content-Length"));
  5169. }
  5170. }
  5171. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5172. Server svr;
  5173. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5174. res.set_header("Content-Length", "5");
  5175. res.set_content("hello world", "text/plain");
  5176. });
  5177. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5178. // A body that reads as the last chunk, were it taken as chunked
  5179. res.set_header("Transfer-Encoding", "chunked");
  5180. res.set_content("0\r\n\r\n", "text/plain");
  5181. });
  5182. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5183. res.set_header("Content-Length", "2");
  5184. res.set_content_provider(5, "text/plain",
  5185. [](size_t offset, size_t length, DataSink &sink) {
  5186. sink.write(&"hello"[offset], length);
  5187. return true;
  5188. });
  5189. });
  5190. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5191. res.set_header("Content-Length", "1234");
  5192. });
  5193. thread t = thread([&] { svr.listen(HOST, PORT); });
  5194. auto se = detail::scope_exit([&] {
  5195. svr.stop();
  5196. t.join();
  5197. ASSERT_FALSE(svr.is_running());
  5198. });
  5199. svr.wait_until_ready();
  5200. Client cli(HOST, PORT);
  5201. cli.set_read_timeout(1, 0);
  5202. auto expect_body = [&](const Result &res, const std::string &body) {
  5203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5204. EXPECT_EQ(body, res->body);
  5205. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5206. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5207. };
  5208. Headers identity{{"Accept-Encoding", ""}};
  5209. expect_body(cli.Get("/body", identity), "hello world");
  5210. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5211. expect_body(cli.Get("/body",
  5212. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5213. "he");
  5214. expect_body(cli.Get("/provider", identity), "hello");
  5215. expect_body(cli.Get("/empty", identity), "");
  5216. // A HEAD response may give the length of the body a GET would get.
  5217. auto res = cli.Head("/empty");
  5218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5219. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5220. }
  5221. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5222. Server svr;
  5223. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5224. res.set_content("short", "text/plain");
  5225. });
  5226. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5227. res.body += " with a footer";
  5228. res.set_header("Transfer-Encoding", "chunked");
  5229. });
  5230. thread t = thread([&] { svr.listen(HOST, PORT); });
  5231. auto se = detail::scope_exit([&] {
  5232. svr.stop();
  5233. t.join();
  5234. ASSERT_FALSE(svr.is_running());
  5235. });
  5236. svr.wait_until_ready();
  5237. Client cli(HOST, PORT);
  5238. cli.set_read_timeout(1, 0);
  5239. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. EXPECT_EQ("short with a footer", res->body);
  5242. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5243. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5244. }
  5245. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5246. Server svr;
  5247. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5248. res.set_header("Content-Length", "3");
  5249. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5250. sink.write("abc", 3);
  5251. sink.done();
  5252. return true;
  5253. });
  5254. });
  5255. thread t = thread([&] { svr.listen(HOST, PORT); });
  5256. auto se = detail::scope_exit([&] {
  5257. svr.stop();
  5258. t.join();
  5259. ASSERT_FALSE(svr.is_running());
  5260. });
  5261. svr.wait_until_ready();
  5262. Client cli(HOST, PORT);
  5263. cli.set_keep_alive(true);
  5264. auto res = cli.Get("/");
  5265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5266. EXPECT_EQ("abc", res->body);
  5267. EXPECT_FALSE(res->has_header("Content-Length"));
  5268. EXPECT_EQ("close", res->get_header_value("Connection"));
  5269. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5270. // No body to delimit
  5271. auto head = cli.Head("/");
  5272. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5273. EXPECT_FALSE(head->has_header("Connection"));
  5274. }
  5275. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5276. #ifdef CPPHTTPLIB_SSL_ENABLED
  5277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5278. ASSERT_TRUE(svr.is_valid());
  5279. #else
  5280. Server svr;
  5281. #endif
  5282. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5283. if (req.path == "/routing_handler") {
  5284. res.set_header("PRE_ROUTING", "on");
  5285. res.set_content("Routing Handler", "text/plain");
  5286. return httplib::Server::HandlerResponse::Handled;
  5287. }
  5288. return httplib::Server::HandlerResponse::Unhandled;
  5289. });
  5290. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5291. res.set_content("Error", "text/html");
  5292. });
  5293. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5294. if (req.path == "/routing_handler") {
  5295. res.set_header("POST_ROUTING", "on");
  5296. }
  5297. });
  5298. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5299. res.set_content("Hello World!\n", "text/plain");
  5300. });
  5301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5302. auto se = detail::scope_exit([&] {
  5303. svr.stop();
  5304. thread.join();
  5305. ASSERT_FALSE(svr.is_running());
  5306. });
  5307. svr.wait_until_ready();
  5308. {
  5309. #ifdef CPPHTTPLIB_SSL_ENABLED
  5310. SSLClient cli(HOST, PORT);
  5311. cli.enable_server_certificate_verification(false);
  5312. #else
  5313. Client cli(HOST, PORT);
  5314. #endif
  5315. auto res = cli.Get("/routing_handler");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("Routing Handler", res->body);
  5319. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5320. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5321. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5322. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5323. }
  5324. {
  5325. #ifdef CPPHTTPLIB_SSL_ENABLED
  5326. SSLClient cli(HOST, PORT);
  5327. cli.enable_server_certificate_verification(false);
  5328. #else
  5329. Client cli(HOST, PORT);
  5330. #endif
  5331. auto res = cli.Get("/hi");
  5332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. EXPECT_EQ("Hello World!\n", res->body);
  5335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5337. }
  5338. {
  5339. #ifdef CPPHTTPLIB_SSL_ENABLED
  5340. SSLClient cli(HOST, PORT);
  5341. cli.enable_server_certificate_verification(false);
  5342. #else
  5343. Client cli(HOST, PORT);
  5344. #endif
  5345. auto res = cli.Get("/aaa");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5348. EXPECT_EQ("Error", res->body);
  5349. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5350. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5351. }
  5352. }
  5353. TEST(RequestHandlerTest, PreRequestHandler) {
  5354. auto route_path = "/user/:user";
  5355. Server svr;
  5356. svr.Get("/hi", [](const Request &, Response &res) {
  5357. res.set_content("hi", "text/plain");
  5358. });
  5359. svr.Get(route_path, [](const Request &req, Response &res) {
  5360. res.set_content(req.path_params.at("user"), "text/plain");
  5361. });
  5362. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5363. if (req.matched_route == route_path) {
  5364. auto user = req.path_params.at("user");
  5365. if (user != "john") {
  5366. res.status = StatusCode::Forbidden_403;
  5367. res.set_content("error", "text/html");
  5368. return Server::HandlerResponse::Handled;
  5369. }
  5370. }
  5371. return Server::HandlerResponse::Unhandled;
  5372. });
  5373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5374. auto se = detail::scope_exit([&] {
  5375. svr.stop();
  5376. thread.join();
  5377. ASSERT_FALSE(svr.is_running());
  5378. });
  5379. svr.wait_until_ready();
  5380. Client cli(HOST, PORT);
  5381. {
  5382. auto res = cli.Get("/hi");
  5383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. EXPECT_EQ("hi", res->body);
  5386. }
  5387. {
  5388. auto res = cli.Get("/user/john");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ("john", res->body);
  5392. }
  5393. {
  5394. auto res = cli.Get("/user/invalid-user");
  5395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5396. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5397. EXPECT_EQ("error", res->body);
  5398. }
  5399. }
  5400. // The pre-request handler must run before the request body is read, so a
  5401. // rejected request never forces the server to buffer a (potentially large)
  5402. // body. Here the posted body is larger than the payload limit: if the body
  5403. // were read first the server would answer 413, but because the pre-request
  5404. // handler runs first it answers 403 and the body is never read.
  5405. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5406. Server svr;
  5407. svr.set_payload_max_length(8);
  5408. auto handler_ran = false;
  5409. svr.Post("/reject", [&](const Request &req, Response &res) {
  5410. handler_ran = true;
  5411. res.set_content(req.body, "text/plain");
  5412. });
  5413. svr.Post("/accept", [](const Request &req, Response &res) {
  5414. res.set_content(req.body, "text/plain");
  5415. });
  5416. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5417. if (req.matched_route == "/reject") {
  5418. res.status = StatusCode::Forbidden_403;
  5419. res.set_content("denied", "text/plain");
  5420. return Server::HandlerResponse::Handled;
  5421. }
  5422. return Server::HandlerResponse::Unhandled;
  5423. });
  5424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5425. auto se = detail::scope_exit([&] {
  5426. svr.stop();
  5427. thread.join();
  5428. ASSERT_FALSE(svr.is_running());
  5429. });
  5430. svr.wait_until_ready();
  5431. Client cli(HOST, PORT);
  5432. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5433. // rejects with 403 before the body is read, so 413 is never reached.
  5434. {
  5435. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5437. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5438. EXPECT_EQ("denied", res->body);
  5439. EXPECT_FALSE(handler_ran);
  5440. }
  5441. // An approved route still reads the body and enforces the payload limit.
  5442. {
  5443. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5446. }
  5447. }
  5448. TEST(UserDataTest, BasicOperations) {
  5449. httplib::UserData ud;
  5450. // Initially empty
  5451. EXPECT_FALSE(ud.has("key"));
  5452. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5453. // set and get
  5454. ud.set("key", 42);
  5455. EXPECT_TRUE(ud.has("key"));
  5456. auto *p = ud.get<int>("key");
  5457. ASSERT_NE(nullptr, p);
  5458. EXPECT_EQ(42, *p);
  5459. // Type mismatch → nullptr
  5460. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5461. // Overwrite with different type
  5462. ud.set("key", std::string("hello"));
  5463. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5464. auto *s = ud.get<std::string>("key");
  5465. ASSERT_NE(nullptr, s);
  5466. EXPECT_EQ("hello", *s);
  5467. // erase
  5468. ud.erase("key");
  5469. EXPECT_FALSE(ud.has("key"));
  5470. // clear
  5471. ud.set("a", 1);
  5472. ud.set("b", 2);
  5473. ud.clear();
  5474. EXPECT_FALSE(ud.has("a"));
  5475. EXPECT_FALSE(ud.has("b"));
  5476. }
  5477. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5478. struct AuthCtx {
  5479. std::string user_id;
  5480. };
  5481. Server svr;
  5482. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5483. res.user_data.set("auth", AuthCtx{"alice"});
  5484. return Server::HandlerResponse::Unhandled;
  5485. });
  5486. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5487. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5488. ASSERT_NE(nullptr, ctx);
  5489. res.set_content("Hello " + ctx->user_id, "text/plain");
  5490. });
  5491. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5492. auto se = detail::scope_exit([&] {
  5493. svr.stop();
  5494. thread.join();
  5495. ASSERT_FALSE(svr.is_running());
  5496. });
  5497. svr.wait_until_ready();
  5498. Client cli(HOST, PORT);
  5499. auto res = cli.Get("/me");
  5500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. EXPECT_EQ("Hello alice", res->body);
  5503. }
  5504. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5505. struct RoleCtx {
  5506. std::string role;
  5507. };
  5508. Server svr;
  5509. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5510. res.user_data.set("role", RoleCtx{"admin"});
  5511. return Server::HandlerResponse::Unhandled;
  5512. });
  5513. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5514. auto *ctx = res.user_data.get<RoleCtx>("role");
  5515. ASSERT_NE(nullptr, ctx);
  5516. res.set_content(ctx->role, "text/plain");
  5517. });
  5518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5519. auto se = detail::scope_exit([&] {
  5520. svr.stop();
  5521. thread.join();
  5522. ASSERT_FALSE(svr.is_running());
  5523. });
  5524. svr.wait_until_ready();
  5525. Client cli(HOST, PORT);
  5526. auto res = cli.Get("/role");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::OK_200, res->status);
  5529. EXPECT_EQ("admin", res->body);
  5530. }
  5531. TEST(InvalidFormatTest, StatusCode) {
  5532. Server svr;
  5533. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5534. res.set_content("Hello World!\n", "text/plain");
  5535. res.status = 9999; // Status should be a three-digit code...
  5536. });
  5537. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5538. auto se = detail::scope_exit([&] {
  5539. svr.stop();
  5540. thread.join();
  5541. ASSERT_FALSE(svr.is_running());
  5542. });
  5543. svr.wait_until_ready();
  5544. {
  5545. Client cli(HOST, PORT);
  5546. auto res = cli.Get("/hi");
  5547. ASSERT_FALSE(res);
  5548. }
  5549. }
  5550. TEST(URLFragmentTest, WithFragment) {
  5551. Server svr;
  5552. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5553. EXPECT_TRUE(req.target == "/hi");
  5554. });
  5555. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5556. auto se = detail::scope_exit([&] {
  5557. svr.stop();
  5558. thread.join();
  5559. ASSERT_FALSE(svr.is_running());
  5560. });
  5561. svr.wait_until_ready();
  5562. {
  5563. Client cli(HOST, PORT);
  5564. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5565. EXPECT_TRUE(res);
  5566. EXPECT_EQ(StatusCode::OK_200, res->status);
  5567. res = cli.Get("/hi%23key1=val1=key2=val2");
  5568. EXPECT_TRUE(res);
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. }
  5571. }
  5572. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5573. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5574. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5575. Server svr;
  5576. std::vector<std::string> targets;
  5577. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5578. targets.push_back(req.target);
  5579. });
  5580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5581. auto se = detail::scope_exit([&] {
  5582. svr.stop();
  5583. thread.join();
  5584. ASSERT_FALSE(svr.is_running());
  5585. });
  5586. svr.wait_until_ready();
  5587. Client cli(HOST, PORT);
  5588. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5589. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5590. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5591. // A '?' after the '#' belongs to the fragment, not to the query.
  5592. Request req;
  5593. req.method = "GET";
  5594. req.path = "/hi#f?x=1";
  5595. req.params.emplace("a", "1");
  5596. Response res;
  5597. auto error = Error::Success;
  5598. EXPECT_TRUE(cli.send(req, res, error));
  5599. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5600. "/hi?a=1"}),
  5601. targets);
  5602. }
  5603. TEST(HeaderWriter, SetHeaderWriter) {
  5604. Server svr;
  5605. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5606. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5607. return detail::write_headers(strm, hdrs);
  5608. });
  5609. svr.Get("/hi", [](const Request &req, Response &res) {
  5610. auto it = req.headers.find("CustomClientHeader");
  5611. EXPECT_TRUE(it != req.headers.end());
  5612. EXPECT_EQ(it->second, "CustomClientValue");
  5613. res.set_content("Hello World!\n", "text/plain");
  5614. });
  5615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5616. auto se = detail::scope_exit([&] {
  5617. svr.stop();
  5618. thread.join();
  5619. ASSERT_FALSE(svr.is_running());
  5620. });
  5621. svr.wait_until_ready();
  5622. {
  5623. Client cli(HOST, PORT);
  5624. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5625. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5626. return detail::write_headers(strm, hdrs);
  5627. });
  5628. auto res = cli.Get("/hi");
  5629. EXPECT_TRUE(res);
  5630. EXPECT_EQ(StatusCode::OK_200, res->status);
  5631. auto it = res->headers.find("CustomServerHeader");
  5632. EXPECT_TRUE(it != res->headers.end());
  5633. EXPECT_EQ(it->second, "CustomServerValue");
  5634. }
  5635. }
  5636. class ServerTest : public ::testing::Test {
  5637. protected:
  5638. ServerTest()
  5639. : cli_(HOST, PORT)
  5640. #ifdef CPPHTTPLIB_SSL_ENABLED
  5641. ,
  5642. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5643. #endif
  5644. {
  5645. #ifdef CPPHTTPLIB_SSL_ENABLED
  5646. cli_.enable_server_certificate_verification(false);
  5647. #endif
  5648. // Allow LARGE_DATA (100MB) responses
  5649. cli_.set_payload_max_length(200 * 1024 * 1024);
  5650. }
  5651. virtual void SetUp() {
  5652. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5653. svr_.set_payload_max_length(200 * 1024 * 1024);
  5654. svr_.set_mount_point("/", "./www");
  5655. svr_.set_mount_point("/mount", "./www2");
  5656. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5657. svr_.Get("/hi",
  5658. [&](const Request & /*req*/, Response &res) {
  5659. res.set_content("Hello World!", "text/plain");
  5660. })
  5661. .Get("/file_content",
  5662. [&](const Request & /*req*/, Response &res) {
  5663. res.set_file_content("./www/dir/test.html");
  5664. })
  5665. .Get("/file_content_with_content_type",
  5666. [&](const Request & /*req*/, Response &res) {
  5667. res.set_file_content("./www/file", "text/plain");
  5668. })
  5669. .Get("/invalid_file_content",
  5670. [&](const Request & /*req*/, Response &res) {
  5671. res.set_file_content("./www/dir/invalid_file_path");
  5672. })
  5673. .Get("/http_response_splitting",
  5674. [&](const Request & /*req*/, Response &res) {
  5675. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5676. EXPECT_EQ(0U, res.headers.size());
  5677. EXPECT_FALSE(res.has_header("a"));
  5678. res.set_header("a", "1\nSet-Cookie: a=1");
  5679. EXPECT_EQ(0U, res.headers.size());
  5680. EXPECT_FALSE(res.has_header("a"));
  5681. res.set_header("a", "1\rSet-Cookie: a=1");
  5682. EXPECT_EQ(0U, res.headers.size());
  5683. EXPECT_FALSE(res.has_header("a"));
  5684. res.set_header("a\r\nb", "0");
  5685. EXPECT_EQ(0U, res.headers.size());
  5686. EXPECT_FALSE(res.has_header("a"));
  5687. res.set_header("a\rb", "0");
  5688. EXPECT_EQ(0U, res.headers.size());
  5689. EXPECT_FALSE(res.has_header("a"));
  5690. res.set_header("a\nb", "0");
  5691. EXPECT_EQ(0U, res.headers.size());
  5692. EXPECT_FALSE(res.has_header("a"));
  5693. res.set_redirect("1\r\nSet-Cookie: a=1");
  5694. EXPECT_EQ(0U, res.headers.size());
  5695. EXPECT_FALSE(res.has_header("Location"));
  5696. })
  5697. .Get("/slow",
  5698. [&](const Request & /*req*/, Response &res) {
  5699. std::this_thread::sleep_for(std::chrono::seconds(4));
  5700. res.set_content("slow", "text/plain");
  5701. })
  5702. #if 0
  5703. .Post("/slowpost",
  5704. [&](const Request & /*req*/, Response &res) {
  5705. std::this_thread::sleep_for(std::chrono::seconds(2));
  5706. res.set_content("slow", "text/plain");
  5707. })
  5708. #endif
  5709. .Get("/remote_addr",
  5710. [&](const Request &req, Response &res) {
  5711. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5712. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5713. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5714. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5715. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5716. #endif
  5717. res.set_content(req.remote_addr, "text/plain");
  5718. })
  5719. .Get("/local_addr",
  5720. [&](const Request &req, Response &res) {
  5721. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5722. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5723. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5724. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5725. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5726. #endif
  5727. auto local_addr = req.local_addr;
  5728. auto local_port = std::to_string(req.local_port);
  5729. res.set_content(local_addr.append(":").append(local_port),
  5730. "text/plain");
  5731. })
  5732. .Get("/endwith%",
  5733. [&](const Request & /*req*/, Response &res) {
  5734. res.set_content("Hello World!", "text/plain");
  5735. })
  5736. .Get("/a\\+\\+b",
  5737. [&](const Request &req, Response &res) {
  5738. ASSERT_TRUE(req.has_param("a +b"));
  5739. auto val = req.get_param_value("a +b");
  5740. res.set_content(val, "text/plain");
  5741. })
  5742. .Get("/", [&](const Request & /*req*/,
  5743. Response &res) { res.set_redirect("/hi"); })
  5744. .Post("/1",
  5745. [](const Request & /*req*/, Response &res) {
  5746. res.set_redirect("/2", StatusCode::SeeOther_303);
  5747. })
  5748. .Get("/2",
  5749. [](const Request & /*req*/, Response &res) {
  5750. res.set_content("redirected.", "text/plain");
  5751. res.status = StatusCode::OK_200;
  5752. })
  5753. .Post("/person",
  5754. [&](const Request &req, Response &res) {
  5755. if (req.has_param("name") && req.has_param("note")) {
  5756. persons_[req.get_param_value("name")] =
  5757. req.get_param_value("note");
  5758. } else {
  5759. res.status = StatusCode::BadRequest_400;
  5760. }
  5761. })
  5762. .Put("/person",
  5763. [&](const Request &req, Response &res) {
  5764. if (req.has_param("name") && req.has_param("note")) {
  5765. persons_[req.get_param_value("name")] =
  5766. req.get_param_value("note");
  5767. } else {
  5768. res.status = StatusCode::BadRequest_400;
  5769. }
  5770. })
  5771. .Get("/person/(.*)",
  5772. [&](const Request &req, Response &res) {
  5773. string name = req.matches[1];
  5774. if (persons_.find(name) != persons_.end()) {
  5775. auto note = persons_[name];
  5776. res.set_content(note, "text/plain");
  5777. } else {
  5778. res.status = StatusCode::NotFound_404;
  5779. }
  5780. })
  5781. .Delete("/person",
  5782. [&](const Request &req, Response &res) {
  5783. if (req.has_param("name")) {
  5784. string name = req.get_param_value("name");
  5785. if (persons_.find(name) != persons_.end()) {
  5786. persons_.erase(name);
  5787. res.set_content("DELETED", "text/plain");
  5788. } else {
  5789. res.status = StatusCode::NotFound_404;
  5790. }
  5791. } else {
  5792. res.status = StatusCode::BadRequest_400;
  5793. }
  5794. })
  5795. .Post("/x-www-form-urlencoded-json",
  5796. [&](const Request &req, Response &res) {
  5797. auto json = req.get_param_value("json");
  5798. ASSERT_EQ(JSON_DATA, json);
  5799. res.set_content(json, "appliation/json");
  5800. res.status = StatusCode::OK_200;
  5801. })
  5802. .Get("/streamed-chunked",
  5803. [&](const Request & /*req*/, Response &res) {
  5804. res.set_chunked_content_provider(
  5805. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5806. sink.os << "123";
  5807. sink.os << "456";
  5808. sink.os << "789";
  5809. sink.done();
  5810. return true;
  5811. });
  5812. })
  5813. .Get("/streamed-chunked-with-prohibited-trailer",
  5814. [&](const Request & /*req*/, Response &res) {
  5815. auto i = new int(0);
  5816. // Declare both a prohibited trailer (Content-Length) and an
  5817. // allowed one
  5818. res.set_header("Trailer", "Content-Length, X-Allowed");
  5819. res.set_chunked_content_provider(
  5820. "text/plain",
  5821. [i](size_t /*offset*/, DataSink &sink) {
  5822. switch (*i) {
  5823. case 0: sink.os << "123"; break;
  5824. case 1: sink.os << "456"; break;
  5825. case 2: sink.os << "789"; break;
  5826. case 3: {
  5827. sink.done_with_trailer(
  5828. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5829. } break;
  5830. }
  5831. (*i)++;
  5832. return true;
  5833. },
  5834. [i](bool success) {
  5835. EXPECT_TRUE(success);
  5836. delete i;
  5837. });
  5838. })
  5839. .Get("/streamed-chunked2",
  5840. [&](const Request & /*req*/, Response &res) {
  5841. auto i = new int(0);
  5842. res.set_chunked_content_provider(
  5843. "text/plain",
  5844. [i](size_t /*offset*/, DataSink &sink) {
  5845. switch (*i) {
  5846. case 0: sink.os << "123"; break;
  5847. case 1: sink.os << "456"; break;
  5848. case 2: sink.os << "789"; break;
  5849. case 3: sink.done(); break;
  5850. }
  5851. (*i)++;
  5852. return true;
  5853. },
  5854. [i](bool success) {
  5855. EXPECT_TRUE(success);
  5856. delete i;
  5857. });
  5858. })
  5859. .Get("/streamed-chunked-with-trailer",
  5860. [&](const Request & /*req*/, Response &res) {
  5861. auto i = new int(0);
  5862. res.set_header("Trailer", "Dummy1, Dummy2");
  5863. res.set_chunked_content_provider(
  5864. "text/plain",
  5865. [i](size_t /*offset*/, DataSink &sink) {
  5866. switch (*i) {
  5867. case 0: sink.os << "123"; break;
  5868. case 1: sink.os << "456"; break;
  5869. case 2: sink.os << "789"; break;
  5870. case 3: {
  5871. sink.done_with_trailer(
  5872. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5873. } break;
  5874. }
  5875. (*i)++;
  5876. return true;
  5877. },
  5878. [i](bool success) {
  5879. EXPECT_TRUE(success);
  5880. delete i;
  5881. });
  5882. })
  5883. .Get("/streamed",
  5884. [&](const Request & /*req*/, Response &res) {
  5885. res.set_content_provider(
  5886. 6, "text/plain",
  5887. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5888. sink.os << (offset < 3 ? "a" : "b");
  5889. return true;
  5890. });
  5891. })
  5892. .Get("/streamed-without-length",
  5893. [&](const Request & /*req*/, Response &res) {
  5894. auto data = new std::string("abcdefg");
  5895. res.set_content_provider(
  5896. "text/plain",
  5897. [data](size_t offset, DataSink &sink) {
  5898. if (offset < data->size()) {
  5899. sink.os << data->substr(offset);
  5900. }
  5901. sink.done();
  5902. return true;
  5903. },
  5904. [data](bool success) {
  5905. EXPECT_TRUE(success);
  5906. delete data;
  5907. });
  5908. })
  5909. .Get("/streamed-with-range",
  5910. [&](const Request &req, Response &res) {
  5911. auto data = new std::string("abcdefg");
  5912. // An explicit status keeps the server from picking the 206 it
  5913. // would otherwise choose for a ranged request, so the response
  5914. // is not a partial representation.
  5915. auto status = req.get_param_value("status");
  5916. if (status == "200") {
  5917. res.status = StatusCode::OK_200;
  5918. } else if (status == "403") {
  5919. res.status = StatusCode::Forbidden_403;
  5920. }
  5921. res.set_content_provider(
  5922. data->size(), "text/plain",
  5923. [data](size_t offset, size_t length, DataSink &sink) {
  5924. size_t DATA_CHUNK_SIZE = 4;
  5925. const auto &d = *data;
  5926. auto out_len =
  5927. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5928. auto ret =
  5929. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5930. EXPECT_TRUE(ret);
  5931. return true;
  5932. },
  5933. [data, &req](bool success) {
  5934. EXPECT_EQ(success, !req.has_param("error"));
  5935. delete data;
  5936. });
  5937. })
  5938. .Get("/streamed-cancel",
  5939. [&](const Request & /*req*/, Response &res) {
  5940. res.set_content_provider(
  5941. size_t(-1), "text/plain",
  5942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5943. sink.os << "data_chunk";
  5944. return true;
  5945. });
  5946. })
  5947. .Get("/regex-with-delimiter",
  5948. [&](const Request &req, Response & /*res*/) {
  5949. ASSERT_TRUE(req.has_param("key"));
  5950. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5951. })
  5952. .Get("/with-range",
  5953. [&](const Request & /*req*/, Response &res) {
  5954. res.set_content("abcdefg", "text/plain");
  5955. })
  5956. .Get("/test-start-time",
  5957. [&](const Request &req, Response & /*res*/) {
  5958. EXPECT_NE(req.start_time_,
  5959. std::chrono::steady_clock::time_point::min());
  5960. })
  5961. .Get("/with-range-customized-response",
  5962. [&](const Request & /*req*/, Response &res) {
  5963. res.status = StatusCode::BadRequest_400;
  5964. res.set_content(JSON_DATA, "application/json");
  5965. })
  5966. .Post("/chunked",
  5967. [&](const Request &req, Response & /*res*/) {
  5968. EXPECT_EQ(req.body, "dechunked post body");
  5969. })
  5970. .Post("/large-chunked",
  5971. [&](const Request &req, Response & /*res*/) {
  5972. std::string expected(6 * 30 * 1024u, 'a');
  5973. EXPECT_EQ(req.body, expected);
  5974. })
  5975. .Post("/multipart",
  5976. [&](const Request &req, Response & /*res*/) {
  5977. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5978. req.form.get_field_count("text2") +
  5979. req.form.get_field_count("file3") +
  5980. req.form.get_field_count("file4"));
  5981. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5982. req.form.get_file_count("file2"));
  5983. ASSERT_TRUE(!req.form.has_file("???"));
  5984. ASSERT_TRUE(!req.form.has_field("???"));
  5985. ASSERT_TRUE(req.body.empty());
  5986. {
  5987. const auto &text = req.form.get_field("text1");
  5988. EXPECT_EQ("text default", text);
  5989. }
  5990. {
  5991. const auto &text = req.form.get_field("text2");
  5992. EXPECT_EQ("aωb", text);
  5993. }
  5994. {
  5995. const auto &file = req.form.get_file("file1");
  5996. EXPECT_EQ("hello.txt", file.filename);
  5997. EXPECT_EQ("text/plain", file.content_type);
  5998. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5999. }
  6000. {
  6001. const auto &file = req.form.get_file("file2");
  6002. EXPECT_EQ("world.json", file.filename);
  6003. EXPECT_EQ("application/json", file.content_type);
  6004. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6005. }
  6006. {
  6007. const auto &text = req.form.get_field("file3");
  6008. EXPECT_EQ(0u, text.size());
  6009. }
  6010. {
  6011. const auto &text = req.form.get_field("file4");
  6012. EXPECT_EQ(0u, text.size());
  6013. }
  6014. })
  6015. .Post("/multipart/multi_file_values",
  6016. [&](const Request &req, Response & /*res*/) {
  6017. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6018. req.form.get_field_count("multi_text1"));
  6019. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6020. ASSERT_TRUE(!req.form.has_file("???"));
  6021. ASSERT_TRUE(!req.form.has_field("???"));
  6022. ASSERT_TRUE(req.body.empty());
  6023. {
  6024. const auto &text = req.form.get_field("text");
  6025. EXPECT_EQ("default text", text);
  6026. }
  6027. {
  6028. const auto &text1_values = req.form.get_fields("multi_text1");
  6029. EXPECT_EQ(2u, text1_values.size());
  6030. EXPECT_EQ("aaaaa", text1_values[0]);
  6031. EXPECT_EQ("bbbbb", text1_values[1]);
  6032. }
  6033. {
  6034. const auto &file1_values = req.form.get_files("multi_file1");
  6035. EXPECT_EQ(2u, file1_values.size());
  6036. auto file1 = file1_values[0];
  6037. EXPECT_EQ(file1.filename, "hello.txt");
  6038. EXPECT_EQ(file1.content_type, "text/plain");
  6039. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6040. auto file2 = file1_values[1];
  6041. EXPECT_EQ(file2.filename, "world.json");
  6042. EXPECT_EQ(file2.content_type, "application/json");
  6043. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6044. }
  6045. })
  6046. .Post("/empty",
  6047. [&](const Request &req, Response &res) {
  6048. EXPECT_EQ(req.body, "");
  6049. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6050. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6051. res.set_content("empty", "text/plain");
  6052. })
  6053. .Post("/empty-no-content-type",
  6054. [&](const Request &req, Response &res) {
  6055. EXPECT_EQ(req.body, "");
  6056. EXPECT_FALSE(req.has_header("Content-Type"));
  6057. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6058. res.set_content("empty-no-content-type", "text/plain");
  6059. })
  6060. .Post("/path-only",
  6061. [&](const Request &req, Response &res) {
  6062. EXPECT_EQ(req.body, "");
  6063. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6064. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6065. res.set_content("path-only", "text/plain");
  6066. })
  6067. .Post("/path-headers-only",
  6068. [&](const Request &req, Response &res) {
  6069. EXPECT_EQ(req.body, "");
  6070. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6071. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6072. EXPECT_EQ("world", req.get_header_value("hello"));
  6073. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6074. res.set_content("path-headers-only", "text/plain");
  6075. })
  6076. .Post("/post-large",
  6077. [&](const Request &req, Response &res) {
  6078. EXPECT_EQ(req.body, LARGE_DATA);
  6079. res.set_content(req.body, "text/plain");
  6080. })
  6081. .Post("/post-loopback",
  6082. [&](const Request &, Response &res,
  6083. ContentReader const &content_reader) {
  6084. std::string body;
  6085. content_reader([&](const char *data, size_t data_length) {
  6086. body.append(data, data_length);
  6087. return true;
  6088. });
  6089. res.set_content(body, "text/plain");
  6090. })
  6091. .Put("/put-loopback",
  6092. [&](const Request &, Response &res,
  6093. ContentReader const &content_reader) {
  6094. std::string body;
  6095. content_reader([&](const char *data, size_t data_length) {
  6096. body.append(data, data_length);
  6097. return true;
  6098. });
  6099. res.set_content(body, "text/plain");
  6100. })
  6101. .Patch("/patch-loopback",
  6102. [&](const Request &, Response &res,
  6103. ContentReader const &content_reader) {
  6104. std::string body;
  6105. content_reader([&](const char *data, size_t data_length) {
  6106. body.append(data, data_length);
  6107. return true;
  6108. });
  6109. res.set_content(body, "text/plain");
  6110. })
  6111. .Put("/empty-no-content-type",
  6112. [&](const Request &req, Response &res) {
  6113. EXPECT_EQ(req.body, "");
  6114. EXPECT_FALSE(req.has_header("Content-Type"));
  6115. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6116. res.set_content("empty-no-content-type", "text/plain");
  6117. })
  6118. .Put("/put",
  6119. [&](const Request &req, Response &res) {
  6120. EXPECT_EQ(req.body, "PUT");
  6121. res.set_content(req.body, "text/plain");
  6122. })
  6123. .Put("/put-large",
  6124. [&](const Request &req, Response &res) {
  6125. EXPECT_EQ(req.body, LARGE_DATA);
  6126. res.set_content(req.body, "text/plain");
  6127. })
  6128. .Patch("/patch",
  6129. [&](const Request &req, Response &res) {
  6130. EXPECT_EQ(req.body, "PATCH");
  6131. res.set_content(req.body, "text/plain");
  6132. })
  6133. .Delete("/delete",
  6134. [&](const Request & /*req*/, Response &res) {
  6135. res.set_content("DELETE", "text/plain");
  6136. })
  6137. .Delete("/delete-body",
  6138. [&](const Request &req, Response &res) {
  6139. EXPECT_EQ(req.body, "content");
  6140. res.set_content(req.body, "text/plain");
  6141. })
  6142. .Options(R"(\*)",
  6143. [&](const Request & /*req*/, Response &res) {
  6144. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6145. })
  6146. .CustomRoute("PROPFIND", "/dav/:id",
  6147. [&](const Request &req, Response &res) {
  6148. res.set_header("x-body-size",
  6149. std::to_string(req.body.size()));
  6150. res.set_header("x-matched-route", req.matched_route);
  6151. res.set_header("x-dav-id", req.path_params.at("id"));
  6152. res.status = StatusCode::MultiStatus_207;
  6153. res.set_content(req.body, "application/xml");
  6154. })
  6155. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6156. [&](const Request &req, Response &res) {
  6157. res.set_header("x-dav-match", req.matches[1]);
  6158. res.status = StatusCode::MultiStatus_207;
  6159. })
  6160. .CustomRoute("MKCOL", "/dav-mkcol",
  6161. [&](const Request &req, Response &res) {
  6162. EXPECT_TRUE(req.body.empty());
  6163. res.status = StatusCode::Created_201;
  6164. })
  6165. .CustomRoute(
  6166. "REPORT", "/dav-report",
  6167. [&](const Request & /*req*/, Response &res,
  6168. const ContentReader &content_reader) {
  6169. std::string body;
  6170. content_reader([&](const char *data, size_t data_length) {
  6171. body.append(data, data_length);
  6172. return true;
  6173. });
  6174. res.set_header("x-body-size", std::to_string(body.size()));
  6175. res.status = StatusCode::MultiStatus_207;
  6176. res.set_content(body, "application/xml");
  6177. })
  6178. .Get("/request-target",
  6179. [&](const Request &req, Response & /*res*/) {
  6180. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6181. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6182. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6183. })
  6184. .Get("/long-query-value",
  6185. [&](const Request &req, Response & /*res*/) {
  6186. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6187. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6188. })
  6189. .Get("/too-long-query-value",
  6190. [&](const Request &req, Response & /*res*/) {
  6191. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6192. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6193. })
  6194. .Get("/array-param",
  6195. [&](const Request &req, Response & /*res*/) {
  6196. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6197. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6198. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6199. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6200. })
  6201. .Get("/array-param-values",
  6202. [&](const Request &req, Response & /*res*/) {
  6203. auto values = req.get_param_values("array");
  6204. EXPECT_EQ(3u, values.size());
  6205. EXPECT_EQ("value1", values[0]);
  6206. EXPECT_EQ("value2", values[1]);
  6207. EXPECT_EQ("value3", values[2]);
  6208. auto empty = req.get_param_values("nonexistent");
  6209. EXPECT_TRUE(empty.empty());
  6210. })
  6211. .Post("/validate-no-multiple-headers",
  6212. [&](const Request &req, Response & /*res*/) {
  6213. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6214. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6215. })
  6216. .Post("/content_receiver",
  6217. [&](const Request &req, Response &res,
  6218. const ContentReader &content_reader) {
  6219. if (req.is_multipart_form_data()) {
  6220. std::vector<FormData> items;
  6221. content_reader(
  6222. [&](const FormData &file) {
  6223. items.push_back(file);
  6224. return true;
  6225. },
  6226. [&](const char *data, size_t data_length) {
  6227. items.back().content.append(data, data_length);
  6228. return true;
  6229. });
  6230. EXPECT_EQ(5u, items.size());
  6231. {
  6232. const auto &file = get_file_value(items, "text1");
  6233. EXPECT_TRUE(file.filename.empty());
  6234. EXPECT_EQ("text default", file.content);
  6235. }
  6236. {
  6237. const auto &file = get_file_value(items, "text2");
  6238. EXPECT_TRUE(file.filename.empty());
  6239. EXPECT_EQ("aωb", file.content);
  6240. }
  6241. {
  6242. const auto &file = get_file_value(items, "file1");
  6243. EXPECT_EQ("hello.txt", file.filename);
  6244. EXPECT_EQ("text/plain", file.content_type);
  6245. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6246. }
  6247. {
  6248. const auto &file = get_file_value(items, "file2");
  6249. EXPECT_EQ("world.json", file.filename);
  6250. EXPECT_EQ("application/json", file.content_type);
  6251. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6252. }
  6253. {
  6254. const auto &file = get_file_value(items, "file3");
  6255. EXPECT_TRUE(file.filename.empty());
  6256. EXPECT_EQ("application/octet-stream", file.content_type);
  6257. EXPECT_EQ(0u, file.content.size());
  6258. }
  6259. } else {
  6260. std::string body;
  6261. content_reader([&](const char *data, size_t data_length) {
  6262. EXPECT_EQ(7U, data_length);
  6263. body.append(data, data_length);
  6264. return true;
  6265. });
  6266. EXPECT_EQ(body, "content");
  6267. res.set_content(body, "text/plain");
  6268. }
  6269. })
  6270. .Put("/content_receiver",
  6271. [&](const Request & /*req*/, Response &res,
  6272. const ContentReader &content_reader) {
  6273. std::string body;
  6274. content_reader([&](const char *data, size_t data_length) {
  6275. body.append(data, data_length);
  6276. return true;
  6277. });
  6278. EXPECT_EQ(body, "content");
  6279. res.set_content(body, "text/plain");
  6280. })
  6281. .Patch("/content_receiver",
  6282. [&](const Request & /*req*/, Response &res,
  6283. const ContentReader &content_reader) {
  6284. std::string body;
  6285. content_reader([&](const char *data, size_t data_length) {
  6286. body.append(data, data_length);
  6287. return true;
  6288. });
  6289. EXPECT_EQ(body, "content");
  6290. res.set_content(body, "text/plain");
  6291. })
  6292. .Post("/query-string-and-body",
  6293. [&](const Request &req, Response & /*res*/) {
  6294. ASSERT_TRUE(req.has_param("key"));
  6295. EXPECT_EQ(req.get_param_value("key"), "value");
  6296. EXPECT_EQ(req.body, "content");
  6297. })
  6298. .Get("/last-request",
  6299. [&](const Request &req, Response & /*res*/) {
  6300. EXPECT_EQ("close", req.get_header_value("Connection"));
  6301. })
  6302. .Get(R"(/redirect/(\d+))",
  6303. [&](const Request &req, Response &res) {
  6304. auto num = std::stoi(req.matches[1]) + 1;
  6305. std::string url = "/redirect/" + std::to_string(num);
  6306. res.set_redirect(url);
  6307. })
  6308. .Post("/binary",
  6309. [&](const Request &req, Response &res) {
  6310. EXPECT_EQ(4U, req.body.size());
  6311. EXPECT_EQ("application/octet-stream",
  6312. req.get_header_value("Content-Type"));
  6313. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6314. res.set_content(req.body, "application/octet-stream");
  6315. })
  6316. .Put("/binary",
  6317. [&](const Request &req, Response &res) {
  6318. EXPECT_EQ(4U, req.body.size());
  6319. EXPECT_EQ("application/octet-stream",
  6320. req.get_header_value("Content-Type"));
  6321. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6322. res.set_content(req.body, "application/octet-stream");
  6323. })
  6324. .Patch("/binary",
  6325. [&](const Request &req, Response &res) {
  6326. EXPECT_EQ(4U, req.body.size());
  6327. EXPECT_EQ("application/octet-stream",
  6328. req.get_header_value("Content-Type"));
  6329. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6330. res.set_content(req.body, "application/octet-stream");
  6331. })
  6332. .Delete("/binary",
  6333. [&](const Request &req, Response &res) {
  6334. EXPECT_EQ(4U, req.body.size());
  6335. EXPECT_EQ("application/octet-stream",
  6336. req.get_header_value("Content-Type"));
  6337. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6338. res.set_content(req.body, "application/octet-stream");
  6339. })
  6340. .Get("/issue1772",
  6341. [&](const Request & /*req*/, Response &res) {
  6342. res.status = 401;
  6343. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6344. })
  6345. .Delete("/issue609",
  6346. [](const httplib::Request &, httplib::Response &res,
  6347. const httplib::ContentReader &) {
  6348. res.set_content("ok", "text/plain");
  6349. })
  6350. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6351. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6352. .Get("/compress",
  6353. [&](const Request & /*req*/, Response &res) {
  6354. res.set_content(
  6355. "12345678901234567890123456789012345678901234567890123456789"
  6356. "01234567890123456789012345678901234567890",
  6357. "text/plain");
  6358. })
  6359. .Get("/compress-with-charset",
  6360. [&](const Request & /*req*/, Response &res) {
  6361. res.set_content(
  6362. "12345678901234567890123456789012345678901234567890123456789"
  6363. "01234567890123456789012345678901234567890",
  6364. "application/json; charset=utf-8");
  6365. })
  6366. .Get("/nocompress",
  6367. [&](const Request & /*req*/, Response &res) {
  6368. res.set_content(
  6369. "12345678901234567890123456789012345678901234567890123456789"
  6370. "01234567890123456789012345678901234567890",
  6371. "application/octet-stream");
  6372. })
  6373. .Post("/compress-multipart",
  6374. [&](const Request &req, Response & /*res*/) {
  6375. EXPECT_EQ(2u, req.form.fields.size());
  6376. ASSERT_TRUE(!req.form.has_field("???"));
  6377. {
  6378. const auto &text = req.form.get_field("key1");
  6379. EXPECT_EQ("test", text);
  6380. }
  6381. {
  6382. const auto &text = req.form.get_field("key2");
  6383. EXPECT_EQ("--abcdefg123", text);
  6384. }
  6385. })
  6386. #endif
  6387. ;
  6388. persons_["john"] = "programmer";
  6389. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6390. svr_.wait_until_ready();
  6391. }
  6392. virtual void TearDown() {
  6393. svr_.stop();
  6394. if (!request_threads_.empty()) {
  6395. std::this_thread::sleep_for(std::chrono::seconds(1));
  6396. for (auto &t : request_threads_) {
  6397. t.join();
  6398. }
  6399. }
  6400. t_.join();
  6401. }
  6402. map<string, string> persons_;
  6403. #ifdef CPPHTTPLIB_SSL_ENABLED
  6404. SSLClient cli_;
  6405. SSLServer svr_;
  6406. #else
  6407. Client cli_;
  6408. Server svr_;
  6409. #endif
  6410. thread t_;
  6411. std::vector<thread> request_threads_;
  6412. };
  6413. TEST_F(ServerTest, GetMethod200) {
  6414. auto res = cli_.Get("/hi");
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ("HTTP/1.1", res->version);
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. EXPECT_EQ("OK", res->reason);
  6419. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6420. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6421. EXPECT_EQ("Hello World!", res->body);
  6422. }
  6423. TEST_F(ServerTest, GetEmptyFile) {
  6424. auto res = cli_.Get("/empty_file");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6428. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6429. EXPECT_EQ("", res->body);
  6430. }
  6431. TEST_F(ServerTest, GetFileContent) {
  6432. auto res = cli_.Get("/file_content");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6436. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6437. EXPECT_EQ("test.html", res->body);
  6438. }
  6439. TEST_F(ServerTest, GetFileContentWithRange) {
  6440. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6443. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6444. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6445. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6446. EXPECT_EQ("est", res->body);
  6447. }
  6448. TEST_F(ServerTest, GetFileContentWithContentType) {
  6449. auto res = cli_.Get("/file_content_with_content_type");
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6453. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6454. EXPECT_EQ("file\n", res->body);
  6455. }
  6456. TEST_F(ServerTest, GetInvalidFileContent) {
  6457. auto res = cli_.Get("/invalid_file_content");
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6460. }
  6461. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6462. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. EXPECT_EQ("HTTP/1.1", res->version);
  6465. EXPECT_EQ(StatusCode::OK_200, res->status);
  6466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6467. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6468. EXPECT_EQ("Hello World!", res->body);
  6469. }
  6470. TEST_F(ServerTest, GetMethod302) {
  6471. auto res = cli_.Get("/");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::Found_302, res->status);
  6474. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6475. }
  6476. TEST_F(ServerTest, GetMethod302Redirect) {
  6477. cli_.set_follow_location(true);
  6478. auto res = cli_.Get("/");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::OK_200, res->status);
  6481. EXPECT_EQ("Hello World!", res->body);
  6482. EXPECT_EQ("/hi", res->location);
  6483. }
  6484. TEST_F(ServerTest, GetMethod404) {
  6485. auto res = cli_.Get("/invalid");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6488. }
  6489. TEST_F(ServerTest, HeadMethod200) {
  6490. auto res = cli_.Head("/hi");
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::OK_200, res->status);
  6493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6494. EXPECT_TRUE(res->body.empty());
  6495. }
  6496. TEST_F(ServerTest, HeadMethod200Static) {
  6497. auto res = cli_.Head("/mount/dir/index.html");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6501. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6502. EXPECT_TRUE(res->body.empty());
  6503. }
  6504. TEST_F(ServerTest, HeadMethod404) {
  6505. auto res = cli_.Head("/invalid");
  6506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6508. EXPECT_TRUE(res->body.empty());
  6509. }
  6510. TEST_F(ServerTest, GetMethodPersonJohn) {
  6511. auto res = cli_.Get("/person/john");
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6515. EXPECT_EQ("programmer", res->body);
  6516. }
  6517. TEST_F(ServerTest, PostMethod1) {
  6518. auto res = cli_.Get("/person/john1");
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6521. res = cli_.Post("/person", "name=john1&note=coder",
  6522. "application/x-www-form-urlencoded");
  6523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6524. ASSERT_EQ(StatusCode::OK_200, res->status);
  6525. res = cli_.Get("/person/john1");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. ASSERT_EQ(StatusCode::OK_200, res->status);
  6528. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6529. ASSERT_EQ("coder", res->body);
  6530. }
  6531. TEST_F(ServerTest, PostMethod2) {
  6532. auto res = cli_.Get("/person/john2");
  6533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6534. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6535. Params params;
  6536. params.emplace("name", "john2");
  6537. params.emplace("note", "coder");
  6538. res = cli_.Post("/person", params);
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. ASSERT_EQ(StatusCode::OK_200, res->status);
  6541. res = cli_.Get("/person/john2");
  6542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6543. ASSERT_EQ(StatusCode::OK_200, res->status);
  6544. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6545. ASSERT_EQ("coder", res->body);
  6546. }
  6547. TEST_F(ServerTest, PutMethod3) {
  6548. auto res = cli_.Get("/person/john3");
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6551. Params params;
  6552. params.emplace("name", "john3");
  6553. params.emplace("note", "coder");
  6554. res = cli_.Put("/person", params);
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. ASSERT_EQ(StatusCode::OK_200, res->status);
  6557. res = cli_.Get("/person/john3");
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. ASSERT_EQ(StatusCode::OK_200, res->status);
  6560. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6561. ASSERT_EQ("coder", res->body);
  6562. }
  6563. TEST_F(ServerTest, DeleteMethod1) {
  6564. auto res = cli_.Get("/person/john4");
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6567. Params params;
  6568. params.emplace("name", "john4");
  6569. params.emplace("note", "coder");
  6570. res = cli_.Post("/person", params);
  6571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6572. ASSERT_EQ(StatusCode::OK_200, res->status);
  6573. res = cli_.Get("/person/john4");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. ASSERT_EQ(StatusCode::OK_200, res->status);
  6576. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. ASSERT_EQ("coder", res->body);
  6578. Params delete_params;
  6579. delete_params.emplace("name", "john4");
  6580. res = cli_.Delete("/person", delete_params);
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. ASSERT_EQ(StatusCode::OK_200, res->status);
  6583. ASSERT_EQ("DELETED", res->body);
  6584. res = cli_.Get("/person/john4");
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6587. }
  6588. TEST_F(ServerTest, DeleteMethod2) {
  6589. auto res = cli_.Get("/person/john5");
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6592. Params params;
  6593. params.emplace("name", "john5");
  6594. params.emplace("note", "developer");
  6595. res = cli_.Post("/person", params);
  6596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6597. ASSERT_EQ(StatusCode::OK_200, res->status);
  6598. res = cli_.Get("/person/john5");
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. ASSERT_EQ(StatusCode::OK_200, res->status);
  6601. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6602. ASSERT_EQ("developer", res->body);
  6603. Params delete_params;
  6604. delete_params.emplace("name", "john5");
  6605. Headers headers;
  6606. headers.emplace("Custom-Header", "test-value");
  6607. res = cli_.Delete("/person", headers, delete_params);
  6608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6609. ASSERT_EQ(StatusCode::OK_200, res->status);
  6610. ASSERT_EQ("DELETED", res->body);
  6611. res = cli_.Get("/person/john5");
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6614. }
  6615. TEST_F(ServerTest, DeleteMethod3) {
  6616. auto res = cli_.Get("/person/john6");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6619. Params params;
  6620. params.emplace("name", "john6");
  6621. params.emplace("note", "tester");
  6622. res = cli_.Post("/person", params);
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. ASSERT_EQ(StatusCode::OK_200, res->status);
  6625. res = cli_.Get("/person/john6");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. ASSERT_EQ(StatusCode::OK_200, res->status);
  6628. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6629. ASSERT_EQ("tester", res->body);
  6630. Params delete_params;
  6631. delete_params.emplace("name", "john6");
  6632. Headers headers;
  6633. headers.emplace("Custom-Header", "test-value");
  6634. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6636. ASSERT_EQ(StatusCode::OK_200, res->status);
  6637. ASSERT_EQ("DELETED", res->body);
  6638. res = cli_.Get("/person/john6");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6641. }
  6642. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6643. Params params;
  6644. params.emplace("json", JSON_DATA);
  6645. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. ASSERT_EQ(StatusCode::OK_200, res->status);
  6648. ASSERT_EQ(JSON_DATA, res->body);
  6649. }
  6650. TEST_F(ServerTest, PostEmptyContent) {
  6651. auto res = cli_.Post("/empty", "", "text/plain");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. ASSERT_EQ(StatusCode::OK_200, res->status);
  6654. ASSERT_EQ("empty", res->body);
  6655. }
  6656. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6657. auto res = cli_.Post("/empty-no-content-type");
  6658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6659. ASSERT_EQ(StatusCode::OK_200, res->status);
  6660. ASSERT_EQ("empty-no-content-type", res->body);
  6661. }
  6662. TEST_F(ServerTest, PostPathOnly) {
  6663. auto res = cli_.Post("/path-only");
  6664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6665. ASSERT_EQ(StatusCode::OK_200, res->status);
  6666. ASSERT_EQ("path-only", res->body);
  6667. }
  6668. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6669. auto res = cli_.Post("/path-headers-only",
  6670. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6672. ASSERT_EQ(StatusCode::OK_200, res->status);
  6673. ASSERT_EQ("path-headers-only", res->body);
  6674. }
  6675. TEST_F(ServerTest, PostLarge) {
  6676. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. ASSERT_EQ(StatusCode::OK_200, res->status);
  6679. EXPECT_EQ(LARGE_DATA, res->body);
  6680. }
  6681. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6682. auto res = cli_.Put("/empty-no-content-type");
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. ASSERT_EQ(StatusCode::OK_200, res->status);
  6685. ASSERT_EQ("empty-no-content-type", res->body);
  6686. }
  6687. TEST_F(ServerTest, GetMethodDir) {
  6688. auto res = cli_.Get("/dir/");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6692. auto body = R"(<html>
  6693. <head>
  6694. </head>
  6695. <body>
  6696. <a href="/dir/test.html">Test</a>
  6697. <a href="/hi">hi</a>
  6698. </body>
  6699. </html>
  6700. )";
  6701. EXPECT_EQ(body, res->body);
  6702. }
  6703. TEST_F(ServerTest, GetMethodDirTest) {
  6704. auto res = cli_.Get("/dir/test.html");
  6705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6706. EXPECT_EQ(StatusCode::OK_200, res->status);
  6707. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6708. EXPECT_EQ("test.html", res->body);
  6709. }
  6710. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6711. auto res = cli_.Get("/dir/../dir/test.html");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6714. }
  6715. TEST_F(ServerTest, GetMethodInvalidPath) {
  6716. auto res = cli_.Get("/dir/../test.html");
  6717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6719. }
  6720. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6721. auto res = cli_.Get("/../www/dir/test.html");
  6722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6724. }
  6725. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6726. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6729. }
  6730. TEST_F(ServerTest, GetMethodDirMountTest) {
  6731. auto res = cli_.Get("/mount/dir/test.html");
  6732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6733. EXPECT_EQ(StatusCode::OK_200, res->status);
  6734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6735. EXPECT_EQ("test.html", res->body);
  6736. }
  6737. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6738. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6741. }
  6742. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6743. auto res = cli_.Get("/mount/dir/../test.html");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6746. }
  6747. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6748. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6751. }
  6752. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6753. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6756. }
  6757. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6758. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6761. }
  6762. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6763. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6766. }
  6767. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6768. auto res = cli_.Get("/mount/dir");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6771. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6772. }
  6773. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6774. auto res = cli_.Get("//dir");
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6777. EXPECT_FALSE(res->has_header("Location"));
  6778. }
  6779. TEST_F(ServerTest, PostMethod303) {
  6780. auto res = cli_.Post("/1", "body", "text/plain");
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6783. EXPECT_EQ("/2", res->get_header_value("Location"));
  6784. }
  6785. TEST_F(ServerTest, PostMethod303Redirect) {
  6786. cli_.set_follow_location(true);
  6787. auto res = cli_.Post("/1", "body", "text/plain");
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. EXPECT_EQ("redirected.", res->body);
  6791. EXPECT_EQ("/2", res->location);
  6792. }
  6793. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6794. auto res = cli_.Get("/dir/test.abcde");
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6798. EXPECT_EQ("abcde", res->body);
  6799. }
  6800. TEST_F(ServerTest, StaticFileRange) {
  6801. auto res =
  6802. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6805. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6806. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6807. EXPECT_EQ(true, res->has_header("Content-Range"));
  6808. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6809. EXPECT_EQ(std::string("cd"), res->body);
  6810. }
  6811. TEST_F(ServerTest, StaticFileRanges) {
  6812. auto res = cli_.Get("/dir/test.abcde",
  6813. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6816. EXPECT_TRUE(
  6817. res->get_header_value("Content-Type")
  6818. .find(
  6819. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6820. 0);
  6821. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6822. }
  6823. TEST_F(ServerTest, StaticFileRangeHead) {
  6824. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6827. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6828. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6829. EXPECT_EQ(true, res->has_header("Content-Range"));
  6830. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6831. }
  6832. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6833. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6838. EXPECT_EQ(true, res->has_header("Content-Range"));
  6839. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6840. res->get_header_value("Content-Range"));
  6841. EXPECT_EQ("LAST\n", res->body);
  6842. }
  6843. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6844. auto res =
  6845. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6849. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6850. EXPECT_EQ(true, res->has_header("Content-Range"));
  6851. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6852. }
  6853. TEST_F(ServerTest, StaticFileBigFile) {
  6854. auto res = cli_.Get("/dir/1MB.txt");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6858. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6859. }
  6860. TEST_F(ServerTest, InvalidBaseDirMount) {
  6861. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6862. }
  6863. TEST_F(ServerTest, Binary) {
  6864. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6865. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6866. "application/octet-stream");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. ASSERT_EQ(StatusCode::OK_200, res->status);
  6869. ASSERT_EQ(4U, res->body.size());
  6870. res = cli_.Put("/binary", binary.data(), binary.size(),
  6871. "application/octet-stream");
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. ASSERT_EQ(StatusCode::OK_200, res->status);
  6874. ASSERT_EQ(4U, res->body.size());
  6875. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6876. "application/octet-stream");
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. ASSERT_EQ(StatusCode::OK_200, res->status);
  6879. ASSERT_EQ(4U, res->body.size());
  6880. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6881. "application/octet-stream");
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. ASSERT_EQ(StatusCode::OK_200, res->status);
  6884. ASSERT_EQ(4U, res->body.size());
  6885. }
  6886. TEST_F(ServerTest, BinaryString) {
  6887. auto binary = std::string("\x00\x01\x02\x03", 4);
  6888. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. ASSERT_EQ(StatusCode::OK_200, res->status);
  6891. ASSERT_EQ(4U, res->body.size());
  6892. res = cli_.Put("/binary", binary, "application/octet-stream");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. ASSERT_EQ(StatusCode::OK_200, res->status);
  6895. ASSERT_EQ(4U, res->body.size());
  6896. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6898. ASSERT_EQ(StatusCode::OK_200, res->status);
  6899. ASSERT_EQ(4U, res->body.size());
  6900. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. ASSERT_EQ(StatusCode::OK_200, res->status);
  6903. ASSERT_EQ(4U, res->body.size());
  6904. }
  6905. TEST_F(ServerTest, EmptyRequest) {
  6906. auto res = cli_.Get("");
  6907. ASSERT_TRUE(!res);
  6908. EXPECT_EQ(Error::Connection, res.error());
  6909. }
  6910. TEST_F(ServerTest, LongRequest) {
  6911. std::string request;
  6912. for (size_t i = 0; i < 545; i++) {
  6913. request += "/TooLongRequest";
  6914. }
  6915. request += "OK";
  6916. auto res = cli_.Get(request.c_str());
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6919. }
  6920. TEST_F(ServerTest, TooLongRequest) {
  6921. std::string request;
  6922. for (size_t i = 0; i < 546; i++) {
  6923. request += "/TooLongRequest";
  6924. }
  6925. request += "_NG";
  6926. auto start = std::chrono::high_resolution_clock::now();
  6927. cli_.set_keep_alive(true);
  6928. auto res = cli_.Get(request.c_str());
  6929. auto end = std::chrono::high_resolution_clock::now();
  6930. auto elapsed =
  6931. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6932. .count();
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6935. EXPECT_LE(elapsed, 1000);
  6936. EXPECT_EQ("close", res->get_header_value("Connection"));
  6937. EXPECT_FALSE(cli_.is_socket_open());
  6938. }
  6939. TEST_F(ServerTest, AlmostTooLongRequest) {
  6940. // test for #2046 - URI length check shouldn't include other content on req
  6941. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6942. // leading /, space, HTTP/1.1)
  6943. std::string request =
  6944. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6945. auto res = cli_.Get(request.c_str());
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6948. }
  6949. TEST_F(ServerTest, LongHeader) {
  6950. Request req;
  6951. req.method = "GET";
  6952. req.path = "/hi";
  6953. std::string host_and_port;
  6954. host_and_port += HOST;
  6955. host_and_port += ":";
  6956. host_and_port += std::to_string(PORT);
  6957. req.headers.emplace("Host", host_and_port.c_str());
  6958. req.headers.emplace("Accept", "*/*");
  6959. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6960. req.headers.emplace(
  6961. "Header-Name",
  6962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6990. "@@@@@@@@@@@@@@@@");
  6991. auto res = std::make_shared<Response>();
  6992. auto error = Error::Success;
  6993. auto ret = cli_.send(req, *res, error);
  6994. ASSERT_TRUE(ret);
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. }
  6997. TEST_F(ServerTest, LongQueryValue) {
  6998. auto start = std::chrono::high_resolution_clock::now();
  6999. cli_.set_keep_alive(true);
  7000. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7001. auto end = std::chrono::high_resolution_clock::now();
  7002. auto elapsed =
  7003. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7004. .count();
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7007. EXPECT_LE(elapsed, 1000);
  7008. EXPECT_EQ("close", res->get_header_value("Connection"));
  7009. EXPECT_FALSE(cli_.is_socket_open());
  7010. }
  7011. TEST_F(ServerTest, TooLongQueryValue) {
  7012. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7013. ASSERT_FALSE(res);
  7014. EXPECT_EQ(Error::Read, res.error());
  7015. }
  7016. TEST_F(ServerTest, TooLongHeader) {
  7017. Request req;
  7018. req.method = "GET";
  7019. req.path = "/hi";
  7020. std::string host_and_port;
  7021. host_and_port += HOST;
  7022. host_and_port += ":";
  7023. host_and_port += std::to_string(PORT);
  7024. req.headers.emplace("Host", host_and_port.c_str());
  7025. req.headers.emplace("Accept", "*/*");
  7026. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7027. req.headers.emplace(
  7028. "Header-Name",
  7029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7057. "@@@@@@@@@@@@@@@@@");
  7058. auto res = std::make_shared<Response>();
  7059. auto error = Error::Success;
  7060. auto ret = cli_.send(req, *res, error);
  7061. ASSERT_TRUE(ret);
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. }
  7064. TEST_F(ServerTest, HeaderCountAtLimit) {
  7065. // Test with headers just under the 100 limit
  7066. httplib::Headers headers;
  7067. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7068. // This should keep us just under the 100 header limit
  7069. for (int i = 0; i < 95; i++) {
  7070. std::string name = "X-Test-Header-" + std::to_string(i);
  7071. std::string value = "value" + std::to_string(i);
  7072. headers.emplace(name, value);
  7073. }
  7074. // This should work fine as we're under the limit
  7075. auto res = cli_.Get("/hi", headers);
  7076. EXPECT_TRUE(res);
  7077. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7078. }
  7079. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7080. // Test with many headers to exceed the 100 limit
  7081. httplib::Headers headers;
  7082. // Add 150 headers to definitely exceed the 100 limit
  7083. for (int i = 0; i < 150; i++) {
  7084. std::string name = "X-Test-Header-" + std::to_string(i);
  7085. std::string value = "value" + std::to_string(i);
  7086. headers.emplace(name, value);
  7087. }
  7088. // This should fail due to exceeding header count limit
  7089. cli_.set_keep_alive(true);
  7090. auto res = cli_.Get("/hi", headers);
  7091. // The server should respond with 400 Bad Request
  7092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7093. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7094. EXPECT_EQ("close", res->get_header_value("Connection"));
  7095. EXPECT_FALSE(cli_.is_socket_open());
  7096. }
  7097. TEST_F(ServerTest, PercentEncoding) {
  7098. auto res = cli_.Get("/e%6edwith%");
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::OK_200, res->status);
  7101. }
  7102. TEST_F(ServerTest, PercentEncodingUnicode) {
  7103. auto res = cli_.Get("/e%u006edwith%");
  7104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7105. EXPECT_EQ(StatusCode::OK_200, res->status);
  7106. }
  7107. TEST_F(ServerTest, InvalidPercentEncoding) {
  7108. auto res = cli_.Get("/%endwith%");
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7111. }
  7112. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7113. auto res = cli_.Get("/%uendwith%");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7116. }
  7117. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7118. auto res = cli_.Get("/hello?aaa=bbb%");
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7121. }
  7122. TEST_F(ServerTest, PlusSignEncoding) {
  7123. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::OK_200, res->status);
  7126. EXPECT_EQ("a +b", res->body);
  7127. }
  7128. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7129. // This test simulates a potential DoS attack using many headers
  7130. // to verify our security fix prevents memory exhaustion
  7131. httplib::Headers attack_headers;
  7132. // Attempt to add many headers like an attacker would (200 headers to far
  7133. // exceed limit)
  7134. for (int i = 0; i < 200; i++) {
  7135. std::string name = "X-Attack-Header-" + std::to_string(i);
  7136. std::string value = "attack_payload_" + std::to_string(i);
  7137. attack_headers.emplace(name, value);
  7138. }
  7139. // Try to POST with excessive headers
  7140. cli_.set_keep_alive(true);
  7141. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7142. // Should either fail or return 400 Bad Request due to security limit
  7143. if (res) {
  7144. // If we get a response, it should be 400 Bad Request
  7145. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7146. EXPECT_EQ("close", res->get_header_value("Connection"));
  7147. }
  7148. EXPECT_FALSE(cli_.is_socket_open());
  7149. }
  7150. TEST_F(ServerTest, MultipartFormData) {
  7151. UploadFormDataItems items = {
  7152. {"text1", "text default", "", ""},
  7153. {"text2", "aωb", "", ""},
  7154. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7155. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7156. {"file3", "", "", "application/octet-stream"},
  7157. {"file4", "", "", " application/json tmp-string "}};
  7158. auto res = cli_.Post("/multipart", items);
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::OK_200, res->status);
  7161. }
  7162. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7163. UploadFormDataItems items = {
  7164. {"text", "default text", "", ""},
  7165. {"multi_text1", "aaaaa", "", ""},
  7166. {"multi_text1", "bbbbb", "", ""},
  7167. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7168. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7169. "application/json"},
  7170. };
  7171. auto res = cli_.Post("/multipart/multi_file_values", items);
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::OK_200, res->status);
  7174. }
  7175. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7176. auto res = cli_.Get("/hi");
  7177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7178. EXPECT_EQ(StatusCode::OK_200, res->status);
  7179. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7180. EXPECT_EQ("Hello World!", res->body);
  7181. }
  7182. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7183. Request req;
  7184. req.method = "POST";
  7185. req.path = "/chunked";
  7186. std::string host_and_port;
  7187. host_and_port += HOST;
  7188. host_and_port += ":";
  7189. host_and_port += std::to_string(PORT);
  7190. req.headers.emplace("Host", host_and_port.c_str());
  7191. req.headers.emplace("Accept", "*/*");
  7192. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7193. req.headers.emplace("Content-Type", "text/plain");
  7194. req.headers.emplace("Content-Length", "0");
  7195. req.headers.emplace(
  7196. "Transfer-Encoding",
  7197. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7198. // Client does not chunk, so make a chunked body manually.
  7199. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7200. auto res = std::make_shared<Response>();
  7201. auto error = Error::Success;
  7202. auto ret = cli_.send(req, *res, error);
  7203. ASSERT_TRUE(ret);
  7204. EXPECT_EQ(StatusCode::OK_200, res->status);
  7205. }
  7206. template <typename ClientT>
  7207. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7208. int expected_status) {
  7209. Request req;
  7210. req.method = "POST";
  7211. req.path = "/chunked";
  7212. std::string host_and_port;
  7213. host_and_port += HOST;
  7214. host_and_port += ":";
  7215. host_and_port += std::to_string(PORT);
  7216. req.headers.emplace("Host", host_and_port.c_str());
  7217. req.headers.emplace("Content-Length", "0");
  7218. req.headers.emplace("Transfer-Encoding", "chunked");
  7219. req.body = body;
  7220. auto res = std::make_shared<Response>();
  7221. auto error = Error::Success;
  7222. ASSERT_TRUE(cli.send(req, *res, error));
  7223. EXPECT_EQ(expected_status, res->status);
  7224. }
  7225. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7226. // rather than treat them as valid lengths.
  7227. template <typename ClientT>
  7228. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7229. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7230. }
  7231. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7232. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7233. }
  7234. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7235. expect_chunked_body_rejected(
  7236. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7237. }
  7238. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7239. // chunk-size line carries no CR, LF or other control character ahead of its
  7240. // terminator. Such a line must be refused rather than read as extension text.
  7241. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7242. expect_chunked_body_rejected(
  7243. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7244. }
  7245. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7246. expect_chunked_body_rejected(
  7247. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7248. }
  7249. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7250. expect_chunked_body_rejected(
  7251. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7252. }
  7253. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7254. // The literal stays split: a hex escape consumes every hex digit that
  7255. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7256. expect_chunked_body_rejected(
  7257. cli_, "4;a\x01"
  7258. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7259. }
  7260. // The bytes around chunk data are no payload, so they cannot ride on the
  7261. // payload limit
  7262. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7263. // Small enough that the whole request is sent before the server turns it
  7264. // down, yet past the limit by the last chunks
  7265. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7266. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7267. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7268. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7269. SCOPED_TRACE(size_line.substr(0, 2));
  7270. std::string body;
  7271. for (auto c : std::string("dechunked post body")) {
  7272. body += size_line + "\r\n" + c + "\r\n";
  7273. }
  7274. body += "0\r\n\r\n";
  7275. expect_chunked_body_rejected(cli_, body.c_str());
  7276. }
  7277. }
  7278. TEST_F(ServerTest, AcceptsChunkExtension) {
  7279. expect_chunked_body_status(cli_,
  7280. "4;name=value\r\ndech\r\n"
  7281. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7282. "0;last\r\n\r\n",
  7283. StatusCode::OK_200);
  7284. }
  7285. TEST_F(ServerTest, GetStreamed2) {
  7286. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7289. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7290. EXPECT_EQ(true, res->has_header("Content-Range"));
  7291. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7292. EXPECT_EQ(std::string("ab"), res->body);
  7293. }
  7294. TEST_F(ServerTest, GetStreamed) {
  7295. auto res = cli_.Get("/streamed");
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7299. EXPECT_EQ(std::string("aaabbb"), res->body);
  7300. }
  7301. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7302. auto res = cli_.Get("/streamed-without-length",
  7303. Headers{make_range_header({{0, -1}})});
  7304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7305. EXPECT_EQ(StatusCode::OK_200, res->status);
  7306. EXPECT_EQ(false, res->has_header("Content-Length"));
  7307. EXPECT_EQ(false, res->has_header("Content-Range"));
  7308. EXPECT_EQ(std::string("abcdefg"), res->body);
  7309. }
  7310. TEST_F(ServerTest, GetStreamedWithRange1) {
  7311. auto res =
  7312. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7315. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7316. EXPECT_EQ(true, res->has_header("Content-Range"));
  7317. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7318. EXPECT_EQ(std::string("def"), res->body);
  7319. }
  7320. TEST_F(ServerTest, GetStreamedWithRange2) {
  7321. auto res =
  7322. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7325. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7326. EXPECT_EQ(true, res->has_header("Content-Range"));
  7327. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7328. EXPECT_EQ(std::string("bcdefg"), res->body);
  7329. }
  7330. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7331. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7334. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7335. EXPECT_EQ(true, res->has_header("Content-Range"));
  7336. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7337. EXPECT_EQ(std::string("efg"), res->body);
  7338. }
  7339. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7340. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7341. // the entire representation.
  7342. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7343. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7345. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7346. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7347. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7348. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7349. }
  7350. }
  7351. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7352. auto res =
  7353. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7356. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7357. EXPECT_EQ(false, res->has_header("Content-Range"));
  7358. EXPECT_EQ(0U, res->body.size());
  7359. }
  7360. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7361. // Only a 206 is served as a partial representation. Under any other status
  7362. // `apply_ranges()` reported the full content length, so the body must match
  7363. // that header, and the content provider must never be asked for an offset
  7364. // outside the representation.
  7365. auto check = [&](int status, const char *range) {
  7366. auto path =
  7367. std::string("/streamed-with-range?status=") + std::to_string(status);
  7368. auto ctx = path + " Range: " + range;
  7369. auto res = cli_.Get(path, Headers{{"Range", range}});
  7370. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7371. EXPECT_EQ(status, res->status) << ctx;
  7372. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7374. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7375. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7376. };
  7377. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7378. check(403, "bytes=3-5");
  7379. // The offset is far past the representation.
  7380. check(403, "bytes=100000-100200");
  7381. // `first_pos` is still -1 here, and the bounds asserts in
  7382. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7383. check(403, "bytes=-3");
  7384. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7385. // multipart branch would have written one that is empty.
  7386. check(403, "bytes=1-2, 4-5");
  7387. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7388. // covers the whole representation.
  7389. check(200, "bytes=3-5");
  7390. check(200, "bytes=1-2, 4-5");
  7391. }
  7392. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7393. auto res =
  7394. cli_.Get("/streamed-with-range",
  7395. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7396. "92233720368547758079223372036854775807"}});
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7399. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7400. EXPECT_EQ(false, res->has_header("Content-Range"));
  7401. EXPECT_EQ(0U, res->body.size());
  7402. }
  7403. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7404. auto res = cli_.Get(
  7405. "/with-range",
  7406. Headers{{"Range",
  7407. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7408. {"Accept-Encoding", ""}});
  7409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7410. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7411. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7412. EXPECT_EQ(true, res->has_header("Content-Range"));
  7413. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7414. EXPECT_EQ(std::string("abcdefg"), res->body);
  7415. }
  7416. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7417. auto res = cli_.Get("/with-range", Headers{
  7418. {"Range", "bytes=0-"},
  7419. {"Accept-Encoding", ""},
  7420. });
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7423. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7424. EXPECT_EQ(true, res->has_header("Content-Range"));
  7425. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7426. EXPECT_EQ(std::string("abcdefg"), res->body);
  7427. }
  7428. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7429. auto res = cli_.Get("/streamed-with-range",
  7430. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7433. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7434. EXPECT_EQ(false, res->has_header("Content-Range"));
  7435. EXPECT_EQ(267U, res->body.size());
  7436. // Check that both range contents are present
  7437. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7438. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7439. // Check that Content-Range headers are present for both ranges
  7440. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7441. std::string::npos);
  7442. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7443. std::string::npos);
  7444. }
  7445. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7446. Ranges ranges;
  7447. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7448. ranges.emplace_back(0, -1);
  7449. }
  7450. auto res = cli_.Get("/streamed-with-range?error",
  7451. Headers{{make_range_header(ranges)}});
  7452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7453. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7454. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7455. EXPECT_EQ(false, res->has_header("Content-Range"));
  7456. EXPECT_EQ(0U, res->body.size());
  7457. }
  7458. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7459. auto res = cli_.Get("/streamed-with-range",
  7460. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7463. EXPECT_EQ(5U, res->body.size());
  7464. // Check that overlapping ranges are coalesced into a single range
  7465. EXPECT_EQ("bcdef", res->body);
  7466. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7467. // Should be single range, not multipart
  7468. EXPECT_TRUE(res->has_header("Content-Range"));
  7469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7470. }
  7471. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7472. auto res = cli_.Get("/streamed-with-range",
  7473. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7476. EXPECT_EQ(268U, res->body.size());
  7477. // Check that both range contents are present
  7478. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7479. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7480. // Check that Content-Range headers are present for both ranges
  7481. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7482. std::string::npos);
  7483. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7484. std::string::npos);
  7485. }
  7486. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7487. auto res = cli_.Get("/streamed-with-range",
  7488. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7491. EXPECT_EQ(269U, res->body.size());
  7492. // Check that both duplicate range contents are present
  7493. size_t first_abc = res->body.find("abc\r\n");
  7494. EXPECT_TRUE(first_abc != std::string::npos);
  7495. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7496. EXPECT_TRUE(second_abc != std::string::npos);
  7497. // Check that Content-Range headers are present for both ranges
  7498. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7499. EXPECT_TRUE(first_range != std::string::npos);
  7500. size_t second_range =
  7501. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7502. EXPECT_TRUE(second_range != std::string::npos);
  7503. }
  7504. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7505. auto res =
  7506. cli_.Get("/streamed-with-range?error",
  7507. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7510. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7511. EXPECT_EQ(false, res->has_header("Content-Range"));
  7512. EXPECT_EQ(0U, res->body.size());
  7513. }
  7514. TEST_F(ServerTest, GetStreamedEndless) {
  7515. uint64_t offset = 0;
  7516. auto res = cli_.Get("/streamed-cancel",
  7517. [&](const char * /*data*/, uint64_t data_length) {
  7518. if (offset < 100) {
  7519. offset += data_length;
  7520. return true;
  7521. }
  7522. return false;
  7523. });
  7524. ASSERT_TRUE(!res);
  7525. EXPECT_EQ(Error::Canceled, res.error());
  7526. }
  7527. TEST_F(ServerTest, ClientStop) {
  7528. std::atomic_size_t count{4};
  7529. std::vector<std::thread> threads;
  7530. for (auto i = count.load(); i != 0; --i) {
  7531. threads.emplace_back([&]() {
  7532. auto res = cli_.Get("/streamed-cancel",
  7533. [&](const char *, uint64_t) { return true; });
  7534. --count;
  7535. ASSERT_TRUE(!res);
  7536. EXPECT_TRUE(res.error() == Error::Canceled ||
  7537. res.error() == Error::Read || res.error() == Error::Write);
  7538. });
  7539. }
  7540. std::this_thread::sleep_for(std::chrono::seconds(2));
  7541. while (count != 0) {
  7542. cli_.stop();
  7543. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7544. }
  7545. for (auto &t : threads) {
  7546. t.join();
  7547. }
  7548. }
  7549. TEST_F(ServerTest, GetWithRange1) {
  7550. auto res = cli_.Get("/with-range", Headers{
  7551. make_range_header({{3, 5}}),
  7552. {"Accept-Encoding", ""},
  7553. });
  7554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7556. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7557. EXPECT_EQ(true, res->has_header("Content-Range"));
  7558. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7559. EXPECT_EQ(std::string("def"), res->body);
  7560. }
  7561. TEST_F(ServerTest, GetWithRange2) {
  7562. auto res = cli_.Get("/with-range", Headers{
  7563. make_range_header({{1, -1}}),
  7564. {"Accept-Encoding", ""},
  7565. });
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7568. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7569. EXPECT_EQ(true, res->has_header("Content-Range"));
  7570. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7571. EXPECT_EQ(std::string("bcdefg"), res->body);
  7572. }
  7573. TEST_F(ServerTest, GetWithRange3) {
  7574. auto res = cli_.Get("/with-range", Headers{
  7575. make_range_header({{0, 0}}),
  7576. {"Accept-Encoding", ""},
  7577. });
  7578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7580. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7581. EXPECT_EQ(true, res->has_header("Content-Range"));
  7582. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7583. EXPECT_EQ(std::string("a"), res->body);
  7584. }
  7585. TEST_F(ServerTest, GetWithRange4) {
  7586. auto res = cli_.Get("/with-range", Headers{
  7587. make_range_header({{-1, 2}}),
  7588. {"Accept-Encoding", ""},
  7589. });
  7590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7592. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7593. EXPECT_EQ(true, res->has_header("Content-Range"));
  7594. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7595. EXPECT_EQ(std::string("fg"), res->body);
  7596. }
  7597. TEST_F(ServerTest, GetWithRange5) {
  7598. auto res = cli_.Get("/with-range", Headers{
  7599. make_range_header({{0, 5}}),
  7600. {"Accept-Encoding", ""},
  7601. });
  7602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7604. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7605. EXPECT_EQ(true, res->has_header("Content-Range"));
  7606. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7607. EXPECT_EQ(std::string("abcdef"), res->body);
  7608. }
  7609. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7610. auto res =
  7611. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7614. }
  7615. TEST_F(ServerTest, GetWithRangeMultipart) {
  7616. auto res =
  7617. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7620. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7621. EXPECT_EQ(false, res->has_header("Content-Range"));
  7622. EXPECT_EQ(267U, res->body.size());
  7623. }
  7624. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7625. auto res = cli_.Get("/with-range",
  7626. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7628. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7629. }
  7630. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7631. auto res = cli_.Get("/with-range-customized-response",
  7632. Headers{{make_range_header({{1, 2}})}});
  7633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7634. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7635. EXPECT_EQ(true, res->has_header("Content-Length"));
  7636. EXPECT_EQ(false, res->has_header("Content-Range"));
  7637. EXPECT_EQ(JSON_DATA, res->body);
  7638. }
  7639. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7640. auto res = cli_.Get("/with-range-customized-response",
  7641. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7644. EXPECT_EQ(true, res->has_header("Content-Length"));
  7645. EXPECT_EQ(false, res->has_header("Content-Range"));
  7646. EXPECT_EQ(JSON_DATA, res->body);
  7647. }
  7648. TEST_F(ServerTest, Issue1772) {
  7649. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7652. }
  7653. TEST_F(ServerTest, Issue609) {
  7654. auto res = cli_.Delete("/issue609");
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. EXPECT_EQ(std::string("ok"), res->body);
  7658. }
  7659. TEST_F(ServerTest, GetStreamedChunked) {
  7660. auto res = cli_.Get("/streamed-chunked");
  7661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7662. EXPECT_EQ(StatusCode::OK_200, res->status);
  7663. EXPECT_EQ(std::string("123456789"), res->body);
  7664. }
  7665. TEST_F(ServerTest, GetStreamedChunked2) {
  7666. auto res = cli_.Get("/streamed-chunked2");
  7667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. EXPECT_EQ(std::string("123456789"), res->body);
  7670. }
  7671. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7672. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ(std::string("123456789"), res->body);
  7676. EXPECT_TRUE(res->has_header("Trailer"));
  7677. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7678. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7679. // Trailers are now stored separately from headers (security fix)
  7680. EXPECT_EQ(2U, res->trailers.size());
  7681. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7682. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7683. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7684. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7685. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7686. // Verify trailers are NOT in headers (security verification)
  7687. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7688. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7689. }
  7690. TEST_F(ServerTest, LargeChunkedPost) {
  7691. Request req;
  7692. req.method = "POST";
  7693. req.path = "/large-chunked";
  7694. std::string host_and_port;
  7695. host_and_port += HOST;
  7696. host_and_port += ":";
  7697. host_and_port += std::to_string(PORT);
  7698. req.headers.emplace("Host", host_and_port.c_str());
  7699. req.headers.emplace("Accept", "*/*");
  7700. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7701. req.headers.emplace("Content-Type", "text/plain");
  7702. req.headers.emplace("Content-Length", "0");
  7703. req.headers.emplace("Transfer-Encoding", "chunked");
  7704. std::string long_string(30 * 1024u, 'a');
  7705. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7706. // Attempt to make a large enough post to exceed OS buffers, to test that
  7707. // the server handles short reads if the full chunk data isn't available.
  7708. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7709. auto res = std::make_shared<Response>();
  7710. auto error = Error::Success;
  7711. auto ret = cli_.send(req, *res, error);
  7712. ASSERT_TRUE(ret);
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. }
  7715. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7716. auto res = cli_.Get("/remote_addr");
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7720. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7721. }
  7722. TEST_F(ServerTest, GetMethodLocalAddr) {
  7723. auto res = cli_.Get("/local_addr");
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::OK_200, res->status);
  7726. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7727. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7728. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7729. }
  7730. TEST_F(ServerTest, HTTPResponseSplitting) {
  7731. auto res = cli_.Get("/http_response_splitting");
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. }
  7735. TEST_F(ServerTest, SlowRequest) {
  7736. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7737. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7738. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7739. }
  7740. #if 0
  7741. TEST_F(ServerTest, SlowPost) {
  7742. char buffer[64 * 1024];
  7743. memset(buffer, 0x42, sizeof(buffer));
  7744. auto res = cli_.Post(
  7745. "/slowpost", 64 * 1024 * 1024,
  7746. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7747. auto ret = sink.write(buffer, sizeof(buffer));
  7748. EXPECT_TRUE(ret);
  7749. return true;
  7750. },
  7751. "text/plain");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. }
  7755. TEST_F(ServerTest, SlowPostFail) {
  7756. char buffer[64 * 1024];
  7757. memset(buffer, 0x42, sizeof(buffer));
  7758. cli_.set_write_timeout(std::chrono::seconds(0));
  7759. auto res = cli_.Post(
  7760. "/slowpost", 64 * 1024 * 1024,
  7761. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7762. sink.write(buffer, sizeof(buffer));
  7763. return true;
  7764. },
  7765. "text/plain");
  7766. ASSERT_TRUE(!res);
  7767. EXPECT_EQ(Error::Write, res.error());
  7768. }
  7769. #endif
  7770. TEST_F(ServerTest, Put) {
  7771. auto res = cli_.Put("/put", "PUT", "text/plain");
  7772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7773. EXPECT_EQ(StatusCode::OK_200, res->status);
  7774. EXPECT_EQ("PUT", res->body);
  7775. }
  7776. TEST_F(ServerTest, PutWithContentProvider) {
  7777. auto res = cli_.Put(
  7778. "/put", 3,
  7779. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7780. sink.os << "PUT";
  7781. return true;
  7782. },
  7783. "text/plain");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. EXPECT_EQ("PUT", res->body);
  7787. }
  7788. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7789. auto res = cli_.Post(
  7790. "/post", 42,
  7791. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7792. return false;
  7793. },
  7794. "text/plain");
  7795. ASSERT_TRUE(!res);
  7796. EXPECT_EQ(Error::Canceled, res.error());
  7797. }
  7798. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7799. auto res = cli_.Put(
  7800. "/put",
  7801. [](size_t /*offset*/, DataSink &sink) {
  7802. sink.os << "PUT";
  7803. sink.done();
  7804. return true;
  7805. },
  7806. "text/plain");
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::OK_200, res->status);
  7809. EXPECT_EQ("PUT", res->body);
  7810. }
  7811. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7812. auto res = cli_.Post(
  7813. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7814. "text/plain");
  7815. ASSERT_TRUE(!res);
  7816. EXPECT_EQ(Error::Canceled, res.error());
  7817. }
  7818. TEST_F(ServerTest, PostLoopBack) {
  7819. std::string body;
  7820. auto res = cli_.Post(
  7821. "/post-loopback", 9,
  7822. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7823. EXPECT_EQ(9u, length);
  7824. sink.write("123", 3);
  7825. sink.write("456", 3);
  7826. sink.write("789", 3);
  7827. return true;
  7828. },
  7829. "text/plain",
  7830. [&body](const char *data, size_t data_length) {
  7831. body.append(data, data_length);
  7832. return true;
  7833. });
  7834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7835. EXPECT_EQ(StatusCode::OK_200, res->status);
  7836. EXPECT_EQ("123456789", body);
  7837. }
  7838. TEST_F(ServerTest, PutLoopBack) {
  7839. std::string body;
  7840. auto res = cli_.Put(
  7841. "/put-loopback", 9,
  7842. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7843. EXPECT_EQ(9u, length);
  7844. sink.write("123", 3);
  7845. sink.write("456", 3);
  7846. sink.write("789", 3);
  7847. return true;
  7848. },
  7849. "text/plain",
  7850. [&body](const char *data, size_t data_length) {
  7851. body.append(data, data_length);
  7852. return true;
  7853. });
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. EXPECT_EQ("123456789", body);
  7857. }
  7858. TEST_F(ServerTest, PatchLoopBack) {
  7859. std::string body;
  7860. auto res = cli_.Patch(
  7861. "/patch-loopback", 9,
  7862. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7863. EXPECT_EQ(9u, length);
  7864. sink.write("123", 3);
  7865. sink.write("456", 3);
  7866. sink.write("789", 3);
  7867. return true;
  7868. },
  7869. "text/plain",
  7870. [&body](const char *data, size_t data_length) {
  7871. body.append(data, data_length);
  7872. return true;
  7873. });
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. EXPECT_EQ("123456789", body);
  7877. }
  7878. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7879. std::string body;
  7880. auto res = cli_.Post(
  7881. "/post-loopback",
  7882. [](size_t /*offset*/, DataSink &sink) {
  7883. sink.write("123", 3);
  7884. sink.write("456", 3);
  7885. sink.write("789", 3);
  7886. sink.done();
  7887. return true;
  7888. },
  7889. "text/plain",
  7890. [&body](const char *data, size_t data_length) {
  7891. body.append(data, data_length);
  7892. return true;
  7893. });
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. EXPECT_EQ("123456789", body);
  7897. }
  7898. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7899. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7900. cli_.set_compress(true);
  7901. auto res = cli_.Put(
  7902. "/put", 3,
  7903. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7904. sink.os << "PUT";
  7905. return true;
  7906. },
  7907. "text/plain");
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. EXPECT_EQ("PUT", res->body);
  7911. }
  7912. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7913. cli_.set_compress(true);
  7914. auto res = cli_.Post(
  7915. "/post", 42,
  7916. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7917. return false;
  7918. },
  7919. "text/plain");
  7920. ASSERT_TRUE(!res);
  7921. EXPECT_EQ(Error::Canceled, res.error());
  7922. }
  7923. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7924. cli_.set_compress(true);
  7925. auto res = cli_.Put(
  7926. "/put",
  7927. [](size_t /*offset*/, DataSink &sink) {
  7928. sink.os << "PUT";
  7929. sink.done();
  7930. return true;
  7931. },
  7932. "text/plain");
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::OK_200, res->status);
  7935. EXPECT_EQ("PUT", res->body);
  7936. }
  7937. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7938. cli_.set_compress(true);
  7939. auto res = cli_.Post(
  7940. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7941. "text/plain");
  7942. ASSERT_TRUE(!res);
  7943. EXPECT_EQ(Error::Canceled, res.error());
  7944. }
  7945. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7946. cli_.set_compress(true);
  7947. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ(StatusCode::OK_200, res->status);
  7950. EXPECT_EQ(LARGE_DATA, res->body);
  7951. }
  7952. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7953. #ifdef CPPHTTPLIB_SSL_ENABLED
  7954. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7955. Client cli(s.c_str());
  7956. cli.enable_server_certificate_verification(false);
  7957. #else
  7958. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7959. Client cli(s.c_str());
  7960. #endif
  7961. cli.set_compress(true);
  7962. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_EQ(LARGE_DATA, res->body);
  7966. // The compressed size should be less than a 10th of the original. May vary
  7967. // depending on the zlib library.
  7968. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7969. static_cast<uint64_t>(10 * 1024 * 1024));
  7970. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7971. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7972. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7973. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7974. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7975. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7976. #endif
  7977. }
  7978. TEST_F(ServerTest, PutContentWithDeflate) {
  7979. cli_.set_compress(false);
  7980. Headers headers;
  7981. headers.emplace("Content-Encoding", "deflate");
  7982. // PUT in deflate format:
  7983. auto res = cli_.Put("/put", headers,
  7984. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. EXPECT_EQ("PUT", res->body);
  7988. }
  7989. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7990. Headers headers;
  7991. headers.emplace("Accept-Encoding", "gzip, deflate");
  7992. auto res = cli_.Get("/streamed-chunked", headers);
  7993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7994. EXPECT_EQ(StatusCode::OK_200, res->status);
  7995. EXPECT_EQ(std::string("123456789"), res->body);
  7996. }
  7997. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7998. Headers headers;
  7999. headers.emplace("Accept-Encoding", "gzip, deflate");
  8000. auto res = cli_.Get("/streamed-chunked2", headers);
  8001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8002. EXPECT_EQ(StatusCode::OK_200, res->status);
  8003. EXPECT_EQ(std::string("123456789"), res->body);
  8004. }
  8005. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8006. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. }
  8010. TEST(GzipDecompressor, ChunkedDecompression) {
  8011. std::string data;
  8012. for (size_t i = 0; i < 32 * 1024; ++i) {
  8013. data.push_back(static_cast<char>('a' + i % 26));
  8014. }
  8015. std::string compressed_data;
  8016. {
  8017. httplib::detail::gzip_compressor compressor;
  8018. bool result = compressor.compress(
  8019. data.data(), data.size(),
  8020. /*last=*/true,
  8021. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8022. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8023. compressed_data_size);
  8024. return true;
  8025. });
  8026. ASSERT_TRUE(result);
  8027. }
  8028. std::string decompressed_data;
  8029. {
  8030. httplib::detail::gzip_decompressor decompressor;
  8031. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8032. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8033. size_t chunk_size = 130;
  8034. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8035. chunk_begin += chunk_size) {
  8036. size_t current_chunk_size =
  8037. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8038. bool result = decompressor.decompress(
  8039. compressed_data.data() + chunk_begin, current_chunk_size,
  8040. [&](const char *decompressed_data_chunk,
  8041. size_t decompressed_data_chunk_size) {
  8042. decompressed_data.insert(decompressed_data.size(),
  8043. decompressed_data_chunk,
  8044. decompressed_data_chunk_size);
  8045. return true;
  8046. });
  8047. ASSERT_TRUE(result);
  8048. }
  8049. }
  8050. ASSERT_EQ(data, decompressed_data);
  8051. }
  8052. TEST(GzipDecompressor, DeflateDecompression) {
  8053. std::string original_text = "Raw deflate without gzip";
  8054. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8055. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8056. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8057. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8058. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8059. std::string decompressed_data;
  8060. {
  8061. httplib::detail::gzip_decompressor decompressor;
  8062. bool result = decompressor.decompress(
  8063. compressed_data.data(), compressed_data.size(),
  8064. [&](const char *decompressed_data_chunk,
  8065. size_t decompressed_data_chunk_size) {
  8066. decompressed_data.insert(decompressed_data.size(),
  8067. decompressed_data_chunk,
  8068. decompressed_data_chunk_size);
  8069. return true;
  8070. });
  8071. ASSERT_TRUE(result);
  8072. }
  8073. ASSERT_EQ(original_text, decompressed_data);
  8074. }
  8075. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8076. std::string original_text = "Raw deflate without gzip";
  8077. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8078. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8079. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8080. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8081. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8082. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8083. std::string decompressed_data;
  8084. {
  8085. httplib::detail::gzip_decompressor decompressor;
  8086. bool result = decompressor.decompress(
  8087. compressed_data.data(), compressed_data.size(),
  8088. [&](const char *decompressed_data_chunk,
  8089. size_t decompressed_data_chunk_size) {
  8090. decompressed_data.insert(decompressed_data.size(),
  8091. decompressed_data_chunk,
  8092. decompressed_data_chunk_size);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(result);
  8096. }
  8097. ASSERT_EQ(original_text, decompressed_data);
  8098. }
  8099. #endif
  8100. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8101. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8102. Headers headers;
  8103. headers.emplace("Accept-Encoding", "br");
  8104. auto res = cli_.Get("/streamed-chunked", headers);
  8105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8106. EXPECT_EQ(StatusCode::OK_200, res->status);
  8107. EXPECT_EQ(std::string("123456789"), res->body);
  8108. }
  8109. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8110. Headers headers;
  8111. headers.emplace("Accept-Encoding", "br");
  8112. auto res = cli_.Get("/streamed-chunked2", headers);
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. EXPECT_EQ(std::string("123456789"), res->body);
  8116. }
  8117. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8118. cli_.set_compress(true);
  8119. auto res = cli_.Put(
  8120. "/put", 3,
  8121. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8122. sink.os << "PUT";
  8123. return true;
  8124. },
  8125. "text/plain");
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. EXPECT_EQ("PUT", res->body);
  8129. }
  8130. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8131. cli_.set_compress(true);
  8132. auto res = cli_.Put(
  8133. "/put",
  8134. [](size_t /*offset*/, DataSink &sink) {
  8135. sink.os << "PUT";
  8136. sink.done();
  8137. return true;
  8138. },
  8139. "text/plain");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. EXPECT_EQ("PUT", res->body);
  8143. }
  8144. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8145. cli_.set_compress(true);
  8146. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8148. EXPECT_EQ(StatusCode::OK_200, res->status);
  8149. EXPECT_EQ(LARGE_DATA, res->body);
  8150. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8151. }
  8152. #endif
  8153. TEST_F(ServerTest, Patch) {
  8154. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. EXPECT_EQ(StatusCode::OK_200, res->status);
  8157. EXPECT_EQ("PATCH", res->body);
  8158. }
  8159. TEST_F(ServerTest, Delete) {
  8160. auto res = cli_.Delete("/delete");
  8161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8162. EXPECT_EQ(StatusCode::OK_200, res->status);
  8163. EXPECT_EQ("DELETE", res->body);
  8164. }
  8165. TEST_F(ServerTest, DeleteContentReceiver) {
  8166. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::OK_200, res->status);
  8169. EXPECT_EQ("content", res->body);
  8170. }
  8171. TEST_F(ServerTest, Options) {
  8172. auto res = cli_.Options("*");
  8173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8174. EXPECT_EQ(StatusCode::OK_200, res->status);
  8175. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8176. EXPECT_TRUE(res->body.empty());
  8177. }
  8178. TEST_F(ServerTest, URL) {
  8179. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::OK_200, res->status);
  8182. }
  8183. TEST_F(ServerTest, ArrayParam) {
  8184. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8186. EXPECT_EQ(StatusCode::OK_200, res->status);
  8187. }
  8188. TEST_F(ServerTest, ArrayParamValues) {
  8189. auto res =
  8190. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. }
  8194. TEST_F(ServerTest, NoMultipleHeaders) {
  8195. Headers headers = {{"Content-Length", "5"}};
  8196. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8197. "text/plain");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. }
  8201. TEST_F(ServerTest, PostContentReceiver) {
  8202. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8204. ASSERT_EQ(StatusCode::OK_200, res->status);
  8205. ASSERT_EQ("content", res->body);
  8206. }
  8207. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8208. UploadFormDataItems items = {
  8209. {"text1", "text default", "", ""},
  8210. {"text2", "aωb", "", ""},
  8211. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8212. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8213. {"file3", "", "", "application/octet-stream"},
  8214. };
  8215. auto res = cli_.Post("/content_receiver", items);
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. }
  8219. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8220. UploadFormDataItems items = {
  8221. {"text1", "text default", "", ""},
  8222. {"text2", "aωb", "", ""},
  8223. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8224. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8225. {"file3", "", "", "application/octet-stream"},
  8226. };
  8227. auto boundary = std::string("+++++");
  8228. std::string body;
  8229. for (const auto &item : items) {
  8230. body += "--" + boundary + "\r\n";
  8231. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8232. if (!item.filename.empty()) {
  8233. body += "; filename=\"" + item.filename + "\"";
  8234. }
  8235. body += "\r\n";
  8236. if (!item.content_type.empty()) {
  8237. body += "Content-Type: " + item.content_type + "\r\n";
  8238. }
  8239. body += "\r\n";
  8240. body += item.content + "\r\n";
  8241. }
  8242. body += "--" + boundary + "--\r\n";
  8243. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8244. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::OK_200, res->status);
  8247. }
  8248. TEST(MultipartFormDataTest, FieldEscaping) {
  8249. Server svr;
  8250. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8251. const ContentReader &content_reader) {
  8252. ASSERT_TRUE(req.is_multipart_form_data());
  8253. std::vector<FormData> received;
  8254. content_reader(
  8255. [&](const FormData &file) {
  8256. received.push_back(file);
  8257. return true;
  8258. },
  8259. [&](const char *data, size_t data_length) {
  8260. received.back().content.append(data, data_length);
  8261. return true;
  8262. });
  8263. // '"', CR and LF in names and filenames are escaped following the
  8264. // WHATWG HTML standard, so each part still parses as a single part
  8265. // with no injected headers. Content types get CR/LF escaped too,
  8266. // while '"' (legal there, e.g. quoted charset) is preserved.
  8267. ASSERT_EQ(4U, received.size());
  8268. EXPECT_EQ("na%22me", received[0].name);
  8269. EXPECT_EQ("quoted name", received[0].content);
  8270. EXPECT_EQ("file", received[1].name);
  8271. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8272. received[1].filename);
  8273. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8274. EXPECT_EQ("injected", received[1].content);
  8275. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8276. EXPECT_EQ("my%22file.txt", received[2].filename);
  8277. EXPECT_EQ("cr lf name", received[2].content);
  8278. EXPECT_EQ("typed", received[3].name);
  8279. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8280. received[3].content_type);
  8281. EXPECT_EQ("typed content", received[3].content);
  8282. });
  8283. auto port = svr.bind_to_any_port("localhost");
  8284. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8285. auto se = detail::scope_exit([&] {
  8286. svr.stop();
  8287. t.join();
  8288. ASSERT_FALSE(svr.is_running());
  8289. });
  8290. svr.wait_until_ready();
  8291. Client cli("localhost", port);
  8292. UploadFormDataItems items = {
  8293. {"na\"me", "quoted name", "", ""},
  8294. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8295. "application/octet-stream"},
  8296. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8297. {"typed", "typed content", "",
  8298. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8299. };
  8300. auto res = cli.Post("/post", items);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. }
  8304. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8305. const UploadFormDataItems items = {
  8306. {"name1", "Content 1", "", ""},
  8307. {"name2", "Content 2", "file2.txt", "text/plain"},
  8308. };
  8309. Server svr;
  8310. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8311. const ContentReader &content_reader) {
  8312. ASSERT_TRUE(req.is_multipart_form_data());
  8313. std::vector<FormData> received;
  8314. content_reader(
  8315. [&](const FormData &file) {
  8316. received.push_back(file);
  8317. return true;
  8318. },
  8319. [&](const char *data, size_t data_length) {
  8320. received.back().content.append(data, data_length);
  8321. return true;
  8322. });
  8323. ASSERT_EQ(2U, received.size());
  8324. EXPECT_EQ("name1", received[0].name);
  8325. EXPECT_EQ("Content 1", received[0].content);
  8326. EXPECT_EQ("name2", received[1].name);
  8327. EXPECT_EQ("Content 2", received[1].content);
  8328. EXPECT_EQ("file2.txt", received[1].filename);
  8329. EXPECT_EQ("text/plain", received[1].content_type);
  8330. });
  8331. auto port = svr.bind_to_any_port("localhost");
  8332. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8333. auto se = detail::scope_exit([&] {
  8334. svr.stop();
  8335. t.join();
  8336. ASSERT_FALSE(svr.is_running());
  8337. });
  8338. svr.wait_until_ready();
  8339. Client cli("localhost", port);
  8340. // Whole-body serialization with a generated boundary
  8341. {
  8342. MultipartFormDataWriter writer;
  8343. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8344. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8345. writer.content_type());
  8346. auto body = writer.serialize(items);
  8347. EXPECT_EQ(body.size(), writer.content_length(items));
  8348. auto res = cli.Post("/post", body, writer.content_type());
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_EQ(StatusCode::OK_200, res->status);
  8351. }
  8352. // Per-part framing with a custom boundary via a content provider
  8353. {
  8354. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8355. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8356. MultipartFormDataWriter writer("custom-boundary_123");
  8357. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8358. std::string body;
  8359. for (const auto &item : items) {
  8360. body += writer.item_begin(item);
  8361. body += item.content;
  8362. body += MultipartFormDataWriter::item_end();
  8363. }
  8364. body += writer.finish();
  8365. EXPECT_EQ(body.size(), writer.content_length(items));
  8366. auto res = cli.Post(
  8367. "/post", body.size(),
  8368. [&](size_t offset, size_t length, DataSink &sink) {
  8369. sink.write(body.data() + offset, length);
  8370. return true;
  8371. },
  8372. writer.content_type());
  8373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8374. EXPECT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. }
  8377. TEST_F(ServerTest, PostContentReceiverGzip) {
  8378. cli_.set_compress(true);
  8379. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. ASSERT_EQ(StatusCode::OK_200, res->status);
  8382. ASSERT_EQ("content", res->body);
  8383. }
  8384. TEST_F(ServerTest, PutContentReceiver) {
  8385. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. ASSERT_EQ(StatusCode::OK_200, res->status);
  8388. ASSERT_EQ("content", res->body);
  8389. }
  8390. TEST_F(ServerTest, PatchContentReceiver) {
  8391. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8393. ASSERT_EQ(StatusCode::OK_200, res->status);
  8394. ASSERT_EQ("content", res->body);
  8395. }
  8396. template <typename ClientType>
  8397. void TestWithHeadersAndContentReceiver(
  8398. ClientType &cli,
  8399. std::function<Result(ClientType &, const std::string &, const Headers &,
  8400. const std::string &, const std::string &,
  8401. ContentReceiver, DownloadProgress)>
  8402. request_func) {
  8403. Headers headers;
  8404. headers.emplace("X-Custom-Header", "test-value");
  8405. std::string received_body;
  8406. auto res = request_func(
  8407. cli, "/content_receiver", headers, "content", "application/json",
  8408. [&](const char *data, size_t data_length) {
  8409. received_body.append(data, data_length);
  8410. return true;
  8411. },
  8412. nullptr);
  8413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. EXPECT_EQ("content", received_body);
  8416. }
  8417. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8418. #ifdef CPPHTTPLIB_SSL_ENABLED
  8419. using ClientT = SSLClient;
  8420. #else
  8421. using ClientT = Client;
  8422. #endif
  8423. TestWithHeadersAndContentReceiver<ClientT>(
  8424. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8425. const std::string &body, const std::string &content_type,
  8426. ContentReceiver receiver, DownloadProgress progress) {
  8427. return cli.Post(path, headers, body, content_type, receiver, progress);
  8428. });
  8429. }
  8430. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8431. #ifdef CPPHTTPLIB_SSL_ENABLED
  8432. using ClientT = SSLClient;
  8433. #else
  8434. using ClientT = Client;
  8435. #endif
  8436. TestWithHeadersAndContentReceiver<ClientT>(
  8437. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8438. const std::string &body, const std::string &content_type,
  8439. ContentReceiver receiver, DownloadProgress progress) {
  8440. return cli.Put(path, headers, body, content_type, receiver, progress);
  8441. });
  8442. }
  8443. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8444. #ifdef CPPHTTPLIB_SSL_ENABLED
  8445. using ClientT = SSLClient;
  8446. #else
  8447. using ClientT = Client;
  8448. #endif
  8449. TestWithHeadersAndContentReceiver<ClientT>(
  8450. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8451. const std::string &body, const std::string &content_type,
  8452. ContentReceiver receiver, DownloadProgress progress) {
  8453. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8454. });
  8455. }
  8456. template <typename ClientType>
  8457. void TestWithHeadersAndContentReceiverWithProgress(
  8458. ClientType &cli,
  8459. std::function<Result(ClientType &, const std::string &, const Headers &,
  8460. const std::string &, const std::string &,
  8461. ContentReceiver, DownloadProgress)>
  8462. request_func) {
  8463. Headers headers;
  8464. headers.emplace("X-Test-Header", "progress-test");
  8465. std::string received_body;
  8466. auto progress_called = false;
  8467. auto res = request_func(
  8468. cli, "/content_receiver", headers, "content", "text/plain",
  8469. [&](const char *data, size_t data_length) {
  8470. received_body.append(data, data_length);
  8471. return true;
  8472. },
  8473. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8474. progress_called = true;
  8475. return true;
  8476. });
  8477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8478. EXPECT_EQ(StatusCode::OK_200, res->status);
  8479. EXPECT_EQ("content", received_body);
  8480. EXPECT_TRUE(progress_called);
  8481. }
  8482. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8483. #ifdef CPPHTTPLIB_SSL_ENABLED
  8484. using ClientT = SSLClient;
  8485. #else
  8486. using ClientT = Client;
  8487. #endif
  8488. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8489. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8490. const std::string &body, const std::string &content_type,
  8491. ContentReceiver receiver, DownloadProgress progress) {
  8492. return cli.Post(path, headers, body, content_type, receiver, progress);
  8493. });
  8494. }
  8495. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8496. #ifdef CPPHTTPLIB_SSL_ENABLED
  8497. using ClientT = SSLClient;
  8498. #else
  8499. using ClientT = Client;
  8500. #endif
  8501. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8502. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8503. const std::string &body, const std::string &content_type,
  8504. ContentReceiver receiver, DownloadProgress progress) {
  8505. return cli.Put(path, headers, body, content_type, receiver, progress);
  8506. });
  8507. }
  8508. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8509. #ifdef CPPHTTPLIB_SSL_ENABLED
  8510. using ClientT = SSLClient;
  8511. #else
  8512. using ClientT = Client;
  8513. #endif
  8514. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8515. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8516. const std::string &body, const std::string &content_type,
  8517. ContentReceiver receiver, DownloadProgress progress) {
  8518. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8519. });
  8520. }
  8521. template <typename ClientType>
  8522. void TestWithHeadersAndContentReceiverError(
  8523. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8524. const Headers &, const std::string &,
  8525. const std::string &, ContentReceiver)>
  8526. request_func) {
  8527. Headers headers;
  8528. headers.emplace("X-Error-Test", "true");
  8529. std::string received_body;
  8530. auto receiver_failed = false;
  8531. auto res =
  8532. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8533. [&](const char *data, size_t data_length) {
  8534. received_body.append(data, data_length);
  8535. receiver_failed = true;
  8536. return false;
  8537. });
  8538. ASSERT_FALSE(res);
  8539. EXPECT_TRUE(receiver_failed);
  8540. }
  8541. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8542. #ifdef CPPHTTPLIB_SSL_ENABLED
  8543. using ClientT = SSLClient;
  8544. #else
  8545. using ClientT = Client;
  8546. #endif
  8547. TestWithHeadersAndContentReceiverError<ClientT>(
  8548. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8549. const std::string &body, const std::string &content_type,
  8550. ContentReceiver receiver) {
  8551. return cli.Post(path, headers, body, content_type, receiver);
  8552. });
  8553. }
  8554. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8555. #ifdef CPPHTTPLIB_SSL_ENABLED
  8556. using ClientT = SSLClient;
  8557. #else
  8558. using ClientT = Client;
  8559. #endif
  8560. TestWithHeadersAndContentReceiverError<ClientT>(
  8561. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8562. const std::string &body, const std::string &content_type,
  8563. ContentReceiver receiver) {
  8564. return cli.Put(path, headers, body, content_type, receiver);
  8565. });
  8566. }
  8567. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8568. #ifdef CPPHTTPLIB_SSL_ENABLED
  8569. using ClientT = SSLClient;
  8570. #else
  8571. using ClientT = Client;
  8572. #endif
  8573. TestWithHeadersAndContentReceiverError<ClientT>(
  8574. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8575. const std::string &body, const std::string &content_type,
  8576. ContentReceiver receiver) {
  8577. return cli.Patch(path, headers, body, content_type, receiver);
  8578. });
  8579. }
  8580. TEST_F(ServerTest, PostQueryStringAndBody) {
  8581. auto res =
  8582. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. ASSERT_EQ(StatusCode::OK_200, res->status);
  8585. }
  8586. TEST_F(ServerTest, HTTP2Magic) {
  8587. Request req;
  8588. req.method = "PRI";
  8589. req.path = "*";
  8590. req.body = "SM";
  8591. auto res = std::make_shared<Response>();
  8592. auto error = Error::Success;
  8593. auto ret = cli_.send(req, *res, error);
  8594. ASSERT_TRUE(ret);
  8595. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8596. }
  8597. TEST_F(ServerTest, KeepAlive) {
  8598. auto res = cli_.Get("/hi");
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::OK_200, res->status);
  8601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8602. EXPECT_EQ("Hello World!", res->body);
  8603. res = cli_.Get("/hi");
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(StatusCode::OK_200, res->status);
  8606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("Hello World!", res->body);
  8608. res = cli_.Get("/hi");
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(StatusCode::OK_200, res->status);
  8611. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8612. EXPECT_EQ("Hello World!", res->body);
  8613. res = cli_.Get("/not-exist");
  8614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8616. res = cli_.Post("/empty", "", "text/plain");
  8617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8618. EXPECT_EQ(StatusCode::OK_200, res->status);
  8619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8620. EXPECT_EQ("empty", res->body);
  8621. EXPECT_EQ("close", res->get_header_value("Connection"));
  8622. res = cli_.Post(
  8623. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8624. "text/plain");
  8625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8626. EXPECT_EQ(StatusCode::OK_200, res->status);
  8627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8628. EXPECT_EQ("empty", res->body);
  8629. cli_.set_keep_alive(false);
  8630. res = cli_.Get("/last-request");
  8631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8632. EXPECT_EQ(StatusCode::OK_200, res->status);
  8633. EXPECT_EQ("close", res->get_header_value("Connection"));
  8634. }
  8635. TEST_F(ServerTest, TooManyRedirect) {
  8636. cli_.set_follow_location(true);
  8637. auto res = cli_.Get("/redirect/0");
  8638. ASSERT_TRUE(!res);
  8639. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8640. }
  8641. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8642. Request req;
  8643. req.method = "FOOBAR";
  8644. req.path = "/hi";
  8645. cli_.set_keep_alive(true);
  8646. auto res = cli_.send(req);
  8647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8648. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8649. EXPECT_EQ("close", res->get_header_value("Connection"));
  8650. EXPECT_FALSE(cli_.is_socket_open());
  8651. }
  8652. TEST_F(ServerTest, CustomRouteReadsBody) {
  8653. const std::string xml =
  8654. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8655. Request req;
  8656. req.method = "PROPFIND";
  8657. req.path = "/dav/dir";
  8658. req.set_header("Depth", "1");
  8659. req.body = xml;
  8660. auto res = cli_.send(req);
  8661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8662. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8663. EXPECT_EQ(xml, res->body);
  8664. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8665. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8666. }
  8667. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8668. Request req;
  8669. req.method = "PROPFIND";
  8670. req.path = "/dav/42";
  8671. auto res = cli_.send(req);
  8672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8673. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8674. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8675. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8676. }
  8677. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8678. Request req;
  8679. req.method = "PROPFIND";
  8680. req.path = "/dav-re/123";
  8681. auto res = cli_.send(req);
  8682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8683. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8684. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8685. }
  8686. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8687. Request req;
  8688. req.method = "MKCOL";
  8689. req.path = "/dav-mkcol";
  8690. auto res = cli_.send(req);
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::Created_201, res->status);
  8693. }
  8694. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8695. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8696. Request req;
  8697. req.method = "REPORT";
  8698. req.path = "/dav-report";
  8699. req.body = xml;
  8700. auto res = cli_.send(req);
  8701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8702. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8703. EXPECT_EQ(xml, res->body);
  8704. }
  8705. // A content reader route must fire even when the request carries no body,
  8706. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8707. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8708. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8709. Request req;
  8710. req.method = "REPORT";
  8711. req.path = "/dav-report";
  8712. auto res = cli_.send(req);
  8713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8714. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8715. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8716. }
  8717. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8718. Request req;
  8719. req.method = "PROPFIND";
  8720. req.path = "/not-dav";
  8721. auto res = cli_.send(req);
  8722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8724. }
  8725. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8726. Request req;
  8727. req.method = "UNLOCK";
  8728. req.path = "/dav/dir";
  8729. cli_.set_keep_alive(true);
  8730. auto res = cli_.send(req);
  8731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8732. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8733. EXPECT_EQ("close", res->get_header_value("Connection"));
  8734. EXPECT_FALSE(cli_.is_socket_open());
  8735. }
  8736. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8737. // The mount point serves this path, but only for GET and HEAD.
  8738. auto get_res = cli_.Get("/dir/index.html");
  8739. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8740. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8741. Request req;
  8742. req.method = "PROPFIND";
  8743. req.path = "/dir/index.html";
  8744. auto res = cli_.send(req);
  8745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8746. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8747. }
  8748. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8749. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8750. cli_.set_keep_alive(true);
  8751. for (auto i = 0; i < 2; i++) {
  8752. Request req;
  8753. req.method = "PROPFIND";
  8754. req.path = "/dav/dir";
  8755. req.body = xml;
  8756. auto res = cli_.send(req);
  8757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8758. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8759. EXPECT_EQ(xml, res->body);
  8760. EXPECT_TRUE(cli_.is_socket_open());
  8761. }
  8762. // A built-in method must still be served on the same connection.
  8763. cli_.set_keep_alive(false);
  8764. auto res = cli_.Get("/hi");
  8765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8766. EXPECT_EQ(StatusCode::OK_200, res->status);
  8767. EXPECT_EQ("close", res->get_header_value("Connection"));
  8768. }
  8769. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8770. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8771. Request req;
  8772. req.method = "PROPFIND";
  8773. req.path = "/dav/dir";
  8774. req.set_header("Expect", "100-continue");
  8775. req.body = xml;
  8776. auto res = cli_.send(req);
  8777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8778. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8779. EXPECT_EQ(xml, res->body);
  8780. }
  8781. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8782. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8783. TEST_F(ServerTest, Gzip) {
  8784. Headers headers;
  8785. headers.emplace("Accept-Encoding", "gzip, deflate");
  8786. auto res = cli_.Get("/compress", headers);
  8787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8788. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8789. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8790. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8791. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8792. "7890123456789012345678901234567890",
  8793. res->body);
  8794. EXPECT_EQ(StatusCode::OK_200, res->status);
  8795. }
  8796. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8797. Headers headers;
  8798. headers.emplace("Accept-Encoding", "gzip, deflate");
  8799. auto res = cli_.Get("/compress-with-charset", headers);
  8800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8801. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8802. EXPECT_EQ("application/json; charset=utf-8",
  8803. res->get_header_value("Content-Type"));
  8804. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8805. "7890123456789012345678901234567890",
  8806. res->body);
  8807. EXPECT_EQ(StatusCode::OK_200, res->status);
  8808. }
  8809. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8810. Headers headers;
  8811. headers.emplace("Accept-Encoding", "");
  8812. auto res = cli_.Get("/compress", headers);
  8813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8814. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8816. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8817. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8818. "7890123456789012345678901234567890",
  8819. res->body);
  8820. EXPECT_EQ(StatusCode::OK_200, res->status);
  8821. }
  8822. TEST_F(ServerTest, GzipWithContentReceiver) {
  8823. Headers headers;
  8824. headers.emplace("Accept-Encoding", "gzip, deflate");
  8825. std::string body;
  8826. auto res =
  8827. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8828. EXPECT_EQ(100U, data_length);
  8829. body.append(data, data_length);
  8830. return true;
  8831. });
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8835. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8836. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8837. "7890123456789012345678901234567890",
  8838. body);
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. }
  8841. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8842. Headers headers;
  8843. headers.emplace("Accept-Encoding", "gzip, deflate");
  8844. cli_.set_decompress(false);
  8845. auto res = cli_.Get("/compress", headers);
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8849. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8850. EXPECT_EQ(33U, res->body.size());
  8851. EXPECT_EQ(StatusCode::OK_200, res->status);
  8852. }
  8853. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8854. Headers headers;
  8855. headers.emplace("Accept-Encoding", "");
  8856. std::string body;
  8857. auto res =
  8858. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8859. EXPECT_EQ(100U, data_length);
  8860. body.append(data, data_length);
  8861. return true;
  8862. });
  8863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8864. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8866. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8867. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8868. "7890123456789012345678901234567890",
  8869. body);
  8870. EXPECT_EQ(StatusCode::OK_200, res->status);
  8871. }
  8872. TEST_F(ServerTest, NoGzip) {
  8873. Headers headers;
  8874. headers.emplace("Accept-Encoding", "gzip, deflate");
  8875. auto res = cli_.Get("/nocompress", headers);
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8878. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8879. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8880. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8881. "7890123456789012345678901234567890",
  8882. res->body);
  8883. EXPECT_EQ(StatusCode::OK_200, res->status);
  8884. }
  8885. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8886. Headers headers;
  8887. headers.emplace("Accept-Encoding", "gzip, deflate");
  8888. std::string body;
  8889. auto res = cli_.Get("/nocompress", headers,
  8890. [&](const char *data, size_t data_length) {
  8891. EXPECT_EQ(100U, data_length);
  8892. body.append(data, data_length);
  8893. return true;
  8894. });
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8897. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8898. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8899. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8900. "7890123456789012345678901234567890",
  8901. body);
  8902. EXPECT_EQ(StatusCode::OK_200, res->status);
  8903. }
  8904. TEST_F(ServerTest, MultipartFormDataGzip) {
  8905. UploadFormDataItems items = {
  8906. {"key1", "test", "", ""},
  8907. {"key2", "--abcdefg123", "", ""},
  8908. };
  8909. cli_.set_compress(true);
  8910. auto res = cli_.Post("/compress-multipart", items);
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. #endif
  8915. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8916. // Static file compression is opt-in, so these run their own server rather than
  8917. // flipping it on for the shared ServerTest fixture, which would silently
  8918. // rewrite what every other static file test is asserting.
  8919. class StaticFileCompressionTest : public ::testing::Test {
  8920. protected:
  8921. void TearDown() override {
  8922. if (t_.joinable()) {
  8923. svr_.stop();
  8924. t_.join();
  8925. }
  8926. }
  8927. int start(const std::function<void(Server &)> &configure = nullptr) {
  8928. // Serves the same tree as a directory of build-time compressed assets
  8929. // would be served: the mount point names the coding the files are already
  8930. // stored in. Registered before "/" so it is the one that matches.
  8931. svr_.set_mount_point("/pre-encoded", "./www",
  8932. {{"Content-Encoding", "gzip"}});
  8933. svr_.set_mount_point("/", "./www");
  8934. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8935. res.set_file_content("./www/dir/index.html", "text/html");
  8936. });
  8937. svr_.Get("/pre-encoded-file-content",
  8938. [](const Request & /*req*/, Response &res) {
  8939. res.set_header("Content-Encoding", "gzip");
  8940. res.set_file_content("./www/dir/index.html", "text/html");
  8941. });
  8942. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8943. res.set_content_provider(
  8944. 6, "text/plain",
  8945. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8946. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8947. return true;
  8948. });
  8949. });
  8950. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8951. res.set_content_provider(
  8952. 1000, "text/plain",
  8953. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8954. if (offset < 100) {
  8955. std::string data(100, 'A');
  8956. sink.write(data.data(), data.size());
  8957. return true;
  8958. }
  8959. std::this_thread::sleep_for(std::chrono::seconds(2));
  8960. std::string data(900, 'B');
  8961. sink.write(data.data(), data.size());
  8962. return true;
  8963. });
  8964. });
  8965. if (configure) { configure(svr_); }
  8966. auto port = svr_.bind_to_any_port(HOST);
  8967. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8968. svr_.wait_until_ready();
  8969. return port;
  8970. }
  8971. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8972. // Every file under ./www except 1MB.txt is smaller than the default
  8973. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8974. // it out of the way.
  8975. static void enable_without_floor(Server &svr) {
  8976. svr.set_static_file_compression(true);
  8977. svr.set_static_file_compression_min_length(0);
  8978. }
  8979. Server svr_;
  8980. std::thread t_;
  8981. };
  8982. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8983. auto port = start();
  8984. Client cli(HOST, port);
  8985. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_EQ(StatusCode::OK_200, res->status);
  8988. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8989. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8990. EXPECT_EQ(1048576U, res->body.size());
  8991. }
  8992. TEST_F(StaticFileCompressionTest, MountPoint) {
  8993. auto port = start(enable);
  8994. Client cli(HOST, port);
  8995. cli.set_decompress(false);
  8996. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8998. EXPECT_EQ(StatusCode::OK_200, res->status);
  8999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9000. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9001. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9002. // The response stays self-delimiting: a length, not a chunked body.
  9003. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9004. EXPECT_EQ(std::to_string(res->body.size()),
  9005. res->get_header_value("Content-Length"));
  9006. EXPECT_LT(res->body.size(), 1048576U);
  9007. EXPECT_FALSE(res->body.empty());
  9008. }
  9009. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9010. auto port = start(enable);
  9011. Client cli(HOST, port);
  9012. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9014. EXPECT_EQ(StatusCode::OK_200, res->status);
  9015. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9016. EXPECT_EQ(1048576U, res->body.size());
  9017. }
  9018. TEST_F(StaticFileCompressionTest, FileContent) {
  9019. auto port = start(enable_without_floor);
  9020. Client cli(HOST, port);
  9021. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9023. EXPECT_EQ(StatusCode::OK_200, res->status);
  9024. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9025. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9026. EXPECT_EQ(104U, res->body.size());
  9027. }
  9028. // A handler that serves an already-encoded file names the coding itself. The
  9029. // file-backed path decided its coding from Accept-Encoding and the content
  9030. // type alone, so it compressed the stored bytes a second time and appended a
  9031. // second Content-Encoding field line.
  9032. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9033. auto port = start(enable_without_floor);
  9034. Client cli(HOST, port);
  9035. cli.set_decompress(false);
  9036. auto res = cli.Get("/pre-encoded-file-content",
  9037. Headers{{"Accept-Encoding", "gzip"}});
  9038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9039. EXPECT_EQ(StatusCode::OK_200, res->status);
  9040. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9041. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9042. // Vary belongs to a coding the server chose, and it chose none here.
  9043. EXPECT_FALSE(res->has_header("Vary"));
  9044. // The file travels exactly as it is stored on disk.
  9045. EXPECT_EQ(104U, res->body.size());
  9046. }
  9047. // The 1MB file clears the default floor, so this one runs the configuration a
  9048. // deployment would actually have.
  9049. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9050. auto port = start(enable);
  9051. Client cli(HOST, port);
  9052. cli.set_decompress(false);
  9053. auto res =
  9054. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9058. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9059. EXPECT_FALSE(res->has_header("Vary"));
  9060. EXPECT_EQ(1048576U, res->body.size());
  9061. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9062. }
  9063. TEST_F(StaticFileCompressionTest, Head) {
  9064. auto port = start(enable);
  9065. Client cli(HOST, port);
  9066. cli.set_decompress(false);
  9067. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9068. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9069. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::OK_200, res->status);
  9072. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9073. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9074. // HEAD still reports the size a GET would return.
  9075. EXPECT_EQ(get->get_header_value("Content-Length"),
  9076. res->get_header_value("Content-Length"));
  9077. EXPECT_TRUE(res->body.empty());
  9078. }
  9079. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9080. auto port = start(enable);
  9081. Client cli(HOST, port);
  9082. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9083. {"Accept-Encoding", "gzip"}});
  9084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9086. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9087. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9088. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9089. EXPECT_EQ("cd", res->body);
  9090. }
  9091. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9092. auto port = start(enable);
  9093. Client cli(HOST, port);
  9094. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9096. EXPECT_EQ(StatusCode::OK_200, res->status);
  9097. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9098. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9099. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9100. }
  9101. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9102. auto port = start(enable);
  9103. Client cli(HOST, port);
  9104. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9106. EXPECT_EQ(StatusCode::OK_200, res->status);
  9107. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9108. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9109. EXPECT_TRUE(res->body.empty());
  9110. }
  9111. TEST_F(StaticFileCompressionTest, MinLength) {
  9112. auto port = start(enable);
  9113. Client cli(HOST, port);
  9114. // 104 bytes, well under the default floor. Compressing it would add the
  9115. // gzip header and trailer to a body that already fits in one packet.
  9116. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9118. EXPECT_EQ(StatusCode::OK_200, res->status);
  9119. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9120. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9121. }
  9122. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9123. auto port = start([](Server &svr) {
  9124. svr.set_static_file_compression(true);
  9125. svr.set_static_file_compression_min_length(1);
  9126. });
  9127. Client cli(HOST, port);
  9128. cli.set_decompress(false);
  9129. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9131. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9132. // A 9-byte file comes back larger than it went in, because gzip's header and
  9133. // trailer outweigh anything deflate can save. That is the end of the range
  9134. // the floor exists to keep out.
  9135. EXPECT_GT(res->body.size(), 9U);
  9136. }
  9137. TEST_F(StaticFileCompressionTest, MaxLength) {
  9138. auto port = start([](Server &svr) {
  9139. svr.set_static_file_compression(true);
  9140. svr.set_static_file_compression_min_length(0);
  9141. svr.set_static_file_compression_max_length(1024);
  9142. });
  9143. Client cli(HOST, port);
  9144. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9145. // defines `small` as a macro on Windows.
  9146. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9147. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9148. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9149. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9150. // Under it: compressed.
  9151. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9152. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9153. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9154. }
  9155. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9156. auto port = start(enable_without_floor);
  9157. Client cli(HOST, port);
  9158. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9159. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9160. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9161. auto identity_etag = identity->get_header_value("ETag");
  9162. ASSERT_FALSE(identity_etag.empty());
  9163. auto gzipped =
  9164. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9165. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9166. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9167. auto gzip_etag = gzipped->get_header_value("ETag");
  9168. ASSERT_FALSE(gzip_etag.empty());
  9169. // Two representations, two validators.
  9170. EXPECT_NE(identity_etag, gzip_etag);
  9171. // Each one revalidates against the request that would produce it...
  9172. auto fresh =
  9173. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9174. {"If-None-Match", gzip_etag}});
  9175. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9176. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9177. auto fresh_identity =
  9178. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9179. {"If-None-Match", identity_etag}});
  9180. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9181. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9182. // ...and not against the other representation.
  9183. auto crossed =
  9184. cli.Get("/dir/index.html",
  9185. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9186. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9187. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9188. }
  9189. // The opt-in covers responses the server reads off disk itself. A caller's own
  9190. // known-length provider keeps its Content-Length and, more importantly, keeps
  9191. // delivering incrementally: routing it through a compressor would hold every
  9192. // write back until zlib's window filled.
  9193. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9194. auto port = start(enable);
  9195. Client cli(HOST, port);
  9196. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9198. EXPECT_EQ(StatusCode::OK_200, res->status);
  9199. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9200. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9201. EXPECT_EQ("aaabbb", res->body);
  9202. }
  9203. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9204. auto port = start(enable);
  9205. Client cli(HOST, port);
  9206. cli.set_read_timeout(1, 0);
  9207. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9208. Headers{{"Accept-Encoding", "gzip"}});
  9209. ASSERT_TRUE(handle.is_valid());
  9210. // The provider writes 100 bytes and then stalls for longer than the read
  9211. // timeout. Those first bytes have to arrive anyway: run the response through
  9212. // a compressor and zlib holds them until its window fills, so the read would
  9213. // come back empty instead.
  9214. char buf[256];
  9215. auto n = handle.read(buf, sizeof(buf));
  9216. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9217. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9218. }
  9219. #endif
  9220. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9221. TEST_F(ServerTest, Brotli) {
  9222. Headers headers;
  9223. headers.emplace("Accept-Encoding", "br");
  9224. auto res = cli_.Get("/compress", headers);
  9225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9226. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9228. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9229. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9230. "7890123456789012345678901234567890",
  9231. res->body);
  9232. EXPECT_EQ(StatusCode::OK_200, res->status);
  9233. }
  9234. #endif
  9235. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9236. TEST_F(ServerTest, Zstd) {
  9237. Headers headers;
  9238. headers.emplace("Accept-Encoding", "zstd");
  9239. auto res = cli_.Get("/compress", headers);
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9242. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9243. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9244. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9245. "7890123456789012345678901234567890",
  9246. res->body);
  9247. EXPECT_EQ(StatusCode::OK_200, res->status);
  9248. }
  9249. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9250. Headers headers;
  9251. headers.emplace("Accept-Encoding", "");
  9252. auto res = cli_.Get("/compress", headers);
  9253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9254. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9256. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9257. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9258. "7890123456789012345678901234567890",
  9259. res->body);
  9260. EXPECT_EQ(StatusCode::OK_200, res->status);
  9261. }
  9262. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9263. Headers headers;
  9264. headers.emplace("Accept-Encoding", "zstd");
  9265. std::string body;
  9266. auto res =
  9267. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9268. EXPECT_EQ(100U, data_length);
  9269. body.append(data, data_length);
  9270. return true;
  9271. });
  9272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9273. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9274. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9275. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9276. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9277. "7890123456789012345678901234567890",
  9278. body);
  9279. EXPECT_EQ(StatusCode::OK_200, res->status);
  9280. }
  9281. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9282. Headers headers;
  9283. headers.emplace("Accept-Encoding", "zstd");
  9284. cli_.set_decompress(false);
  9285. auto res = cli_.Get("/compress", headers);
  9286. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9287. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9288. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9289. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9291. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9293. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9294. EXPECT_EQ(StatusCode::OK_200, res->status);
  9295. ASSERT_EQ(26U, res->body.size());
  9296. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9297. 0);
  9298. }
  9299. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9300. Headers headers;
  9301. headers.emplace("Accept-Encoding", "");
  9302. std::string body;
  9303. auto res =
  9304. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9305. EXPECT_EQ(100U, data_length);
  9306. body.append(data, data_length);
  9307. return true;
  9308. });
  9309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9310. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9312. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9313. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9314. "7890123456789012345678901234567890",
  9315. body);
  9316. EXPECT_EQ(StatusCode::OK_200, res->status);
  9317. }
  9318. TEST_F(ServerTest, NoZstd) {
  9319. Headers headers;
  9320. headers.emplace("Accept-Encoding", "zstd");
  9321. auto res = cli_.Get("/nocompress", headers);
  9322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9323. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9324. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9325. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9326. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9327. "7890123456789012345678901234567890",
  9328. res->body);
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. }
  9331. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9332. Headers headers;
  9333. headers.emplace("Accept-Encoding", "zstd");
  9334. std::string body;
  9335. auto res = cli_.Get("/nocompress", headers,
  9336. [&](const char *data, size_t data_length) {
  9337. EXPECT_EQ(100U, data_length);
  9338. body.append(data, data_length);
  9339. return true;
  9340. });
  9341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9342. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9343. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9344. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9345. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9346. "7890123456789012345678901234567890",
  9347. body);
  9348. EXPECT_EQ(StatusCode::OK_200, res->status);
  9349. }
  9350. // TODO: How to enable zstd ??
  9351. TEST_F(ServerTest, MultipartFormDataZstd) {
  9352. UploadFormDataItems items = {
  9353. {"key1", "test", "", ""},
  9354. {"key2", "--abcdefg123", "", ""},
  9355. };
  9356. Headers headers;
  9357. headers.emplace("Accept-Encoding", "zstd");
  9358. cli_.set_compress(true);
  9359. auto res = cli_.Post("/compress-multipart", headers, items);
  9360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9361. EXPECT_EQ(StatusCode::OK_200, res->status);
  9362. }
  9363. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9364. Headers headers;
  9365. headers.emplace("Accept-Encoding", "zstd");
  9366. cli_.set_compress(true);
  9367. auto res = cli_.Put(
  9368. "/put", headers, 3,
  9369. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9370. sink.os << "PUT";
  9371. return true;
  9372. },
  9373. "text/plain");
  9374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9375. EXPECT_EQ(StatusCode::OK_200, res->status);
  9376. EXPECT_EQ("PUT", res->body);
  9377. }
  9378. // Pre-compression logging tests
  9379. TEST_F(ServerTest, PreCompressionLogging) {
  9380. // Test data for compression (matches the actual /compress endpoint content)
  9381. const std::string test_content =
  9382. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9383. "3456789012345678901234567890";
  9384. // Variables to capture logging data
  9385. std::string pre_compression_body;
  9386. std::string pre_compression_content_type;
  9387. std::string pre_compression_content_encoding;
  9388. std::string post_compression_body;
  9389. std::string post_compression_content_type;
  9390. std::string post_compression_content_encoding;
  9391. // Set up pre-compression logger
  9392. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9393. const Response &res) {
  9394. pre_compression_body = res.body;
  9395. pre_compression_content_type = res.get_header_value("Content-Type");
  9396. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9397. });
  9398. // Set up post-compression logger
  9399. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9400. post_compression_body = res.body;
  9401. post_compression_content_type = res.get_header_value("Content-Type");
  9402. post_compression_content_encoding =
  9403. res.get_header_value("Content-Encoding");
  9404. });
  9405. // Test with gzip compression
  9406. Headers headers;
  9407. headers.emplace("Accept-Encoding", "gzip");
  9408. auto res = cli_.Get("/compress", headers);
  9409. // Verify response was compressed
  9410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9411. EXPECT_EQ(StatusCode::OK_200, res->status);
  9412. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9413. // Verify pre-compression logger captured uncompressed content
  9414. EXPECT_EQ(test_content, pre_compression_body);
  9415. EXPECT_EQ("text/plain", pre_compression_content_type);
  9416. EXPECT_TRUE(pre_compression_content_encoding
  9417. .empty()); // No encoding header before compression
  9418. // Verify post-compression logger captured compressed content
  9419. EXPECT_NE(test_content,
  9420. post_compression_body); // Should be different after compression
  9421. EXPECT_EQ("text/plain", post_compression_content_type);
  9422. EXPECT_EQ("gzip", post_compression_content_encoding);
  9423. // Verify compressed content is smaller
  9424. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9425. }
  9426. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9427. const std::string test_content =
  9428. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9429. "3456789012345678901234567890";
  9430. std::string pre_compression_body;
  9431. std::string post_compression_body;
  9432. svr_.set_pre_compression_logger(
  9433. [&](const Request & /*req*/, const Response &res) {
  9434. pre_compression_body = res.body;
  9435. });
  9436. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9437. post_compression_body = res.body;
  9438. });
  9439. Headers headers;
  9440. headers.emplace("Accept-Encoding", "br");
  9441. auto res = cli_.Get("/compress", headers);
  9442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9443. EXPECT_EQ(StatusCode::OK_200, res->status);
  9444. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9445. // Verify pre-compression content is uncompressed
  9446. EXPECT_EQ(test_content, pre_compression_body);
  9447. // Verify post-compression content is compressed
  9448. EXPECT_NE(test_content, post_compression_body);
  9449. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9450. }
  9451. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9452. const std::string test_content =
  9453. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9454. "3456789012345678901234567890";
  9455. std::string pre_compression_body;
  9456. std::string post_compression_body;
  9457. svr_.set_pre_compression_logger(
  9458. [&](const Request & /*req*/, const Response &res) {
  9459. pre_compression_body = res.body;
  9460. });
  9461. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9462. post_compression_body = res.body;
  9463. });
  9464. // Request without compression (use /nocompress endpoint)
  9465. Headers headers;
  9466. auto res = cli_.Get("/nocompress", headers);
  9467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9468. EXPECT_EQ(StatusCode::OK_200, res->status);
  9469. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9470. // Pre-compression logger should not be called when no compression is applied
  9471. EXPECT_TRUE(
  9472. pre_compression_body.empty()); // Pre-compression logger not called
  9473. EXPECT_EQ(
  9474. test_content,
  9475. post_compression_body); // Post-compression logger captures final content
  9476. }
  9477. TEST_F(ServerTest, LoggerSeesContentLength) {
  9478. size_t logged_content_length = 0;
  9479. std::string logged_content_length_header;
  9480. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9481. logged_content_length = res.content_length_;
  9482. logged_content_length_header = res.get_header_value("Content-Length");
  9483. });
  9484. auto res = cli_.Get("/nocompress");
  9485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9486. EXPECT_EQ(StatusCode::OK_200, res->status);
  9487. EXPECT_EQ(res->body.size(), logged_content_length);
  9488. EXPECT_EQ(std::to_string(logged_content_length),
  9489. logged_content_length_header);
  9490. }
  9491. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9492. const std::string test_content =
  9493. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9494. "3456789012345678901234567890";
  9495. std::string pre_compression_body;
  9496. bool pre_logger_called = false;
  9497. // Set only pre-compression logger
  9498. svr_.set_pre_compression_logger(
  9499. [&](const Request & /*req*/, const Response &res) {
  9500. pre_compression_body = res.body;
  9501. pre_logger_called = true;
  9502. });
  9503. Headers headers;
  9504. headers.emplace("Accept-Encoding", "gzip");
  9505. auto res = cli_.Get("/compress", headers);
  9506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9507. EXPECT_EQ(StatusCode::OK_200, res->status);
  9508. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9509. // Verify pre-compression logger was called
  9510. EXPECT_TRUE(pre_logger_called);
  9511. EXPECT_EQ(test_content, pre_compression_body);
  9512. }
  9513. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9514. {
  9515. // Test with Expect: 100-continue header - success case
  9516. // Server returns 100 Continue, client sends body, server returns 200 OK
  9517. Request req;
  9518. req.method = "POST";
  9519. req.path = "/post-large";
  9520. req.set_header("Expect", "100-continue");
  9521. req.body = LARGE_DATA;
  9522. Response res;
  9523. auto error = Error::Success;
  9524. cli_.set_keep_alive(true);
  9525. auto ret = cli_.send(req, res, error);
  9526. EXPECT_TRUE(ret);
  9527. EXPECT_EQ(StatusCode::OK_200, res.status);
  9528. EXPECT_EQ(LARGE_DATA, res.body);
  9529. }
  9530. {
  9531. // Test with Expect: 100-continue header - error case
  9532. // Client should not send the body when server returns an error
  9533. Request req;
  9534. req.method = "POST";
  9535. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9536. req.set_header("Expect", "100-continue");
  9537. req.body = LARGE_DATA;
  9538. Response res;
  9539. auto error = Error::Success;
  9540. auto start = std::chrono::high_resolution_clock::now();
  9541. cli_.set_keep_alive(true);
  9542. auto ret = cli_.send(req, res, error);
  9543. auto end = std::chrono::high_resolution_clock::now();
  9544. auto elapsed =
  9545. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9546. .count();
  9547. // With Expect: 100-continue, request completes successfully but with error
  9548. EXPECT_TRUE(ret);
  9549. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9550. EXPECT_EQ("close", res.get_header_value("Connection"));
  9551. EXPECT_FALSE(cli_.is_socket_open());
  9552. EXPECT_LE(elapsed, 2000);
  9553. }
  9554. {
  9555. // Send an extra GET request to ensure error recovery without hanging
  9556. Request req;
  9557. req.method = "GET";
  9558. req.path = "/hi";
  9559. auto start = std::chrono::high_resolution_clock::now();
  9560. auto res = cli_.send(req);
  9561. auto end = std::chrono::high_resolution_clock::now();
  9562. auto elapsed =
  9563. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9564. .count();
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. EXPECT_EQ(StatusCode::OK_200, res->status);
  9567. EXPECT_EQ("Hello World!", res->body);
  9568. EXPECT_LE(elapsed, 500);
  9569. }
  9570. }
  9571. TEST(ZstdDecompressor, ChunkedDecompression) {
  9572. std::string data;
  9573. for (size_t i = 0; i < 32 * 1024; ++i) {
  9574. data.push_back(static_cast<char>('a' + i % 26));
  9575. }
  9576. std::string compressed_data;
  9577. {
  9578. httplib::detail::zstd_compressor compressor;
  9579. bool result = compressor.compress(
  9580. data.data(), data.size(),
  9581. /*last=*/true,
  9582. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9583. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9584. compressed_data_size);
  9585. return true;
  9586. });
  9587. ASSERT_TRUE(result);
  9588. }
  9589. std::string decompressed_data;
  9590. {
  9591. httplib::detail::zstd_decompressor decompressor;
  9592. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9593. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9594. size_t chunk_size = 130;
  9595. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9596. chunk_begin += chunk_size) {
  9597. size_t current_chunk_size =
  9598. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9599. bool result = decompressor.decompress(
  9600. compressed_data.data() + chunk_begin, current_chunk_size,
  9601. [&](const char *decompressed_data_chunk,
  9602. size_t decompressed_data_chunk_size) {
  9603. decompressed_data.insert(decompressed_data.size(),
  9604. decompressed_data_chunk,
  9605. decompressed_data_chunk_size);
  9606. return true;
  9607. });
  9608. ASSERT_TRUE(result);
  9609. }
  9610. }
  9611. ASSERT_EQ(data, decompressed_data);
  9612. }
  9613. TEST(ZstdDecompressor, Decompress) {
  9614. std::string original_text = "Compressed with ZSTD";
  9615. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9616. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9617. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9618. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9619. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9620. std::string decompressed_data;
  9621. {
  9622. httplib::detail::zstd_decompressor decompressor;
  9623. bool result = decompressor.decompress(
  9624. compressed_data.data(), compressed_data.size(),
  9625. [&](const char *decompressed_data_chunk,
  9626. size_t decompressed_data_chunk_size) {
  9627. decompressed_data.insert(decompressed_data.size(),
  9628. decompressed_data_chunk,
  9629. decompressed_data_chunk_size);
  9630. return true;
  9631. });
  9632. ASSERT_TRUE(result);
  9633. }
  9634. ASSERT_EQ(original_text, decompressed_data);
  9635. }
  9636. #endif
  9637. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9638. // separate chunks so that the server sees each part in its own read(). Used to
  9639. // place a read boundary at a specific offset of a request body.
  9640. static bool send_request_in_parts(time_t read_timeout_sec,
  9641. const std::vector<std::string> &parts,
  9642. std::string *resp = nullptr,
  9643. int port = PORT) {
  9644. auto error = Error::Success;
  9645. auto client_sock = detail::create_client_socket(
  9646. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9647. /*connection_timeout_sec=*/5, 0,
  9648. /*read_timeout_sec=*/5, 0,
  9649. /*write_timeout_sec=*/5, 0, std::string(), error);
  9650. if (client_sock == INVALID_SOCKET) { return false; }
  9651. auto ret = detail::process_client_socket(
  9652. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9653. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9654. for (size_t i = 0; i < parts.size(); i++) {
  9655. const auto &part = parts[i];
  9656. if (part.size() !=
  9657. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9658. return false;
  9659. }
  9660. if (i + 1 < parts.size()) {
  9661. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9662. }
  9663. }
  9664. char buf[512];
  9665. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9666. while (line_reader.getline()) {
  9667. if (resp) { *resp += line_reader.ptr(); }
  9668. }
  9669. return true;
  9670. });
  9671. detail::close_socket(client_sock);
  9672. return ret;
  9673. }
  9674. // Sends a raw request to a server listening at HOST:PORT.
  9675. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9676. std::string *resp = nullptr, int port = PORT) {
  9677. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9678. }
  9679. #ifdef CPPHTTPLIB_SSL_ENABLED
  9680. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9682. ASSERT_TRUE(svr.is_valid());
  9683. svr.set_read_timeout(1, 0);
  9684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9685. auto se = detail::scope_exit([&] {
  9686. svr.stop();
  9687. t.join();
  9688. ASSERT_FALSE(svr.is_running());
  9689. });
  9690. svr.wait_until_ready();
  9691. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9692. // keeps each wait well within the read timeout. The server gives up a
  9693. // second in, so the bytes sent after that fail.
  9694. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9695. parts.resize(26, std::string(1, '\0'));
  9696. EXPECT_FALSE(send_request_in_parts(5, parts));
  9697. }
  9698. #endif
  9699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9700. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9701. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9702. const std::vector<std::string> &parts,
  9703. std::string *resp = nullptr,
  9704. int port = PORT) {
  9705. auto error = Error::Success;
  9706. auto sock = detail::create_client_socket(
  9707. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9708. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9709. /*write_timeout_sec=*/5, 0, std::string(), error);
  9710. if (sock == INVALID_SOCKET) { return false; }
  9711. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9712. auto ctx = SSL_CTX_new(TLS_client_method());
  9713. auto ssl = SSL_new(ctx);
  9714. auto ssl_se = detail::scope_exit([&] {
  9715. SSL_free(ssl);
  9716. SSL_CTX_free(ctx);
  9717. });
  9718. SSL_set_fd(ssl, static_cast<int>(sock));
  9719. if (SSL_connect(ssl) != 1) { return false; }
  9720. for (size_t i = 0; i < parts.size(); i++) {
  9721. const auto &part = parts[i];
  9722. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9723. static_cast<int>(part.size())) {
  9724. return false;
  9725. }
  9726. if (i + 1 < parts.size()) {
  9727. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9728. }
  9729. }
  9730. char buf[512];
  9731. int n;
  9732. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9733. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9734. }
  9735. return true;
  9736. }
  9737. #endif
  9738. // The request line, then a header value a byte at a time.
  9739. static std::vector<std::string> slow_request_head_parts() {
  9740. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9741. parts.resize(26, "a");
  9742. parts.emplace_back("\r\n\r\n");
  9743. return parts;
  9744. }
  9745. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9746. // within the one-second read timeout. The server gives up a second in, before
  9747. // the head is complete.
  9748. static void
  9749. expect_slow_request_head_dropped(Server &svr,
  9750. const std::function<std::string()> &send) {
  9751. std::atomic<bool> handled(false);
  9752. svr.Get("/", [&](const Request &, Response &res) {
  9753. handled = true;
  9754. res.set_content("ok", "text/plain");
  9755. });
  9756. svr.set_read_timeout(1, 0);
  9757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9758. auto se = detail::scope_exit([&] {
  9759. svr.stop();
  9760. t.join();
  9761. ASSERT_FALSE(svr.is_running());
  9762. });
  9763. svr.wait_until_ready();
  9764. auto resp = send();
  9765. EXPECT_FALSE(handled);
  9766. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9767. }
  9768. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9769. Server svr;
  9770. expect_slow_request_head_dropped(svr, [] {
  9771. std::string resp;
  9772. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9773. return resp;
  9774. });
  9775. }
  9776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9777. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9779. ASSERT_TRUE(svr.is_valid());
  9780. expect_slow_request_head_dropped(svr, [] {
  9781. std::string resp;
  9782. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9783. return resp;
  9784. });
  9785. }
  9786. #endif
  9787. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9788. Server svr;
  9789. std::string header_value;
  9790. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9791. header_value = req.get_header_value("foo");
  9792. res.set_content("ok", "text/plain");
  9793. });
  9794. thread t = thread([&] { svr.listen(HOST, PORT); });
  9795. auto se = detail::scope_exit([&] {
  9796. svr.stop();
  9797. t.join();
  9798. ASSERT_FALSE(svr.is_running());
  9799. });
  9800. svr.wait_until_ready();
  9801. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9802. // like characters are not treated the same - use vertical tab and escape.
  9803. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9804. "foo: \t \v bar \x1B\t \r\n"
  9805. "Connection: close\r\n"
  9806. "\r\n";
  9807. std::string res;
  9808. ASSERT_TRUE(send_request(5, req, &res));
  9809. EXPECT_EQ(header_value, "");
  9810. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9811. }
  9812. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9813. Server svr;
  9814. std::string received;
  9815. svr.Get("/order", [&](const Request &req, Response &res) {
  9816. received = entries_to_string(req.headers);
  9817. res.set_content("ok", "text/plain");
  9818. });
  9819. auto port = svr.bind_to_any_port(HOST);
  9820. thread t = thread([&] { svr.listen_after_bind(); });
  9821. auto se = detail::scope_exit([&] {
  9822. svr.stop();
  9823. t.join();
  9824. ASSERT_FALSE(svr.is_running());
  9825. });
  9826. svr.wait_until_ready();
  9827. const std::string req = "GET /order HTTP/1.1\r\n"
  9828. "Host: localhost\r\n"
  9829. "X-First: 1\r\n"
  9830. "X-Dup: a\r\n"
  9831. "X-Second: 2\r\n"
  9832. "X-Dup: b\r\n"
  9833. "Connection: close\r\n"
  9834. "\r\n";
  9835. std::string res;
  9836. ASSERT_TRUE(send_request(5, req, &res, port));
  9837. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9838. EXPECT_EQ(
  9839. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9840. received);
  9841. }
  9842. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9843. Server svr;
  9844. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9845. res.set_header("Set-Cookie", "first=1");
  9846. res.set_header("X-Between", "y");
  9847. res.set_header("Set-Cookie", "second=2");
  9848. res.set_content("ok", "text/plain");
  9849. });
  9850. auto port = svr.bind_to_any_port(HOST);
  9851. thread t = thread([&] { svr.listen_after_bind(); });
  9852. auto se = detail::scope_exit([&] {
  9853. svr.stop();
  9854. t.join();
  9855. ASSERT_FALSE(svr.is_running());
  9856. });
  9857. svr.wait_until_ready();
  9858. Client cli(HOST, port);
  9859. auto res = cli.Get("/cookies");
  9860. ASSERT_TRUE(res);
  9861. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9862. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9863. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9864. }
  9865. // A stream may send a byte at a time with a small extension on each chunk,
  9866. // however long it runs
  9867. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9868. Server svr;
  9869. svr.Post("/count", [](const Request &req, Response &res) {
  9870. res.set_content(std::to_string(req.body.size()), "text/plain");
  9871. });
  9872. auto port = svr.bind_to_any_port(HOST);
  9873. ASSERT_LT(0, port);
  9874. thread t = thread([&] { svr.listen_after_bind(); });
  9875. auto se = detail::scope_exit([&] {
  9876. svr.stop();
  9877. t.join();
  9878. ASSERT_FALSE(svr.is_running());
  9879. });
  9880. svr.wait_until_ready();
  9881. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9882. "\r\nTransfer-Encoding: chunked\r\n"
  9883. "Connection: close\r\n\r\n";
  9884. for (auto i = 0; i < 4096; i++) {
  9885. req += "1;a=b\r\nx\r\n";
  9886. }
  9887. req += "0\r\n\r\n";
  9888. std::string res;
  9889. ASSERT_TRUE(send_request(5, req, &res, port));
  9890. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9891. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9892. }
  9893. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9894. Server svr;
  9895. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9896. auto i = new int(0);
  9897. res.set_header("Trailer", "X-Safe, X-Reflected");
  9898. res.set_chunked_content_provider(
  9899. "text/plain",
  9900. [i](size_t /*offset*/, DataSink &sink) {
  9901. if (*i == 0) {
  9902. sink.os << "body";
  9903. } else {
  9904. Headers trailer;
  9905. // A valid trailer that must survive.
  9906. trailer.emplace("X-Safe", "safe");
  9907. // Attacker-controlled value carrying CR/LF (response splitting).
  9908. trailer.emplace("X-Reflected",
  9909. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9910. // Attacker-controlled name carrying CR/LF.
  9911. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9912. sink.done_with_trailer(trailer);
  9913. }
  9914. (*i)++;
  9915. return true;
  9916. },
  9917. [i](bool /*success*/) { delete i; });
  9918. });
  9919. thread t = thread([&] { svr.listen(HOST, PORT); });
  9920. auto se = detail::scope_exit([&] {
  9921. svr.stop();
  9922. t.join();
  9923. ASSERT_FALSE(svr.is_running());
  9924. });
  9925. svr.wait_until_ready();
  9926. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9927. "Host: " + HOST +
  9928. "\r\n"
  9929. "Connection: close\r\n"
  9930. "\r\n";
  9931. std::string res;
  9932. ASSERT_TRUE(send_request(5, req, &res));
  9933. // The injected fields must not appear anywhere in the raw response.
  9934. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9935. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9936. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9937. // Invalid trailers are dropped entirely, matching set_header().
  9938. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9939. // The valid trailer still passes through.
  9940. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9941. }
  9942. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9943. // A custom header writer gets only the fields the default one writes
  9944. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9945. std::string s;
  9946. for (const auto &h : hdrs) {
  9947. s += h.first + ": " + h.second + "\r\n";
  9948. }
  9949. s += "\r\n";
  9950. return strm.write(s.data(), s.size());
  9951. };
  9952. for (auto custom_writer : {false, true}) {
  9953. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9954. Server svr;
  9955. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9956. svr.set_post_routing_handler([](const Request &, Response &res) {
  9957. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9958. });
  9959. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9960. // res.headers is a public field an application can populate directly,
  9961. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9962. // A valid header that must survive.
  9963. res.headers.emplace("X-Safe", "safe");
  9964. // Attacker-controlled value carrying CR/LF (response splitting).
  9965. res.headers.emplace("X-Reflected",
  9966. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9967. // Attacker-controlled name carrying CR/LF.
  9968. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9969. res.set_content("body", "text/plain");
  9970. });
  9971. thread t = thread([&] { svr.listen(HOST, PORT); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. ASSERT_FALSE(svr.is_running());
  9976. });
  9977. svr.wait_until_ready();
  9978. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9979. "Host: " + HOST +
  9980. "\r\n"
  9981. "Connection: close\r\n"
  9982. "\r\n";
  9983. std::string res;
  9984. ASSERT_TRUE(send_request(5, req, &res));
  9985. // The injected fields must not appear anywhere in the raw response.
  9986. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9987. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9988. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9989. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9990. // Invalid headers are dropped entirely, matching set_header().
  9991. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9992. // The valid header still passes through.
  9993. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9994. }
  9995. }
  9996. // Forward declaration: in split builds split.py strips `inline` and moves the
  9997. // definition into httplib.cc, so detail::write_request_line is not visible from
  9998. // the public httplib.h. Re-declaring it here lets the tests link against the
  9999. // symbol in both header-only and split builds.
  10000. namespace httplib {
  10001. namespace detail {
  10002. ssize_t write_request_line(Stream &strm, const std::string &method,
  10003. const std::string &path);
  10004. } // namespace detail
  10005. } // namespace httplib
  10006. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10007. // A well-formed target is written verbatim.
  10008. {
  10009. detail::BufferStream strm;
  10010. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10011. EXPECT_GT(n, 0);
  10012. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10013. }
  10014. // A target carrying CR/LF, SP or other control octets must be rejected
  10015. // before anything reaches the wire, otherwise it splits the request line and
  10016. // injects a header or a whole request.
  10017. const std::string evil_targets[] = {
  10018. "/a\r\nInjected: pwned",
  10019. "/a\rInjected",
  10020. "/a\nInjected",
  10021. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10022. "/a b",
  10023. "/a\tb",
  10024. "/a\x7f",
  10025. };
  10026. for (const auto &evil : evil_targets) {
  10027. detail::BufferStream strm;
  10028. auto n = detail::write_request_line(strm, "GET", evil);
  10029. EXPECT_LT(n, 0);
  10030. EXPECT_TRUE(strm.get_buffer().empty());
  10031. }
  10032. }
  10033. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10034. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10035. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10036. // target reaches write_request. The client must fail cleanly with
  10037. // Error::Write instead of putting a request-line-less, header-injecting
  10038. // request on the wire.
  10039. Server svr;
  10040. svr.Get("/a", [](const Request &, Response &res) {
  10041. res.set_content("ok", "text/plain");
  10042. });
  10043. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10044. auto se = detail::scope_exit([&] {
  10045. svr.stop();
  10046. thread.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. });
  10049. svr.wait_until_ready();
  10050. {
  10051. Client cli(HOST, PORT);
  10052. cli.set_path_encode(false);
  10053. // The request is rejected before anything is written, so the connection
  10054. // stays silent and the subsequent response read would otherwise block for
  10055. // the full default read timeout. Shorten it -- the assertion is on the
  10056. // error, not the timeout.
  10057. cli.set_read_timeout(1, 0);
  10058. auto res = cli.Get("/a\r\nInjected: pwned");
  10059. EXPECT_FALSE(res);
  10060. EXPECT_EQ(Error::Write, res.error());
  10061. }
  10062. }
  10063. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10064. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10065. // including extension methods.
  10066. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10067. for (const auto &method : good_methods) {
  10068. detail::BufferStream strm;
  10069. auto n = detail::write_request_line(strm, method, "/");
  10070. EXPECT_GT(n, 0);
  10071. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10072. }
  10073. // A method carrying CR/LF would split the request line and smuggle a whole
  10074. // request ahead of the real one. A space or an empty method corrupts the
  10075. // request line. All must be rejected before anything reaches the wire.
  10076. const std::string evil_methods[] = {
  10077. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10078. "GET\r\nInjected: pwned",
  10079. "GET\r",
  10080. "GET\n",
  10081. "GE T",
  10082. "",
  10083. };
  10084. for (const auto &evil : evil_methods) {
  10085. detail::BufferStream strm;
  10086. auto n = detail::write_request_line(strm, evil, "/");
  10087. EXPECT_LT(n, 0);
  10088. EXPECT_TRUE(strm.get_buffer().empty());
  10089. }
  10090. }
  10091. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10092. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10093. // through Client::send must fail with Error::Write and no request, neither
  10094. // the smuggled one nor the real one, may reach the server.
  10095. Server svr;
  10096. std::atomic<int> request_count(0);
  10097. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10098. request_count++;
  10099. res.status = StatusCode::OK_200;
  10100. return Server::HandlerResponse::Handled;
  10101. });
  10102. auto port = svr.bind_to_any_port(HOST);
  10103. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. thread.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. {
  10111. Client cli(HOST, port);
  10112. const std::string evil_methods[] = {
  10113. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10114. "GE T",
  10115. "",
  10116. };
  10117. for (const auto &evil : evil_methods) {
  10118. Request req;
  10119. req.method = evil;
  10120. req.path = "/";
  10121. auto res = cli.send(req);
  10122. EXPECT_FALSE(res);
  10123. EXPECT_EQ(Error::Write, res.error());
  10124. }
  10125. auto handle =
  10126. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10127. EXPECT_FALSE(handle.is_valid());
  10128. EXPECT_EQ(Error::Write, handle.error);
  10129. // A valid request on the same client still goes through.
  10130. auto res = cli.Get("/");
  10131. ASSERT_TRUE(res);
  10132. EXPECT_EQ(StatusCode::OK_200, res->status);
  10133. }
  10134. EXPECT_EQ(1, request_count.load());
  10135. }
  10136. // Sends a raw request and verifies that there isn't a crash or exception.
  10137. static void test_raw_request(const std::string &req,
  10138. std::string *out = nullptr) {
  10139. Server svr;
  10140. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10141. res.set_content("ok", "text/plain");
  10142. });
  10143. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10144. res.set_content("ok", "text/plain");
  10145. });
  10146. svr.Get("/header_field_value_check",
  10147. [&](const Request & /*req*/, Response &res) {
  10148. res.set_content("ok", "text/plain");
  10149. });
  10150. svr.CustomRoute("PROPFIND", "/dav",
  10151. [&](const Request & /*req*/, Response &res) {
  10152. res.status = StatusCode::MultiStatus_207;
  10153. });
  10154. // Server read timeout must be longer than the client read timeout for the
  10155. // bug to reproduce, probably to force the server to process a request
  10156. // without a trailing blank line.
  10157. const time_t client_read_timeout_sec = 1;
  10158. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10159. bool listen_thread_ok = false;
  10160. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. t.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. EXPECT_TRUE(listen_thread_ok);
  10166. });
  10167. svr.wait_until_ready();
  10168. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10169. }
  10170. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10171. // A certain header line causes an exception if the header property is parsed
  10172. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10173. test_raw_request(
  10174. "GET /hi HTTP/1.1\r\n"
  10175. " : "
  10176. " "
  10177. " ");
  10178. }
  10179. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10180. // A certain header line causes an exception if the header property *name* is
  10181. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10182. // greedy matcher and requires backtracking when there are a lot of ":"
  10183. // characters.
  10184. // This occurs with libc++ but not libstdc++.
  10185. test_raw_request(
  10186. "GET /hi HTTP/1.1\r\n"
  10187. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10188. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10189. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10190. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10191. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10192. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10193. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10194. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10195. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10196. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10197. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10198. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10199. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10200. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10201. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10202. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10203. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10204. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10205. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10206. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10207. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10208. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10209. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10210. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10211. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10212. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10213. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10214. "&&&%%%");
  10215. }
  10216. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10217. // Make sure this doesn't crash the server.
  10218. // In a previous version of the header line regex, the "\r" rendered the line
  10219. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10220. // a new position where the leading white space ended and the field value
  10221. // began.
  10222. // The crash occurs with libc++ but not libstdc++.
  10223. test_raw_request("GET /hi HTTP/1.1\r\n"
  10224. "a:" +
  10225. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10226. "\r\n"
  10227. "\r\n");
  10228. }
  10229. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10230. const char *rejected[] = {
  10231. // RFC 9112 §3: one SP between the parts, and nothing else
  10232. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10233. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10234. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10235. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10236. // A request-target has no fragment
  10237. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10238. // An HTTP/1.1 request needs a Host
  10239. "GET /hi HTTP/1.1\r\n\r\n",
  10240. };
  10241. for (auto request : rejected) {
  10242. std::string out;
  10243. test_raw_request(request, &out);
  10244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10245. }
  10246. std::string out;
  10247. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10248. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10249. }
  10250. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10251. // RFC 9112 §6.1
  10252. const char *requests[] = {
  10253. "PUT /put_hi HTTP/1.1\r\n"
  10254. "Host: localhost\r\n"
  10255. "Content-Length: 0\r\n"
  10256. "Transfer-Encoding: chunked\r\n"
  10257. "\r\n"
  10258. "0\r\n\r\n",
  10259. "PUT /put_hi HTTP/1.0\r\n"
  10260. "Connection: keep-alive\r\n"
  10261. "Transfer-Encoding: chunked\r\n"
  10262. "\r\n"
  10263. "0\r\n\r\n",
  10264. };
  10265. for (auto request : requests) {
  10266. std::string out;
  10267. test_raw_request(request, &out);
  10268. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10269. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10270. }
  10271. }
  10272. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10273. std::string out;
  10274. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10275. "Content-Type: text/plain\r\n"
  10276. "Transfer-Encoding: chunked\r\n"
  10277. "\r\n"
  10278. "nothex\r\n",
  10279. &out);
  10280. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10281. }
  10282. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10283. std::string out;
  10284. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10285. "Content-Type: text/plain\r\n"
  10286. "Transfer-Encoding: chunked\r\n"
  10287. "\r\n"
  10288. "3\r\n"
  10289. "xyz\r\n"
  10290. "NaN\r\n",
  10291. &out);
  10292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10293. }
  10294. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10295. std::string out;
  10296. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10297. "Content-Type: text/plain\r\n"
  10298. "Transfer-Encoding: chunked\r\n"
  10299. "\r\n"
  10300. // Length is too large for 64 bits.
  10301. "1ffffffffffffffff\r\n"
  10302. "xyz\r\n",
  10303. &out);
  10304. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10305. }
  10306. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10307. test_raw_request("GET /hi HTTP/1.1\r\n"
  10308. "Content-Type: text/plain\r\n\r");
  10309. }
  10310. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10311. std::string out;
  10312. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10313. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10314. }
  10315. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10316. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10317. std::string out;
  10318. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10319. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10320. }
  10321. }
  10322. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10323. std::string out;
  10324. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10325. "Host: localhost\r\n"
  10326. "Connection: close\r\n\r\n",
  10327. &out);
  10328. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10329. }
  10330. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10331. Server svr;
  10332. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10333. EXPECT_TRUE(!req.remote_addr.empty());
  10334. });
  10335. thread t = thread([&] { svr.listen(HOST, PORT); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. t.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. // Send an invalid request line to trigger Bad Request
  10343. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10344. std::string out;
  10345. ASSERT_TRUE(send_request(5, bad_req, &out));
  10346. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10347. }
  10348. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10349. // answered right away rather than blocking on a read that waits for EOF.
  10350. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10351. std::string out;
  10352. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10353. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10354. }
  10355. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10356. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10357. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10358. for (const auto *method : methods) {
  10359. Server svr;
  10360. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10361. EXPECT_FALSE(svr.is_valid()) << method;
  10362. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10363. }
  10364. }
  10365. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10366. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10367. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10368. for (const auto *method : methods) {
  10369. Server svr;
  10370. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10371. EXPECT_FALSE(svr.is_valid()) << method;
  10372. }
  10373. }
  10374. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10375. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10376. "COPY", "MOVE", "LOCK",
  10377. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10378. Server svr;
  10379. for (const auto *method : methods) {
  10380. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10381. }
  10382. EXPECT_TRUE(svr.is_valid());
  10383. }
  10384. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10385. Server svr;
  10386. svr.CustomRoute("POST", "/x",
  10387. [](const Request &, Response &, const ContentReader &) {});
  10388. EXPECT_FALSE(svr.is_valid());
  10389. }
  10390. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10391. Server svr;
  10392. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10393. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10394. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10395. EXPECT_FALSE(svr.is_valid());
  10396. }
  10397. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10398. Server svr;
  10399. auto captured = Error::Success;
  10400. svr.set_error_logger(
  10401. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10402. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10403. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10404. }
  10405. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10406. std::string out;
  10407. std::string request(
  10408. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10409. test_raw_request(request, &out);
  10410. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10411. }
  10412. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10413. std::string out;
  10414. std::string request(
  10415. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10416. test_raw_request(request, &out);
  10417. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10418. }
  10419. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10420. std::string out;
  10421. std::string request(
  10422. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10423. test_raw_request(request, &out);
  10424. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10425. }
  10426. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10427. std::string out;
  10428. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10429. "Host: localhost\r\n"
  10430. "Test: \r\n\r\n",
  10431. &out);
  10432. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10433. }
  10434. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10435. Server svr;
  10436. std::string x_custom;
  10437. std::string cookie;
  10438. std::string xff;
  10439. std::string x_unicode;
  10440. std::string x_iis;
  10441. svr.Get("/check", [&](const Request &req, Response &res) {
  10442. x_custom = req.get_header_value("X-Custom");
  10443. cookie = req.get_header_value("Cookie");
  10444. xff = req.get_header_value("X-Forwarded-For");
  10445. x_unicode = req.get_header_value("X-Unicode");
  10446. x_iis = req.get_header_value("X-IIS");
  10447. res.set_content("ok", "text/plain");
  10448. });
  10449. thread t = thread([&] { svr.listen(HOST, PORT); });
  10450. auto se = detail::scope_exit([&] {
  10451. svr.stop();
  10452. t.join();
  10453. ASSERT_FALSE(svr.is_running());
  10454. });
  10455. svr.wait_until_ready();
  10456. const std::string req = "GET /check HTTP/1.1\r\n"
  10457. "Host: localhost\r\n"
  10458. "X-Custom: a%0D%0AInjected: b\r\n"
  10459. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10460. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10461. "X-Unicode: %E3%81%82\r\n"
  10462. "X-IIS: %u00E9\r\n"
  10463. "Connection: close\r\n"
  10464. "\r\n";
  10465. std::string res;
  10466. ASSERT_TRUE(send_request(5, req, &res));
  10467. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10468. // Every value must be returned verbatim (wire form), with no decoding.
  10469. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10470. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10471. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10472. EXPECT_EQ("%E3%81%82", x_unicode);
  10473. EXPECT_EQ("%u00E9", x_iis);
  10474. }
  10475. // Applications that previously relied on automatic percent-decoding can
  10476. // reproduce the old behavior by explicitly calling decode_path_component()
  10477. // or, for RFC 3986 conformance, decode_uri_component().
  10478. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10479. Server svr;
  10480. std::string decoded;
  10481. svr.Get("/check", [&](const Request &req, Response &res) {
  10482. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10483. res.set_content("ok", "text/plain");
  10484. });
  10485. thread t = thread([&] { svr.listen(HOST, PORT); });
  10486. auto se = detail::scope_exit([&] {
  10487. svr.stop();
  10488. t.join();
  10489. ASSERT_FALSE(svr.is_running());
  10490. });
  10491. svr.wait_until_ready();
  10492. const std::string req = "GET /check HTTP/1.1\r\n"
  10493. "Host: localhost\r\n"
  10494. "X-Custom: hello%20world\r\n"
  10495. "Connection: close\r\n"
  10496. "\r\n";
  10497. std::string res;
  10498. ASSERT_TRUE(send_request(5, req, &res));
  10499. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10500. EXPECT_EQ("hello world", decoded);
  10501. }
  10502. // Regression test for #2033. Browsers send Referer values that include
  10503. // percent-encoded characters such as %0A inside the URL. Decoding the
  10504. // header value would either trip the post-decode CR/LF/NUL guard (the
  10505. // original bug, returning 400) or, after that guard was relaxed, silently
  10506. // store a literal LF — both unacceptable. The wire form must round-trip.
  10507. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10508. Server svr;
  10509. std::string referer;
  10510. svr.Get("/check", [&](const Request &req, Response &res) {
  10511. referer = req.get_header_value("Referer");
  10512. res.set_content("ok", "text/plain");
  10513. });
  10514. thread t = thread([&] { svr.listen(HOST, PORT); });
  10515. auto se = detail::scope_exit([&] {
  10516. svr.stop();
  10517. t.join();
  10518. ASSERT_FALSE(svr.is_running());
  10519. });
  10520. svr.wait_until_ready();
  10521. const std::string req = "GET /check HTTP/1.1\r\n"
  10522. "Host: localhost\r\n"
  10523. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10524. "Connection: close\r\n"
  10525. "\r\n";
  10526. std::string res;
  10527. ASSERT_TRUE(send_request(5, req, &res));
  10528. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10529. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10530. }
  10531. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10532. Server svr;
  10533. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10534. res.set_header("Cache-Control", "no-cache");
  10535. res.set_chunked_content_provider(
  10536. "text/event-stream", [](size_t offset, DataSink &sink) {
  10537. std::string s = "data:";
  10538. s += std::to_string(offset);
  10539. s += "\n\n";
  10540. auto ret = sink.write(s.data(), s.size());
  10541. EXPECT_TRUE(ret);
  10542. std::this_thread::sleep_for(std::chrono::seconds(1));
  10543. return true;
  10544. });
  10545. });
  10546. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10547. svr.wait_until_ready();
  10548. Client client(HOST, PORT);
  10549. const Headers headers = {{"Accept", "text/event-stream"}};
  10550. auto get_thread = std::thread([&client, &headers]() {
  10551. auto res = client.Get(
  10552. "/events", headers,
  10553. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10554. });
  10555. auto se = detail::scope_exit([&] {
  10556. svr.stop();
  10557. get_thread.join();
  10558. listen_thread.join();
  10559. ASSERT_FALSE(svr.is_running());
  10560. });
  10561. // Give GET time to get a few messages.
  10562. std::this_thread::sleep_for(std::chrono::seconds(2));
  10563. }
  10564. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10565. httplib::Server svr;
  10566. svr.Post("/hi",
  10567. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10568. res.status = StatusCode::OK_200;
  10569. });
  10570. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10571. svr.wait_until_ready();
  10572. Client cli(HOST, PORT);
  10573. auto res = cli.Post("/hi", "data", "text/plain");
  10574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10575. EXPECT_EQ(StatusCode::OK_200, res->status);
  10576. svr.stop();
  10577. thread.join();
  10578. ASSERT_FALSE(svr.is_running());
  10579. res = cli.Post("/hi", "data", "text/plain");
  10580. ASSERT_FALSE(res);
  10581. }
  10582. TEST(ServerStopTest, ListenFailure) {
  10583. Server svr;
  10584. auto t = thread([&]() {
  10585. auto ret = svr.listen("????", PORT);
  10586. EXPECT_FALSE(ret);
  10587. });
  10588. svr.wait_until_ready();
  10589. svr.stop();
  10590. t.join();
  10591. }
  10592. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10593. TEST(ServerStopTest, Decommision) {
  10594. Server svr;
  10595. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10596. for (int i = 0; i < 4; i++) {
  10597. auto is_even = !(i % 2);
  10598. std::thread t{[&] {
  10599. try {
  10600. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10601. if (is_even) {
  10602. throw std::runtime_error("Some thing that happens to go wrong.");
  10603. }
  10604. svr.listen(HOST, PORT);
  10605. } catch (...) { svr.decommission(); }
  10606. }};
  10607. svr.wait_until_ready();
  10608. // Server is up
  10609. {
  10610. Client cli(HOST, PORT);
  10611. auto res = cli.Get("/hi");
  10612. if (is_even) {
  10613. EXPECT_FALSE(res);
  10614. } else {
  10615. EXPECT_TRUE(res);
  10616. EXPECT_EQ("hi...", res->body);
  10617. }
  10618. }
  10619. svr.stop();
  10620. t.join();
  10621. // Server is down...
  10622. {
  10623. Client cli(HOST, PORT);
  10624. auto res = cli.Get("/hi");
  10625. EXPECT_FALSE(res);
  10626. }
  10627. }
  10628. }
  10629. #endif
  10630. // Helper function for string body upload progress tests
  10631. template <typename SetupHandler, typename ClientCall>
  10632. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10633. ClientCall &&client_call,
  10634. const string &body) {
  10635. Server svr;
  10636. setup_handler(svr);
  10637. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10638. auto se = detail::scope_exit([&] {
  10639. svr.stop();
  10640. t.join();
  10641. });
  10642. svr.wait_until_ready();
  10643. Client cli(HOST, PORT);
  10644. vector<uint64_t> progress_values;
  10645. bool progress_called = false;
  10646. auto res =
  10647. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10648. progress_values.push_back(current);
  10649. progress_called = true;
  10650. return true;
  10651. });
  10652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10653. EXPECT_EQ(200, res->status);
  10654. EXPECT_TRUE(progress_called);
  10655. }
  10656. TEST(UploadProgressTest, PostStringBodyBasic) {
  10657. TestStringBodyUploadProgress(
  10658. [](Server &svr) {
  10659. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10660. res.set_content("received", "text/plain");
  10661. });
  10662. },
  10663. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10664. return cli.Post("/test", body, "text/plain", progress_callback);
  10665. },
  10666. "test data for upload progress");
  10667. }
  10668. TEST(UploadProgressTest, PutStringBodyBasic) {
  10669. TestStringBodyUploadProgress(
  10670. [](Server &svr) {
  10671. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10672. res.set_content("put received", "text/plain");
  10673. });
  10674. },
  10675. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10676. return cli.Put("/test", body, "text/plain", progress_callback);
  10677. },
  10678. "put test data for upload progress");
  10679. }
  10680. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10681. TestStringBodyUploadProgress(
  10682. [](Server &svr) {
  10683. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10684. res.set_content("patch received", "text/plain");
  10685. });
  10686. },
  10687. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10688. return cli.Patch("/test", body, "text/plain", progress_callback);
  10689. },
  10690. "patch test data for upload progress");
  10691. }
  10692. // Helper function for content provider upload progress tests
  10693. template <typename SetupHandler, typename ClientCall>
  10694. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10695. ClientCall &&client_call) {
  10696. Server svr;
  10697. setup_handler(svr);
  10698. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10699. auto se = detail::scope_exit([&] {
  10700. svr.stop();
  10701. t.join();
  10702. });
  10703. svr.wait_until_ready();
  10704. Client cli(HOST, PORT);
  10705. vector<uint64_t> progress_values;
  10706. auto res =
  10707. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10708. progress_values.push_back(current);
  10709. return true;
  10710. });
  10711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10712. EXPECT_EQ(200, res->status);
  10713. EXPECT_FALSE(progress_values.empty());
  10714. }
  10715. TEST(UploadProgressTest, PostContentProviderProgress) {
  10716. TestContentProviderUploadProgress(
  10717. [](Server &svr) {
  10718. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10719. res.set_content("provider received", "text/plain");
  10720. });
  10721. },
  10722. [](Client &cli, UploadProgress progress_callback) {
  10723. return cli.Post(
  10724. "/test", 9,
  10725. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10726. sink.os << "test data";
  10727. return true;
  10728. },
  10729. "text/plain", progress_callback);
  10730. });
  10731. }
  10732. // Helper function for multipart upload progress tests
  10733. template <typename SetupHandler, typename ClientCall>
  10734. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10735. ClientCall &&client_call,
  10736. const string &endpoint) {
  10737. Server svr;
  10738. setup_handler(svr);
  10739. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10740. auto se = detail::scope_exit([&] {
  10741. svr.stop();
  10742. t.join();
  10743. });
  10744. svr.wait_until_ready();
  10745. Client cli(HOST, PORT);
  10746. vector<uint64_t> progress_values;
  10747. UploadFormDataItems items = {
  10748. {"field1", "value1", "", ""},
  10749. {"field2", "longer value for progress tracking test", "", ""},
  10750. {"file1", "file content data for upload progress", "test.txt",
  10751. "text/plain"}};
  10752. auto res = client_call(cli, endpoint, items,
  10753. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10754. progress_values.push_back(current);
  10755. return true;
  10756. });
  10757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10758. EXPECT_EQ(200, res->status);
  10759. EXPECT_FALSE(progress_values.empty());
  10760. }
  10761. TEST(UploadProgressTest, PostMultipartProgress) {
  10762. TestMultipartUploadProgress(
  10763. [](Server &svr) {
  10764. svr.Post("/multipart", [](const Request &req, Response &res) {
  10765. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10766. res.set_content("multipart received", "text/plain");
  10767. });
  10768. },
  10769. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10770. UploadProgress progress_callback) {
  10771. return cli.Post(endpoint, items, progress_callback);
  10772. },
  10773. "/multipart");
  10774. }
  10775. // Helper function for basic download progress tests
  10776. template <typename SetupHandler, typename ClientCall>
  10777. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10778. ClientCall &&client_call, const string &endpoint,
  10779. size_t expected_content_size) {
  10780. Server svr;
  10781. setup_handler(svr);
  10782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10783. auto se = detail::scope_exit([&] {
  10784. svr.stop();
  10785. t.join();
  10786. });
  10787. svr.wait_until_ready();
  10788. Client cli(HOST, PORT);
  10789. vector<uint64_t> progress_values;
  10790. auto res = client_call(cli, endpoint,
  10791. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10792. progress_values.push_back(current);
  10793. return true;
  10794. });
  10795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10796. EXPECT_EQ(200, res->status);
  10797. EXPECT_FALSE(progress_values.empty());
  10798. EXPECT_EQ(expected_content_size, res->body.size());
  10799. }
  10800. TEST(DownloadProgressTest, GetBasic) {
  10801. TestBasicDownloadProgress(
  10802. [](Server &svr) {
  10803. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10804. string content(1000, 'D');
  10805. res.set_content(content, "text/plain");
  10806. });
  10807. },
  10808. [](Client &cli, const string &endpoint,
  10809. DownloadProgress progress_callback) {
  10810. return cli.Get(endpoint, progress_callback);
  10811. },
  10812. "/download", 1000u);
  10813. }
  10814. // Helper function for content receiver download progress tests
  10815. template <typename SetupHandler, typename ClientCall>
  10816. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10817. ClientCall &&client_call,
  10818. const string &endpoint,
  10819. size_t expected_content_size) {
  10820. Server svr;
  10821. setup_handler(svr);
  10822. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10823. auto se = detail::scope_exit([&] {
  10824. svr.stop();
  10825. t.join();
  10826. });
  10827. svr.wait_until_ready();
  10828. Client cli(HOST, PORT);
  10829. vector<uint64_t> progress_values;
  10830. string received_body;
  10831. auto res = client_call(
  10832. cli, endpoint,
  10833. [&](const char *data, size_t data_length) -> bool {
  10834. received_body.append(data, data_length);
  10835. return true;
  10836. },
  10837. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10838. progress_values.push_back(current);
  10839. return true;
  10840. });
  10841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10842. EXPECT_EQ(200, res->status);
  10843. EXPECT_FALSE(progress_values.empty());
  10844. EXPECT_EQ(expected_content_size, received_body.size());
  10845. EXPECT_TRUE(res->body.empty());
  10846. }
  10847. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10848. TestContentReceiverDownloadProgress(
  10849. [](Server &svr) {
  10850. svr.Get("/download-receiver",
  10851. [](const Request & /*req*/, Response &res) {
  10852. string content(2000, 'R');
  10853. res.set_content(content, "text/plain");
  10854. });
  10855. },
  10856. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10857. DownloadProgress progress_callback) {
  10858. return cli.Get(endpoint, content_receiver, progress_callback);
  10859. },
  10860. "/download-receiver", 2000u);
  10861. }
  10862. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10863. // A provider reaching a pass with nothing to hand over - an empty buffer
  10864. // popped off a queue, say - must not be taken to mean the body is finished.
  10865. // It used to end the loop with the terminating chunk unwritten while the
  10866. // server still considered the response complete, so the peer waited for an
  10867. // end that never arrived.
  10868. Server svr;
  10869. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10870. auto step = std::make_shared<int>(0);
  10871. res.set_chunked_content_provider("text/plain",
  10872. [step](size_t /*offset*/, DataSink &sink) {
  10873. switch ((*step)++) {
  10874. case 0: sink.write("", 0); break;
  10875. case 1: sink.write("hello", 5); break;
  10876. default: sink.done(); break;
  10877. }
  10878. return true;
  10879. });
  10880. });
  10881. auto port = svr.bind_to_any_port(HOST);
  10882. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10883. auto listen_se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. listen_thread.join();
  10886. ASSERT_FALSE(svr.is_running());
  10887. });
  10888. svr.wait_until_ready();
  10889. Client cli(HOST, port);
  10890. // Without the fix the body is never terminated, so bound the wait rather
  10891. // than letting the test hang on the default read timeout.
  10892. cli.set_read_timeout(5, 0);
  10893. auto res = cli.Get("/stream");
  10894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10895. EXPECT_EQ(StatusCode::OK_200, res->status);
  10896. EXPECT_EQ("hello", res->body);
  10897. }
  10898. TEST(StreamingTest, NoContentLengthStreaming) {
  10899. Server svr;
  10900. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10901. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10902. if (offset < 6) {
  10903. sink.os << (offset < 3 ? "a" : "b");
  10904. } else {
  10905. sink.done();
  10906. }
  10907. return true;
  10908. });
  10909. });
  10910. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10911. auto listen_se = detail::scope_exit([&] {
  10912. svr.stop();
  10913. listen_thread.join();
  10914. ASSERT_FALSE(svr.is_running());
  10915. });
  10916. svr.wait_until_ready();
  10917. Client client(HOST, PORT);
  10918. auto get_thread = std::thread([&client]() {
  10919. std::string s;
  10920. auto res =
  10921. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10922. s += std::string(data, len);
  10923. return true;
  10924. });
  10925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10926. EXPECT_EQ(StatusCode::OK_200, res->status);
  10927. EXPECT_EQ("aaabbb", s);
  10928. });
  10929. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10930. // Give GET time to get a few messages.
  10931. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10932. }
  10933. TEST(MountTest, Unmount) {
  10934. Server svr;
  10935. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10936. auto se = detail::scope_exit([&] {
  10937. svr.stop();
  10938. listen_thread.join();
  10939. ASSERT_FALSE(svr.is_running());
  10940. });
  10941. svr.wait_until_ready();
  10942. Client cli("localhost", PORT);
  10943. svr.set_mount_point("/mount2", "./www2");
  10944. auto res = cli.Get("/");
  10945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10946. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10947. res = cli.Get("/mount2/dir/test.html");
  10948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10949. EXPECT_EQ(StatusCode::OK_200, res->status);
  10950. svr.set_mount_point("/", "./www");
  10951. res = cli.Get("/dir/");
  10952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10953. EXPECT_EQ(StatusCode::OK_200, res->status);
  10954. svr.remove_mount_point("/");
  10955. res = cli.Get("/dir/");
  10956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10958. svr.remove_mount_point("/mount2");
  10959. res = cli.Get("/mount2/dir/test.html");
  10960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10961. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10962. }
  10963. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10964. Server svr;
  10965. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10966. svr.Get("/api/hello", [](const Request &, Response &res) {
  10967. res.set_content("api", "text/plain");
  10968. });
  10969. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10970. auto se = detail::scope_exit([&] {
  10971. svr.stop();
  10972. listen_thread.join();
  10973. ASSERT_FALSE(svr.is_running());
  10974. });
  10975. svr.wait_until_ready();
  10976. Client cli(HOST, PORT);
  10977. auto res = cli.Get("/dir/test.html");
  10978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10979. EXPECT_EQ(StatusCode::OK_200, res->status);
  10980. res = cli.Get("/api/hello");
  10981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10982. EXPECT_EQ(StatusCode::OK_200, res->status);
  10983. EXPECT_EQ("api", res->body);
  10984. }
  10985. TEST(MountTest, PathSegmentBoundary) {
  10986. Server svr;
  10987. svr.set_mount_point("/mount2", "./www2");
  10988. svr.set_mount_point("/", "./www");
  10989. auto port = svr.bind_to_any_port(HOST);
  10990. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10991. auto se = detail::scope_exit([&] {
  10992. svr.stop();
  10993. listen_thread.join();
  10994. ASSERT_FALSE(svr.is_running());
  10995. });
  10996. svr.wait_until_ready();
  10997. Client cli(HOST, port);
  10998. auto res = cli.Get("/mount2/dir/test.html");
  10999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11000. EXPECT_EQ(StatusCode::OK_200, res->status);
  11001. // "/mount2" must not match part-way through a path segment.
  11002. res = cli.Get("/mount2dir/test.html");
  11003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11004. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11005. // A mount point ending in '/' keeps matching every path below it.
  11006. res = cli.Get("/dir/test.html");
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. EXPECT_EQ(StatusCode::OK_200, res->status);
  11009. }
  11010. TEST(MountTest, Redicect) {
  11011. Server svr;
  11012. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11013. auto se = detail::scope_exit([&] {
  11014. svr.stop();
  11015. listen_thread.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. });
  11018. svr.set_mount_point("/", "./www");
  11019. svr.wait_until_ready();
  11020. Client cli("localhost", PORT);
  11021. auto res = cli.Get("/dir/");
  11022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11023. EXPECT_EQ(StatusCode::OK_200, res->status);
  11024. res = cli.Get("/dir");
  11025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11026. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11027. res = cli.Get("/file");
  11028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11029. EXPECT_EQ(StatusCode::OK_200, res->status);
  11030. res = cli.Get("/file/");
  11031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11033. cli.set_follow_location(true);
  11034. res = cli.Get("/dir");
  11035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11036. EXPECT_EQ(StatusCode::OK_200, res->status);
  11037. }
  11038. TEST(MountTest, MultibytesPathName) {
  11039. Server svr;
  11040. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11041. auto se = detail::scope_exit([&] {
  11042. svr.stop();
  11043. listen_thread.join();
  11044. ASSERT_FALSE(svr.is_running());
  11045. });
  11046. svr.set_mount_point("/", "./www");
  11047. svr.wait_until_ready();
  11048. Client cli("localhost", PORT);
  11049. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11051. EXPECT_EQ(StatusCode::OK_200, res->status);
  11052. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11053. }
  11054. // A mount point serves no path with an empty segment or one ending in '.' or
  11055. // a space, so a guard in the pre-routing handler sees the path of every file
  11056. // that is served
  11057. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11058. Server svr;
  11059. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11060. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11061. if (req.path == "/dir/test.html") {
  11062. res.status = StatusCode::Unauthorized_401;
  11063. return Server::HandlerResponse::Handled;
  11064. }
  11065. return Server::HandlerResponse::Unhandled;
  11066. });
  11067. auto port = svr.bind_to_any_port(HOST);
  11068. ASSERT_LT(0, port);
  11069. thread t = thread([&] { svr.listen_after_bind(); });
  11070. auto se = detail::scope_exit([&] {
  11071. svr.stop();
  11072. t.join();
  11073. ASSERT_FALSE(svr.is_running());
  11074. });
  11075. svr.wait_until_ready();
  11076. Client cli(HOST, port);
  11077. for (auto path :
  11078. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11079. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11080. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11081. "/dir/test.html%3A%3A$DATA"}) {
  11082. SCOPED_TRACE(path);
  11083. auto res = cli.Get(path);
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11086. }
  11087. }
  11088. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11089. Server svr;
  11090. svr.set_mount_point("/", "./www");
  11091. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11092. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11093. auto port = svr.bind_to_any_port(HOST);
  11094. ASSERT_GT(port, 0);
  11095. thread t = thread([&] { svr.listen_after_bind(); });
  11096. auto se = detail::scope_exit([&] {
  11097. svr.stop();
  11098. t.join();
  11099. ASSERT_FALSE(svr.is_running());
  11100. });
  11101. svr.wait_until_ready();
  11102. Client cli(HOST, port);
  11103. auto res = cli.Get("/dir/test.abcde");
  11104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11105. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11106. res = cli.Get("/dir/test.html");
  11107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11108. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11109. }
  11110. #ifdef _WIN32
  11111. // Issue #2435: mmap::open() must succeed even when another handle holds
  11112. // the file open for writing (e.g. an active log file).
  11113. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11114. const char *path = "mmap_concurrent_writer_test.txt";
  11115. const char *content = "hello";
  11116. {
  11117. std::ofstream f(path, std::ios::binary);
  11118. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11119. }
  11120. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11121. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11122. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11123. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11124. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11125. detail::mmap m(path);
  11126. ASSERT_TRUE(m.is_open());
  11127. EXPECT_EQ(strlen(content), m.size());
  11128. char buf[8];
  11129. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11130. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11131. }
  11132. #endif
  11133. #ifndef _WIN32
  11134. // A directory or a device has no size to serve.
  11135. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11136. const char *path = "./mmap_not_regular_test_dir";
  11137. ASSERT_EQ(0, ::mkdir(path, 0755));
  11138. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11139. for (auto p : {path, "/dev/null"}) {
  11140. detail::mmap m(p);
  11141. EXPECT_FALSE(m.is_open()) << p;
  11142. EXPECT_EQ(0U, m.size()) << p;
  11143. }
  11144. Server svr;
  11145. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11146. res.set_file_content("/dev/null");
  11147. });
  11148. auto port = svr.bind_to_any_port(HOST);
  11149. thread t = thread([&] { svr.listen_after_bind(); });
  11150. auto se = detail::scope_exit([&] {
  11151. svr.stop();
  11152. t.join();
  11153. });
  11154. svr.wait_until_ready();
  11155. auto res = Client(HOST, port).Get("/null");
  11156. ASSERT_TRUE(res);
  11157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11158. }
  11159. #endif
  11160. #ifdef __linux__
  11161. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11162. TEST(MmapTest, FileIsNotMapped) {
  11163. const char *path = "mmap_not_mapped_test.txt";
  11164. {
  11165. std::ofstream f(path, std::ios::binary);
  11166. f << "hello";
  11167. }
  11168. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11169. detail::mmap m(path);
  11170. ASSERT_TRUE(m.is_open());
  11171. std::ifstream maps("/proc/self/maps");
  11172. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11173. std::istreambuf_iterator<char>());
  11174. EXPECT_EQ(std::string::npos, mappings.find(path));
  11175. }
  11176. #endif
  11177. TEST(KeepAliveTest, ReadTimeout) {
  11178. Server svr;
  11179. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11180. std::this_thread::sleep_for(std::chrono::seconds(2));
  11181. res.set_content("a", "text/plain");
  11182. });
  11183. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11184. res.set_content("b", "text/plain");
  11185. });
  11186. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11187. auto se = detail::scope_exit([&] {
  11188. svr.stop();
  11189. listen_thread.join();
  11190. ASSERT_FALSE(svr.is_running());
  11191. });
  11192. svr.wait_until_ready();
  11193. Client cli("localhost", PORT);
  11194. cli.set_keep_alive(true);
  11195. cli.set_read_timeout(std::chrono::seconds(1));
  11196. auto resa = cli.Get("/a");
  11197. ASSERT_FALSE(resa);
  11198. EXPECT_EQ(Error::Read, resa.error());
  11199. auto resb = cli.Get("/b");
  11200. ASSERT_TRUE(resb);
  11201. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11202. EXPECT_EQ("b", resb->body);
  11203. }
  11204. TEST(KeepAliveTest, MaxCount) {
  11205. size_t keep_alive_max_count = 3;
  11206. Server svr;
  11207. svr.set_keep_alive_max_count(keep_alive_max_count);
  11208. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11209. res.set_content("Hello World!", "text/plain");
  11210. });
  11211. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11212. auto se = detail::scope_exit([&] {
  11213. svr.stop();
  11214. listen_thread.join();
  11215. ASSERT_FALSE(svr.is_running());
  11216. });
  11217. svr.wait_until_ready();
  11218. Client cli(HOST, PORT);
  11219. cli.set_keep_alive(true);
  11220. for (size_t i = 0; i < 5; i++) {
  11221. auto result = cli.Get("/hi");
  11222. ASSERT_TRUE(result);
  11223. EXPECT_EQ(StatusCode::OK_200, result->status);
  11224. if (i == keep_alive_max_count - 1) {
  11225. EXPECT_EQ("close", result->get_header_value("Connection"));
  11226. } else {
  11227. EXPECT_FALSE(result->has_header("Connection"));
  11228. }
  11229. }
  11230. }
  11231. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11232. // can pull the next one into the server's buffer. The server must serve it
  11233. // without waiting for the socket to become readable again. The keep-alive
  11234. // timeout outlasts the client's read timeout, so a request left waiting for it
  11235. // shows up as a missing response.
  11236. static void serve_pipelining_routes(Server &svr,
  11237. const std::function<void(int)> &client) {
  11238. svr.set_keep_alive_timeout(5);
  11239. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11240. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11241. });
  11242. svr.Post("/echo", [](const Request &req, Response &res) {
  11243. res.set_content("echo " + req.body, "text/plain");
  11244. });
  11245. auto port = svr.bind_to_any_port(HOST);
  11246. thread t = thread([&] { svr.listen_after_bind(); });
  11247. auto se = detail::scope_exit([&] {
  11248. svr.stop();
  11249. t.join();
  11250. });
  11251. svr.wait_until_ready();
  11252. client(port);
  11253. }
  11254. static std::string
  11255. send_pipelined_requests(const std::vector<std::string> &parts) {
  11256. Server svr;
  11257. std::string res;
  11258. serve_pipelining_routes(svr, [&](int port) {
  11259. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11260. });
  11261. return res;
  11262. }
  11263. static void expect_in_order(const std::string &res,
  11264. const std::vector<std::string> &bodies) {
  11265. size_t pos = 0;
  11266. for (const auto &body : bodies) {
  11267. pos = res.find(body, pos);
  11268. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11269. pos += body.size();
  11270. }
  11271. }
  11272. TEST(KeepAliveTest, PipelinedRequests) {
  11273. auto res = send_pipelined_requests(
  11274. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11275. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11276. "Content-Length: 4\r\n\r\nbody"
  11277. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11278. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11279. }
  11280. // The second request starts in the server's buffer and ends on the socket.
  11281. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11282. auto res =
  11283. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11284. "GET /hi/2 HTTP/1.1\r\nHo",
  11285. "st: localhost\r\nConnection: close\r\n\r\n"});
  11286. expect_in_order(res, {"hi 1", "hi 2"});
  11287. }
  11288. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11289. // CRLF after a body does not turn into a 400 for the next request.
  11290. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11291. auto res = send_pipelined_requests(
  11292. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11293. "Content-Length: 4\r\n\r\nbody\r\n"
  11294. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11295. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11296. expect_in_order(res, {"echo body", "hi 2"});
  11297. }
  11298. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11299. // must not be served as the next request.
  11300. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11301. auto res = send_pipelined_requests(
  11302. {"INVALID REQUEST LINE\r\n\r\n"
  11303. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11304. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11305. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11306. }
  11307. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11308. // Over TLS, the next request is held by the TLS library as already decrypted
  11309. // data rather than on the socket.
  11310. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11312. std::string res;
  11313. serve_pipelining_routes(svr, [&](int port) {
  11314. // One part, so all three requests arrive in one TLS record
  11315. EXPECT_TRUE(send_ssl_request_in_parts(
  11316. 2,
  11317. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11318. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11319. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11320. &res, port));
  11321. });
  11322. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11323. }
  11324. #endif
  11325. TEST(KeepAliveTest, Issue1041) {
  11326. Server svr;
  11327. svr.set_keep_alive_timeout(3);
  11328. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11329. res.set_content("Hello World!", "text/plain");
  11330. });
  11331. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11332. auto se = detail::scope_exit([&] {
  11333. svr.stop();
  11334. listen_thread.join();
  11335. ASSERT_FALSE(svr.is_running());
  11336. });
  11337. svr.wait_until_ready();
  11338. Client cli(HOST, PORT);
  11339. cli.set_keep_alive(true);
  11340. auto result = cli.Get("/hi");
  11341. ASSERT_TRUE(result);
  11342. EXPECT_EQ(StatusCode::OK_200, result->status);
  11343. std::this_thread::sleep_for(std::chrono::seconds(5));
  11344. result = cli.Get("/hi");
  11345. ASSERT_TRUE(result);
  11346. EXPECT_EQ(StatusCode::OK_200, result->status);
  11347. }
  11348. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11349. Server svr;
  11350. svr.set_keep_alive_max_count(0);
  11351. std::set<int> remote_ports;
  11352. svr.Get("/hi", [&](const Request &req, Response &res) {
  11353. remote_ports.insert(req.remote_port);
  11354. res.set_content("hi", "text/plain");
  11355. });
  11356. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11357. auto se = detail::scope_exit([&] {
  11358. svr.stop();
  11359. listen_thread.join();
  11360. ASSERT_FALSE(svr.is_running());
  11361. });
  11362. svr.wait_until_ready();
  11363. Client cli(HOST, PORT);
  11364. cli.set_keep_alive(true);
  11365. for (int i = 0; i < 3; i++) {
  11366. auto res = cli.Get("/hi");
  11367. ASSERT_TRUE(res);
  11368. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11369. }
  11370. // All three over one connection
  11371. EXPECT_EQ(1u, remote_ports.size());
  11372. }
  11373. TEST(KeepAliveTest, Issue1959) {
  11374. Server svr;
  11375. svr.set_keep_alive_timeout(5);
  11376. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11377. res.set_content("a", "text/plain");
  11378. });
  11379. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11380. auto se = detail::scope_exit([&] {
  11381. if (!svr.is_running()) return;
  11382. svr.stop();
  11383. listen_thread.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.wait_until_ready();
  11387. Client cli("localhost", PORT);
  11388. cli.set_keep_alive(true);
  11389. using namespace std::chrono;
  11390. auto start = steady_clock::now();
  11391. cli.Get("/a");
  11392. svr.stop();
  11393. listen_thread.join();
  11394. auto end = steady_clock::now();
  11395. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11396. EXPECT_LT(elapsed, 5000);
  11397. }
  11398. #ifdef CPPHTTPLIB_SSL_ENABLED
  11399. TEST(KeepAliveTest, SSLClientReconnection) {
  11400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11401. ASSERT_TRUE(svr.is_valid());
  11402. svr.set_keep_alive_timeout(1);
  11403. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11404. res.set_content("Hello World!", "text/plain");
  11405. });
  11406. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11407. auto se = detail::scope_exit([&] {
  11408. svr.stop();
  11409. listen_thread.join();
  11410. ASSERT_FALSE(svr.is_running());
  11411. });
  11412. svr.wait_until_ready();
  11413. SSLClient cli(HOST, PORT);
  11414. cli.enable_server_certificate_verification(false);
  11415. cli.set_keep_alive(true);
  11416. auto result = cli.Get("/hi");
  11417. ASSERT_TRUE(result);
  11418. EXPECT_EQ(StatusCode::OK_200, result->status);
  11419. result = cli.Get("/hi");
  11420. ASSERT_TRUE(result);
  11421. EXPECT_EQ(StatusCode::OK_200, result->status);
  11422. std::this_thread::sleep_for(std::chrono::seconds(2));
  11423. // Recoonect
  11424. result = cli.Get("/hi");
  11425. ASSERT_TRUE(result);
  11426. EXPECT_EQ(StatusCode::OK_200, result->status);
  11427. result = cli.Get("/hi");
  11428. ASSERT_TRUE(result);
  11429. EXPECT_EQ(StatusCode::OK_200, result->status);
  11430. }
  11431. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11433. ASSERT_TRUE(svr.is_valid());
  11434. svr.set_keep_alive_timeout(1);
  11435. std::string content = "reconnect";
  11436. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11437. res.set_content("Hello World!", "text/plain");
  11438. });
  11439. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11440. auto se = detail::scope_exit([&] {
  11441. svr.stop();
  11442. listen_thread.join();
  11443. ASSERT_FALSE(svr.is_running());
  11444. });
  11445. svr.wait_until_ready();
  11446. SSLClient cli(HOST, PORT);
  11447. cli.enable_server_certificate_verification(false);
  11448. cli.set_keep_alive(true);
  11449. auto result = cli.Post(
  11450. "/hi", content.size(),
  11451. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11452. sink.write(content.c_str(), content.size());
  11453. return true;
  11454. },
  11455. "text/plain");
  11456. ASSERT_TRUE(result);
  11457. EXPECT_EQ(200, result->status);
  11458. std::this_thread::sleep_for(std::chrono::seconds(2));
  11459. // Recoonect
  11460. result = cli.Post(
  11461. "/hi", content.size(),
  11462. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11463. sink.write(content.c_str(), content.size());
  11464. return true;
  11465. },
  11466. "text/plain");
  11467. ASSERT_TRUE(result);
  11468. EXPECT_EQ(200, result->status);
  11469. result = cli.Post(
  11470. "/hi", content.size(),
  11471. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11472. sink.write(content.c_str(), content.size());
  11473. return true;
  11474. },
  11475. "text/plain");
  11476. ASSERT_TRUE(result);
  11477. EXPECT_EQ(200, result->status);
  11478. }
  11479. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11480. using namespace httplib::tls;
  11481. {
  11482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11483. ASSERT_TRUE(svr.is_valid());
  11484. svr.Get("/sni", [&](const Request &req, Response &res) {
  11485. std::string expected = req.sni();
  11486. EXPECT_EQ(expected, req.get_param_value("expected"));
  11487. res.set_content("ok", "text/plain");
  11488. });
  11489. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11490. auto se = detail::scope_exit([&] {
  11491. svr.stop();
  11492. listen_thread.join();
  11493. ASSERT_FALSE(svr.is_running());
  11494. });
  11495. svr.wait_until_ready();
  11496. {
  11497. SSLClient cli("localhost", PORT);
  11498. cli.enable_server_certificate_verification(false);
  11499. auto res = cli.Get("/sni?expected=localhost");
  11500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11501. }
  11502. {
  11503. SSLClient cli("::1", PORT);
  11504. cli.enable_server_certificate_verification(false);
  11505. auto res = cli.Get("/sni?expected=");
  11506. // NOTE: This may fail if the server is listening on IPv4 only
  11507. // (e.g., when localhost resolves to 127.0.0.1 only)
  11508. if (res) {
  11509. EXPECT_EQ(StatusCode::OK_200, res->status);
  11510. } else {
  11511. EXPECT_EQ(Error::Connection, res.error());
  11512. }
  11513. }
  11514. }
  11515. }
  11516. // The SNI of a failed handshake does not reach the next connection that the
  11517. // same worker thread serves
  11518. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11520. ASSERT_TRUE(svr.is_valid());
  11521. svr.new_task_queue = [] { return new ThreadPool(1); };
  11522. svr.Get("/sni", [](const Request &req, Response &res) {
  11523. res.set_content(req.sni(), "text/plain");
  11524. });
  11525. auto port = svr.bind_to_any_port("127.0.0.1");
  11526. ASSERT_LT(0, port);
  11527. thread t = thread([&] { svr.listen_after_bind(); });
  11528. auto se = detail::scope_exit([&] {
  11529. svr.stop();
  11530. t.join();
  11531. ASSERT_FALSE(svr.is_running());
  11532. });
  11533. svr.wait_until_ready();
  11534. {
  11535. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11536. SSLClient cli("localhost", port);
  11537. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11538. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11539. auto res = cli.Get("/sni");
  11540. ASSERT_FALSE(res);
  11541. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11542. }
  11543. // An IP host sends no SNI (RFC 6066)
  11544. SSLClient cli("127.0.0.1", port);
  11545. cli.enable_server_certificate_verification(false);
  11546. auto res = cli.Get("/sni");
  11547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11548. EXPECT_EQ("", res->body);
  11549. }
  11550. #endif
  11551. TEST(ClientProblemDetectionTest, ContentProvider) {
  11552. Server svr;
  11553. size_t content_length = 1024 * 1024;
  11554. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11555. res.set_content_provider(
  11556. content_length, "text/plain",
  11557. [&](size_t offset, size_t length, DataSink &sink) {
  11558. auto out_len = std::min(length, static_cast<size_t>(1024));
  11559. std::string out(out_len, '@');
  11560. sink.write(out.data(), out_len);
  11561. return offset < 4096;
  11562. },
  11563. [](bool success) { ASSERT_FALSE(success); });
  11564. });
  11565. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11566. res.set_content_provider(
  11567. 0, "text/plain",
  11568. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11569. EXPECT_TRUE(false);
  11570. return true;
  11571. },
  11572. [](bool success) { ASSERT_FALSE(success); });
  11573. });
  11574. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11575. auto se = detail::scope_exit([&] {
  11576. svr.stop();
  11577. listen_thread.join();
  11578. ASSERT_FALSE(svr.is_running());
  11579. });
  11580. svr.wait_until_ready();
  11581. Client cli("localhost", PORT);
  11582. {
  11583. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11584. size_t /*data_length*/) { return false; });
  11585. ASSERT_FALSE(res);
  11586. }
  11587. {
  11588. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11589. size_t /*data_length*/) { return false; });
  11590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11591. }
  11592. }
  11593. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11594. // A provider that reports success without writing anything and without
  11595. // calling done() used to be handed the same offset and length again on every
  11596. // pass, so it spun for as long as the peer stayed connected.
  11597. Server svr;
  11598. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11599. res.set_content("ok", "text/plain");
  11600. });
  11601. auto port = svr.bind_to_any_port(HOST);
  11602. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11603. auto se = detail::scope_exit([&] {
  11604. svr.stop();
  11605. listen_thread.join();
  11606. ASSERT_FALSE(svr.is_running());
  11607. });
  11608. svr.wait_until_ready();
  11609. std::atomic<int> call_count{0};
  11610. Client cli(HOST, port);
  11611. auto res = cli.Post(
  11612. "/", 1024,
  11613. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11614. // Give up after enough passes to show the spin, so that losing the
  11615. // check below fails this test instead of hanging it.
  11616. return ++call_count < 100;
  11617. },
  11618. "text/plain");
  11619. ASSERT_FALSE(res);
  11620. EXPECT_EQ(Error::Write, res.error());
  11621. EXPECT_EQ(1, call_count.load());
  11622. }
  11623. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11624. // A writer only has to assign `write`. The other three used to be left as
  11625. // empty std::functions, so a provider calling one threw
  11626. // std::bad_function_call out of the thread running it and took the whole
  11627. // process down.
  11628. DataSink sink;
  11629. std::string written;
  11630. sink.write = [&](const char *data, size_t data_len) {
  11631. written.append(data, data_len);
  11632. return true;
  11633. };
  11634. EXPECT_TRUE(sink.is_writable());
  11635. sink.done();
  11636. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11637. EXPECT_TRUE(written.empty());
  11638. }
  11639. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11640. // A sink that cannot carry trailers still has to finish.
  11641. DataSink sink;
  11642. auto done_count = 0;
  11643. sink.done = [&]() { done_count++; };
  11644. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11645. EXPECT_EQ(1, done_count);
  11646. }
  11647. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11648. Server svr;
  11649. const std::string body(4096, 'x');
  11650. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11651. res.set_content_provider(body.size(), "text/plain",
  11652. [&](size_t offset, size_t length, DataSink &sink) {
  11653. sink.write(body.data() + offset, length);
  11654. sink.done();
  11655. return true;
  11656. });
  11657. });
  11658. auto port = svr.bind_to_any_port(HOST);
  11659. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11660. auto se = detail::scope_exit([&] {
  11661. svr.stop();
  11662. listen_thread.join();
  11663. ASSERT_FALSE(svr.is_running());
  11664. });
  11665. svr.wait_until_ready();
  11666. Client cli(HOST, port);
  11667. auto res = cli.Get("/");
  11668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11669. EXPECT_EQ(StatusCode::OK_200, res->status);
  11670. EXPECT_EQ(body, res->body);
  11671. }
  11672. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11673. Server svr;
  11674. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11675. res.set_content_provider(
  11676. 1024, "text/plain",
  11677. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11678. sink.write("hello", 5);
  11679. sink.done(); // short of the 1024 bytes the response promised
  11680. return true;
  11681. });
  11682. });
  11683. auto port = svr.bind_to_any_port(HOST);
  11684. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11685. auto se = detail::scope_exit([&] {
  11686. svr.stop();
  11687. listen_thread.join();
  11688. ASSERT_FALSE(svr.is_running());
  11689. });
  11690. svr.wait_until_ready();
  11691. Client cli(HOST, port);
  11692. cli.set_read_timeout(5, 0);
  11693. // The response is short of its Content-Length, so the client cannot read a
  11694. // complete body. What matters is that this returns at all: a no-op done()
  11695. // would leave the writer looping over a provider that never makes progress.
  11696. auto res = cli.Get("/");
  11697. EXPECT_FALSE(res);
  11698. }
  11699. // Read as the next response by a peer that sees it after a framed body.
  11700. static const std::string smuggled_response =
  11701. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11702. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11703. Server svr;
  11704. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11705. res.set_content_provider(
  11706. 5, "text/plain",
  11707. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11708. auto data = "AAAAA" + smuggled_response;
  11709. sink.write(data.data(), data.size());
  11710. return true;
  11711. });
  11712. });
  11713. thread t = thread([&] { svr.listen(HOST, PORT); });
  11714. auto se = detail::scope_exit([&] {
  11715. svr.stop();
  11716. t.join();
  11717. ASSERT_FALSE(svr.is_running());
  11718. });
  11719. svr.wait_until_ready();
  11720. std::string resp;
  11721. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11722. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11723. resp.clear();
  11724. ASSERT_TRUE(send_request(
  11725. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11726. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11727. }
  11728. TEST(NoContentTest, BodyIsNotSent) {
  11729. Server svr;
  11730. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11731. res.status = StatusCode::NoContent_204;
  11732. res.set_content(smuggled_response, "text/plain");
  11733. });
  11734. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11735. res.status = StatusCode::NotModified_304;
  11736. res.set_chunked_content_provider(
  11737. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11738. sink.write(smuggled_response.data(), smuggled_response.size());
  11739. sink.done();
  11740. return true;
  11741. });
  11742. });
  11743. thread t = thread([&] { svr.listen(HOST, PORT); });
  11744. auto se = detail::scope_exit([&] {
  11745. svr.stop();
  11746. t.join();
  11747. ASSERT_FALSE(svr.is_running());
  11748. });
  11749. svr.wait_until_ready();
  11750. for (auto path : {"/204", "/304"}) {
  11751. std::string resp;
  11752. ASSERT_TRUE(send_request(
  11753. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11754. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11755. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11756. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11757. }
  11758. }
  11759. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11760. Server svr;
  11761. std::atomic<bool> smuggled(false);
  11762. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11763. res.set_content("ok", "text/plain");
  11764. });
  11765. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11766. smuggled = true;
  11767. });
  11768. auto port = svr.bind_to_any_port(HOST);
  11769. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11770. auto se = detail::scope_exit([&] {
  11771. svr.stop();
  11772. listen_thread.join();
  11773. ASSERT_FALSE(svr.is_running());
  11774. });
  11775. svr.wait_until_ready();
  11776. // What follows the body would be read as the next request.
  11777. Client cli(HOST, port);
  11778. auto res = cli.Post(
  11779. "/", 5,
  11780. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11781. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11782. sink.write(data.data(), data.size());
  11783. return true;
  11784. },
  11785. "text/plain");
  11786. ASSERT_FALSE(res);
  11787. EXPECT_EQ(Error::Write, res.error());
  11788. EXPECT_FALSE(smuggled);
  11789. }
  11790. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11791. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11792. // The compressed path builds the whole body before connecting, so this
  11793. // fails client-side and never reaches a server.
  11794. Client cli(HOST, PORT);
  11795. cli.set_compress(true);
  11796. auto res = cli.Post(
  11797. "/", 1024,
  11798. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11799. sink.write("hello", 5);
  11800. sink.done(); // short of the 1024 bytes the request announced
  11801. return true;
  11802. },
  11803. "text/plain");
  11804. ASSERT_FALSE(res);
  11805. EXPECT_EQ(Error::Write, res.error());
  11806. }
  11807. #endif
  11808. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11809. Server svr;
  11810. svr.set_error_handler([](Request const &, Response &res) -> void {
  11811. res.set_chunked_content_provider(
  11812. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11813. sink.os << "hello";
  11814. sink.os << "world";
  11815. sink.done();
  11816. return true;
  11817. });
  11818. });
  11819. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11820. auto se = detail::scope_exit([&] {
  11821. svr.stop();
  11822. listen_thread.join();
  11823. ASSERT_FALSE(svr.is_running());
  11824. });
  11825. svr.wait_until_ready();
  11826. Client cli("localhost", PORT);
  11827. auto res = cli.Get("/");
  11828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11829. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11830. EXPECT_EQ("helloworld", res->body);
  11831. }
  11832. // A body set after a content provider must replace it, not be sent through it.
  11833. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11834. Server svr;
  11835. svr.set_mount_point("/", "./www");
  11836. svr.set_file_request_handler([](const Request &req, Response &res) {
  11837. if (req.path == "/dir/test.html") {
  11838. res.status = StatusCode::Forbidden_403;
  11839. res.set_content(std::string(5000, 'D'), "text/plain");
  11840. } else if (req.path == "/file") {
  11841. res.status = StatusCode::Forbidden_403;
  11842. res.body = "Denied";
  11843. }
  11844. });
  11845. auto port = svr.bind_to_any_port(HOST);
  11846. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11847. auto se = detail::scope_exit([&] {
  11848. svr.stop();
  11849. t.join();
  11850. ASSERT_FALSE(svr.is_running());
  11851. });
  11852. svr.wait_until_ready();
  11853. Client cli(HOST, port);
  11854. {
  11855. auto res = cli.Get("/dir/test.html");
  11856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11857. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11858. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11859. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11860. }
  11861. {
  11862. auto res = cli.Get("/file");
  11863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11864. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11865. EXPECT_EQ("Denied", res->body);
  11866. }
  11867. {
  11868. auto res = cli.Get("/dir/index.html");
  11869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11870. EXPECT_EQ(StatusCode::OK_200, res->status);
  11871. EXPECT_EQ(0U, res->body.find("<html>"));
  11872. }
  11873. }
  11874. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11875. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11876. Server svr;
  11877. std::vector<bool> released;
  11878. std::mutex released_mutex;
  11879. auto releaser = [&](bool success) {
  11880. std::lock_guard<std::mutex> guard(released_mutex);
  11881. released.push_back(success);
  11882. };
  11883. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11884. return sink.write(&"hello"[offset], length);
  11885. };
  11886. svr.Get("/sized", [&](const Request &, Response &res) {
  11887. res.status = StatusCode::NotFound_404;
  11888. res.set_content_provider(5, "text/plain", provider, releaser);
  11889. });
  11890. svr.Get("/chunked", [&](const Request &, Response &res) {
  11891. res.status = StatusCode::ServiceUnavailable_503;
  11892. res.set_chunked_content_provider(
  11893. "text/plain",
  11894. [](size_t, DataSink &sink) {
  11895. sink.os << "chunk";
  11896. sink.done();
  11897. return true;
  11898. },
  11899. releaser);
  11900. });
  11901. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11902. res.set_content_provider(5, "text/plain", provider, releaser);
  11903. throw std::runtime_error("after the provider");
  11904. });
  11905. svr.set_error_handler([](const Request &req, Response &res) {
  11906. // Leave the exception handler's content to it.
  11907. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11908. res.set_content(std::string(1000, 'E'), "text/html");
  11909. return Server::HandlerResponse::Handled;
  11910. });
  11911. svr.set_exception_handler(
  11912. [](const Request &, Response &res, std::exception_ptr) {
  11913. res.status = StatusCode::InternalServerError_500;
  11914. res.set_content(std::string(1000, 'X'), "text/html");
  11915. });
  11916. auto port = svr.bind_to_any_port(HOST);
  11917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11918. auto se = detail::scope_exit([&] {
  11919. svr.stop();
  11920. t.join();
  11921. ASSERT_FALSE(svr.is_running());
  11922. });
  11923. svr.wait_until_ready();
  11924. Client cli(HOST, port);
  11925. {
  11926. auto res = cli.Get("/sized");
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11929. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11930. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11931. }
  11932. {
  11933. auto res = cli.Get("/chunked");
  11934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11935. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11936. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11937. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11938. }
  11939. {
  11940. auto res = cli.Get("/throw");
  11941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11942. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11943. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11944. }
  11945. std::lock_guard<std::mutex> guard(released_mutex);
  11946. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11947. }
  11948. #endif
  11949. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11950. Server svr;
  11951. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11952. return sink.write(&"abc"[offset], length);
  11953. };
  11954. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11955. res.set_file_content("./www/dir/test.html");
  11956. res.set_content("body", "text/plain");
  11957. });
  11958. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11959. res.set_content(std::string(100, 'B'), "text/plain");
  11960. res.set_file_content("./www/dir/test.html");
  11961. });
  11962. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11963. res.set_content(std::string(100, 'B'), "text/plain");
  11964. res.set_content_provider(3, "text/x-provider", abc);
  11965. });
  11966. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11967. res.set_content_provider(3, "text/x-provider", abc);
  11968. res.set_content(std::string(100, 'B'), "text/plain");
  11969. });
  11970. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11971. res.set_content_provider(3, "text/x-provider", abc);
  11972. res.set_file_content("./www/dir/test.html", "text/x-file");
  11973. });
  11974. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11975. res.set_file_content("./www/dir/test.html");
  11976. res.set_header("Content-Type", "text/x-handler");
  11977. });
  11978. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11979. res.set_content_provider(3, "text/plain", abc);
  11980. res.body = "direct";
  11981. });
  11982. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11983. res.set_file_content("./www/dir/test.html");
  11984. res.body = "direct";
  11985. });
  11986. auto port = svr.bind_to_any_port(HOST);
  11987. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11988. auto se = detail::scope_exit([&] {
  11989. svr.stop();
  11990. t.join();
  11991. ASSERT_FALSE(svr.is_running());
  11992. });
  11993. svr.wait_until_ready();
  11994. Client cli(HOST, port);
  11995. auto expect_body = [&](const char *path, const std::string &body,
  11996. const std::string &type) {
  11997. // Uncompressed, so Content-Length can be compared with the body.
  11998. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11999. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12000. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12001. EXPECT_EQ(body, res->body) << path;
  12002. EXPECT_EQ(std::to_string(body.size()),
  12003. res->get_header_value("Content-Length"))
  12004. << path;
  12005. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12006. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12007. };
  12008. expect_body("/file-then-body", "body", "text/plain");
  12009. expect_body("/body-then-file", "test.html", "text/html");
  12010. expect_body("/body-then-provider", "abc", "text/x-provider");
  12011. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12012. expect_body("/provider-then-file", "test.html", "text/x-file");
  12013. expect_body("/file-then-header", "test.html", "text/x-handler");
  12014. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12015. expect_body("/file-then-direct-body", "direct", "text/plain");
  12016. // Ranges are checked against the body, not the dropped provider.
  12017. {
  12018. auto res = cli.Get("/provider-then-direct-body",
  12019. Headers{{make_range_header({{1, 2}})}});
  12020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12022. EXPECT_EQ("ir", res->body);
  12023. }
  12024. {
  12025. auto res = cli.Get("/file-then-direct-body",
  12026. Headers{{make_range_header({{7, 8}})}});
  12027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12028. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12029. }
  12030. }
  12031. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12032. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12033. const char *path = "./truncated_while_served.txt";
  12034. const size_t size = 32 * 1024 * 1024;
  12035. {
  12036. std::ofstream f(path, std::ios::binary);
  12037. f << std::string(size, 'x');
  12038. }
  12039. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12040. // Over TLS, where the bytes are encrypted in this process rather than
  12041. // copied by send().
  12042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12043. svr.Get("/file", [&](const Request &, Response &res) {
  12044. res.set_file_content(path, "text/plain");
  12045. });
  12046. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12047. auto se = detail::scope_exit([&] {
  12048. svr.stop();
  12049. thread.join();
  12050. ASSERT_FALSE(svr.is_running());
  12051. });
  12052. svr.wait_until_ready();
  12053. // The file shrinks once the first bytes are in, as a rewrite in place
  12054. // would, and reading the mapping past its new end used to raise SIGBUS.
  12055. SSLClient cli(HOST, PORT);
  12056. cli.enable_server_certificate_verification(false);
  12057. size_t received = 0;
  12058. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12059. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12060. received += len;
  12061. return true;
  12062. });
  12063. EXPECT_FALSE(res);
  12064. EXPECT_LT(received, size);
  12065. }
  12066. #endif
  12067. // Forward declaration (see the base64_encode note).
  12068. namespace httplib {
  12069. namespace detail {
  12070. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12071. const std::string &content_type,
  12072. EncodingType encoding);
  12073. } // namespace detail
  12074. } // namespace httplib
  12075. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12076. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12077. ASSERT_TRUE(mm->is_open());
  12078. Response res;
  12079. detail::set_file_content_provider(res, mm, "text/html",
  12080. detail::EncodingType::None);
  12081. std::string out;
  12082. DataSink sink;
  12083. sink.write = [&](const char *d, size_t l) {
  12084. out.append(d, l);
  12085. return true;
  12086. };
  12087. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12088. EXPECT_EQ("test.html", out);
  12089. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12090. EXPECT_EQ("test.html", out);
  12091. }
  12092. TEST(LongPollingTest, ClientCloseDetection) {
  12093. Server svr;
  12094. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12095. res.set_chunked_content_provider(
  12096. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12097. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12098. sink.os << "hello";
  12099. auto count = 10;
  12100. while (count > 0 && sink.is_writable()) {
  12101. this_thread::sleep_for(chrono::milliseconds(10));
  12102. count--;
  12103. }
  12104. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12105. return true;
  12106. });
  12107. });
  12108. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12109. auto se = detail::scope_exit([&] {
  12110. svr.stop();
  12111. listen_thread.join();
  12112. ASSERT_FALSE(svr.is_running());
  12113. });
  12114. svr.wait_until_ready();
  12115. Client cli("localhost", PORT);
  12116. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12117. EXPECT_EQ("hello", string(data, data_length));
  12118. return false; // close the socket immediately.
  12119. });
  12120. ASSERT_FALSE(res);
  12121. }
  12122. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12123. Server svr;
  12124. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12125. res.set_chunked_content_provider(
  12126. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12127. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12128. sink.os << "hello";
  12129. EXPECT_TRUE(sink.os.good());
  12130. // Wait for the client to close the connection
  12131. auto count = 10;
  12132. while (count > 0 && sink.is_writable()) {
  12133. this_thread::sleep_for(chrono::milliseconds(10));
  12134. count--;
  12135. }
  12136. // After client disconnect, write repeatedly until the socket
  12137. // write actually fails (small writes may be absorbed by the
  12138. // kernel buffer)
  12139. std::string chunk(1024, 'x');
  12140. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12141. sink.os << chunk;
  12142. }
  12143. EXPECT_TRUE(sink.os.fail());
  12144. return true;
  12145. });
  12146. });
  12147. auto port = svr.bind_to_any_port("localhost");
  12148. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12149. auto se = detail::scope_exit([&] {
  12150. svr.stop();
  12151. listen_thread.join();
  12152. ASSERT_FALSE(svr.is_running());
  12153. });
  12154. svr.wait_until_ready();
  12155. Client cli("localhost", port);
  12156. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12157. EXPECT_EQ("hello", string(data, data_length));
  12158. return false; // close the socket immediately.
  12159. });
  12160. ASSERT_FALSE(res);
  12161. }
  12162. TEST(GetWithParametersTest, GetWithParameters) {
  12163. Server svr;
  12164. svr.Get("/", [&](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("/params", [&](const Request &req, Response &) {
  12170. EXPECT_EQ("world", req.get_param_value("hello"));
  12171. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12172. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12173. });
  12174. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12175. EXPECT_EQ("resource-id", req.matches[1]);
  12176. EXPECT_EQ("foo", req.get_param_value("param1"));
  12177. EXPECT_EQ("bar", req.get_param_value("param2"));
  12178. });
  12179. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12180. EXPECT_EQ("user-id", req.path_params.at("id"));
  12181. EXPECT_EQ("foo", req.get_param_value("param1"));
  12182. EXPECT_EQ("bar", req.get_param_value("param2"));
  12183. });
  12184. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12185. auto se = detail::scope_exit([&] {
  12186. svr.stop();
  12187. listen_thread.join();
  12188. ASSERT_FALSE(svr.is_running());
  12189. });
  12190. svr.wait_until_ready();
  12191. {
  12192. Client cli(HOST, PORT);
  12193. Params params;
  12194. params.emplace("hello", "world");
  12195. params.emplace("hello2", "world2");
  12196. params.emplace("hello3", "world3");
  12197. auto res = cli.Get("/", params, Headers{});
  12198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12199. EXPECT_EQ(StatusCode::OK_200, res->status);
  12200. }
  12201. {
  12202. Client cli(HOST, PORT);
  12203. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12205. EXPECT_EQ(StatusCode::OK_200, res->status);
  12206. }
  12207. {
  12208. Client cli(HOST, PORT);
  12209. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12211. EXPECT_EQ(StatusCode::OK_200, res->status);
  12212. }
  12213. {
  12214. Client cli(HOST, PORT);
  12215. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12217. EXPECT_EQ(StatusCode::OK_200, res->status);
  12218. }
  12219. }
  12220. TEST(GetWithParametersTest, GetWithParameters2) {
  12221. Server svr;
  12222. svr.Get("/", [&](const Request &req, Response &res) {
  12223. auto text = req.get_param_value("hello");
  12224. res.set_content(text, "text/plain");
  12225. });
  12226. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12227. auto se = detail::scope_exit([&] {
  12228. svr.stop();
  12229. listen_thread.join();
  12230. ASSERT_FALSE(svr.is_running());
  12231. });
  12232. svr.wait_until_ready();
  12233. Client cli("localhost", PORT);
  12234. Params params;
  12235. params.emplace("hello", "world");
  12236. std::string body;
  12237. auto res = cli.Get("/", params, Headers{},
  12238. [&](const char *data, size_t data_length) {
  12239. body.append(data, data_length);
  12240. return true;
  12241. });
  12242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12243. EXPECT_EQ(StatusCode::OK_200, res->status);
  12244. EXPECT_EQ("world", body);
  12245. }
  12246. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12247. Server svr;
  12248. svr.Get("/search", [&](const Request &req, Response &res) {
  12249. auto q = req.get_param_value("q");
  12250. res.set_content(q, "text/plain");
  12251. });
  12252. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12253. auto se = detail::scope_exit([&] {
  12254. svr.stop();
  12255. listen_thread.join();
  12256. ASSERT_FALSE(svr.is_running());
  12257. });
  12258. svr.wait_until_ready();
  12259. Client cli("localhost", PORT);
  12260. // Verify that Get(path, params) works without requiring Headers argument
  12261. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12263. EXPECT_EQ(StatusCode::OK_200, res->status);
  12264. EXPECT_EQ("cpp-httplib", res->body);
  12265. }
  12266. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12267. auto host = "httpbingo.org";
  12268. auto path = std::string{"/range/32"};
  12269. #ifdef CPPHTTPLIB_SSL_ENABLED
  12270. SSLClient cli(host);
  12271. #else
  12272. Client cli(host);
  12273. #endif
  12274. cli.set_default_headers({make_range_header({{1, 10}})});
  12275. cli.set_connection_timeout(5);
  12276. {
  12277. auto res = cli.Get(path);
  12278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12279. EXPECT_EQ("bcdefghijk", res->body);
  12280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12281. }
  12282. {
  12283. auto res = cli.Get(path);
  12284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12285. EXPECT_EQ("bcdefghijk", res->body);
  12286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12287. }
  12288. }
  12289. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12290. Server svr;
  12291. svr.set_default_headers({{"Hello", "World"}});
  12292. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12293. res.set_content("ok", "text/plain");
  12294. });
  12295. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12296. auto se = detail::scope_exit([&] {
  12297. svr.stop();
  12298. listen_thread.join();
  12299. ASSERT_FALSE(svr.is_running());
  12300. });
  12301. svr.wait_until_ready();
  12302. Client cli("localhost", PORT);
  12303. auto res = cli.Get("/");
  12304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12305. EXPECT_EQ(StatusCode::OK_200, res->status);
  12306. EXPECT_EQ("ok", res->body);
  12307. EXPECT_EQ("World", res->get_header_value("Hello"));
  12308. }
  12309. #ifdef CPPHTTPLIB_SSL_ENABLED
  12310. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12312. ASSERT_TRUE(svr.is_valid());
  12313. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12314. std::this_thread::sleep_for(std::chrono::seconds(2));
  12315. res.set_content("a", "text/plain");
  12316. });
  12317. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12318. res.set_content("b", "text/plain");
  12319. });
  12320. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12321. auto se = detail::scope_exit([&] {
  12322. svr.stop();
  12323. listen_thread.join();
  12324. ASSERT_FALSE(svr.is_running());
  12325. });
  12326. svr.wait_until_ready();
  12327. SSLClient cli("localhost", PORT);
  12328. cli.enable_server_certificate_verification(false);
  12329. cli.set_keep_alive(true);
  12330. cli.set_read_timeout(std::chrono::seconds(1));
  12331. auto resa = cli.Get("/a");
  12332. ASSERT_TRUE(!resa);
  12333. EXPECT_EQ(Error::Read, resa.error());
  12334. auto resb = cli.Get("/b");
  12335. ASSERT_TRUE(resb);
  12336. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12337. EXPECT_EQ("b", resb->body);
  12338. }
  12339. // Closing an idle keep-alive connection sends close_notify and returns. The
  12340. // server must not wait for the client's close_notify: an idle client never
  12341. // sends one, so the worker would be held until the read timeout expires, and
  12342. // stop() would wait for it.
  12343. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12345. ASSERT_TRUE(svr.is_valid());
  12346. svr.set_keep_alive_timeout(1);
  12347. svr.set_read_timeout(10, 0);
  12348. svr.Get("/", [](const Request &, Response &res) {
  12349. res.set_content("ok", "text/plain");
  12350. });
  12351. auto port = svr.bind_to_any_port(HOST);
  12352. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12353. auto se = detail::scope_exit([&] {
  12354. if (listen_thread.joinable()) {
  12355. svr.stop();
  12356. listen_thread.join();
  12357. }
  12358. });
  12359. svr.wait_until_ready();
  12360. SSLClient cli(HOST, port);
  12361. cli.enable_server_certificate_verification(false);
  12362. cli.set_keep_alive(true);
  12363. auto res = cli.Get("/");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. EXPECT_EQ(StatusCode::OK_200, res->status);
  12366. // Stay idle past the keep-alive timeout so the server closes the connection.
  12367. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12368. auto start = std::chrono::steady_clock::now();
  12369. svr.stop();
  12370. listen_thread.join();
  12371. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12372. std::chrono::steady_clock::now() - start)
  12373. .count();
  12374. EXPECT_LT(elapsed, 3000);
  12375. }
  12376. #endif
  12377. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12378. protected:
  12379. ServerTestWithAI_PASSIVE()
  12380. : cli_(HOST, PORT)
  12381. #ifdef CPPHTTPLIB_SSL_ENABLED
  12382. ,
  12383. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12384. #endif
  12385. {
  12386. #ifdef CPPHTTPLIB_SSL_ENABLED
  12387. cli_.enable_server_certificate_verification(false);
  12388. #endif
  12389. }
  12390. virtual void SetUp() {
  12391. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12392. res.set_content("Hello World!", "text/plain");
  12393. });
  12394. t_ = thread(
  12395. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12396. svr_.wait_until_ready();
  12397. }
  12398. virtual void TearDown() {
  12399. svr_.stop();
  12400. t_.join();
  12401. }
  12402. #ifdef CPPHTTPLIB_SSL_ENABLED
  12403. SSLClient cli_;
  12404. SSLServer svr_;
  12405. #else
  12406. Client cli_;
  12407. Server svr_;
  12408. #endif
  12409. thread t_;
  12410. };
  12411. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12412. auto res = cli_.Get("/hi");
  12413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12414. EXPECT_EQ(StatusCode::OK_200, res->status);
  12415. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12416. EXPECT_EQ("Hello World!", res->body);
  12417. }
  12418. class ServerUpDownTest : public ::testing::Test {
  12419. protected:
  12420. ServerUpDownTest() : cli_(HOST, PORT) {}
  12421. virtual void SetUp() {
  12422. t_ = thread([&]() {
  12423. svr_.bind_to_any_port(HOST);
  12424. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12425. ASSERT_TRUE(svr_.listen_after_bind());
  12426. });
  12427. svr_.wait_until_ready();
  12428. }
  12429. virtual void TearDown() {
  12430. svr_.stop();
  12431. t_.join();
  12432. }
  12433. Client cli_;
  12434. Server svr_;
  12435. thread t_;
  12436. };
  12437. TEST_F(ServerUpDownTest, QuickStartStop) {
  12438. // Should not crash, especially when run with
  12439. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12440. }
  12441. class PayloadMaxLengthTest : public ::testing::Test {
  12442. protected:
  12443. PayloadMaxLengthTest()
  12444. : cli_(HOST, PORT)
  12445. #ifdef CPPHTTPLIB_SSL_ENABLED
  12446. ,
  12447. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12448. #endif
  12449. {
  12450. #ifdef CPPHTTPLIB_SSL_ENABLED
  12451. cli_.enable_server_certificate_verification(false);
  12452. #endif
  12453. }
  12454. virtual void SetUp() {
  12455. svr_.set_payload_max_length(8);
  12456. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12457. res.set_content("test", "text/plain");
  12458. });
  12459. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12460. svr_.wait_until_ready();
  12461. }
  12462. virtual void TearDown() {
  12463. svr_.stop();
  12464. t_.join();
  12465. }
  12466. #ifdef CPPHTTPLIB_SSL_ENABLED
  12467. SSLClient cli_;
  12468. SSLServer svr_;
  12469. #else
  12470. Client cli_;
  12471. Server svr_;
  12472. #endif
  12473. thread t_;
  12474. };
  12475. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12476. auto res = cli_.Post("/test", "123456789", "text/plain");
  12477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12478. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12479. res = cli_.Post("/test", "12345678", "text/plain");
  12480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12481. EXPECT_EQ(StatusCode::OK_200, res->status);
  12482. }
  12483. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12484. // Test chunked encoding with payload exceeding the 8-byte limit
  12485. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12486. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12488. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12489. }
  12490. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12491. // Test chunked encoding with payload within the 8-byte limit
  12492. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12493. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12495. EXPECT_EQ(StatusCode::OK_200, res->status);
  12496. }
  12497. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12498. // Test using send_request to send chunked data exceeding payload limit
  12499. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12500. "Host: " +
  12501. std::string(HOST) + ":" + std::to_string(PORT) +
  12502. "\r\n"
  12503. "Transfer-Encoding: chunked\r\n"
  12504. "Connection: close\r\n"
  12505. "\r\n"
  12506. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12507. "0123456789\r\n"
  12508. "0\r\n" // End chunk
  12509. "\r\n";
  12510. std::string response;
  12511. bool result = send_request(1, chunked_request, &response);
  12512. if (!result) {
  12513. // If send_request fails, it might be because the server closed the
  12514. // connection due to payload limit enforcement, which is acceptable
  12515. SUCCEED()
  12516. << "Server rejected oversized chunked request (connection closed)";
  12517. } else {
  12518. // If we got a response, check if it's an error response or connection was
  12519. // closed early Short response length indicates connection was closed due to
  12520. // payload limit
  12521. if (response.length() <= 10) {
  12522. SUCCEED() << "Server closed connection for oversized chunked request";
  12523. } else {
  12524. // Check for error status codes
  12525. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12526. response.find("Payload Too Large") != std::string::npos ||
  12527. response.find("400") != std::string::npos);
  12528. }
  12529. }
  12530. }
  12531. class LargePayloadMaxLengthTest : public ::testing::Test {
  12532. protected:
  12533. LargePayloadMaxLengthTest()
  12534. : cli_(HOST, PORT)
  12535. #ifdef CPPHTTPLIB_SSL_ENABLED
  12536. ,
  12537. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12538. #endif
  12539. {
  12540. #ifdef CPPHTTPLIB_SSL_ENABLED
  12541. cli_.enable_server_certificate_verification(false);
  12542. #endif
  12543. }
  12544. virtual void SetUp() {
  12545. // Set 10MB payload limit
  12546. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12547. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12548. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12549. res.set_content("Large payload test", "text/plain");
  12550. });
  12551. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12552. svr_.wait_until_ready();
  12553. }
  12554. virtual void TearDown() {
  12555. svr_.stop();
  12556. t_.join();
  12557. }
  12558. #ifdef CPPHTTPLIB_SSL_ENABLED
  12559. SSLClient cli_;
  12560. SSLServer svr_;
  12561. #else
  12562. Client cli_;
  12563. Server svr_;
  12564. #endif
  12565. thread t_;
  12566. };
  12567. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12568. // Test chunked encoding with payload within 10MB limit
  12569. std::string medium_payload(5 * 1024 * 1024,
  12570. 'A'); // 5MB payload, within 10MB limit
  12571. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12573. EXPECT_EQ(StatusCode::OK_200, res->status);
  12574. }
  12575. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12576. // Test chunked encoding with payload exceeding 10MB limit
  12577. std::string large_payload(12 * 1024 * 1024,
  12578. 'B'); // 12MB payload, exceeds 10MB limit
  12579. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12580. // Server may either return 413 or close the connection
  12581. if (res) {
  12582. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12583. } else {
  12584. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12585. }
  12586. }
  12587. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12588. Server svr;
  12589. svr.Get("/", [](const Request &, Response &res) {
  12590. // Claims the most the client accepts, far more than it sends, then drops
  12591. // the connection.
  12592. res.set_content_provider(std::string().max_size(), "text/plain",
  12593. [](size_t, size_t, DataSink &sink) {
  12594. sink.write("abc", 3);
  12595. return false;
  12596. });
  12597. });
  12598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12599. auto se = detail::scope_exit([&] {
  12600. svr.stop();
  12601. thread.join();
  12602. ASSERT_FALSE(svr.is_running());
  12603. });
  12604. svr.wait_until_ready();
  12605. Client cli(HOST, PORT);
  12606. cli.set_payload_max_length(0);
  12607. EXPECT_FALSE(cli.Get("/"));
  12608. }
  12609. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12610. // Stream API does, not as a plain read failure
  12611. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12612. Server svr;
  12613. svr.Get("/big", [](const Request &, Response &res) {
  12614. res.set_content(std::string(100000, 'b'), "text/plain");
  12615. });
  12616. auto port = svr.bind_to_any_port(HOST);
  12617. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12618. auto se = detail::scope_exit([&] {
  12619. svr.stop();
  12620. thread.join();
  12621. });
  12622. svr.wait_until_ready();
  12623. Client cli(HOST, port);
  12624. cli.set_payload_max_length(1000);
  12625. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12626. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12627. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12628. [](const char *, size_t) { return true; });
  12629. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12630. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12631. // Small on the wire, over the limit once decompressed
  12632. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12633. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12634. #endif
  12635. }
  12636. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12637. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12638. // path.
  12639. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12640. Server svr;
  12641. const size_t LIMIT = 64 * 1024; // 64KB
  12642. svr.set_payload_max_length(LIMIT);
  12643. size_t total = 0;
  12644. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12645. const ContentReader &content_reader) {
  12646. content_reader([&](const char * /*data*/, size_t len) {
  12647. total += len;
  12648. return true;
  12649. });
  12650. res.status = 200;
  12651. res.set_content("stream_ok", "text/plain");
  12652. });
  12653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12654. auto se = detail::scope_exit([&] {
  12655. svr.stop();
  12656. thread.join();
  12657. ASSERT_FALSE(svr.is_running());
  12658. });
  12659. svr.wait_until_ready();
  12660. // Prepare 256KB raw data and gzip-compress it
  12661. std::string raw(256 * 1024, 'A');
  12662. std::string gz;
  12663. {
  12664. z_stream zs{};
  12665. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12666. Z_DEFAULT_STRATEGY);
  12667. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12668. zs.avail_in = static_cast<uInt>(raw.size());
  12669. char outbuf[4096];
  12670. int ret;
  12671. do {
  12672. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12673. zs.avail_out = sizeof(outbuf);
  12674. ret = deflate(&zs, Z_FINISH);
  12675. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12676. } while (ret != Z_STREAM_END);
  12677. deflateEnd(&zs);
  12678. }
  12679. Client cli(HOST, PORT);
  12680. cli.set_connection_timeout(std::chrono::seconds(5));
  12681. Headers headers = {{"Content-Encoding", "gzip"}};
  12682. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12683. "application/octet-stream");
  12684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12685. // Server must reject oversized decompressed payloads with 413.
  12686. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12687. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12688. EXPECT_LE(total, LIMIT);
  12689. }
  12690. #endif
  12691. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12692. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12693. // the payload must be passed through untouched instead of being rejected.
  12694. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12695. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12696. Server svr;
  12697. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12698. res.set_content(body, "image/jpeg");
  12699. res.set_header("Content-Encoding", "UTF-8");
  12700. });
  12701. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12702. res.set_content(body, "image/jpeg");
  12703. res.set_header("Content-Encoding", "identity");
  12704. });
  12705. svr.Post("/echo", [](const Request &req, Response &res) {
  12706. res.set_content(req.body, "image/jpeg");
  12707. });
  12708. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12709. auto se = detail::scope_exit([&] {
  12710. svr.stop();
  12711. t.join();
  12712. ASSERT_FALSE(svr.is_running());
  12713. });
  12714. svr.wait_until_ready();
  12715. Client cli(HOST, PORT);
  12716. {
  12717. auto res = cli.Get("/image");
  12718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12719. EXPECT_EQ(StatusCode::OK_200, res->status);
  12720. EXPECT_EQ(body, res->body);
  12721. }
  12722. {
  12723. auto res = cli.Get("/identity");
  12724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12725. EXPECT_EQ(StatusCode::OK_200, res->status);
  12726. EXPECT_EQ(body, res->body);
  12727. }
  12728. {
  12729. // The same applies to a request body reaching the server.
  12730. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12731. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12733. EXPECT_EQ(StatusCode::OK_200, res->status);
  12734. EXPECT_EQ(body, res->body);
  12735. }
  12736. }
  12737. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12738. // gzip-encoded response even when the build has no zlib support.
  12739. static const char GZIPPED_HELLO_WORLD[] = {
  12740. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12741. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12742. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12743. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12744. // A content coding is a whole token, not something the field value merely
  12745. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12746. // as "fibre" look like Brotli, and turned a multi-coding value like
  12747. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12748. // it was never meant to see.
  12749. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12750. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12751. Server svr;
  12752. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12753. res.set_content(body, "image/jpeg");
  12754. res.set_header("Content-Encoding", "fibre");
  12755. });
  12756. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12757. res.set_content(body, "image/jpeg");
  12758. res.set_header("Content-Encoding", "gzip, br");
  12759. });
  12760. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12761. res.set_content(body, "image/jpeg");
  12762. res.set_header("Content-Encoding", "x-zstd-ish");
  12763. });
  12764. auto port = svr.bind_to_any_port(HOST);
  12765. thread t = thread([&]() { svr.listen_after_bind(); });
  12766. auto se = detail::scope_exit([&] {
  12767. svr.stop();
  12768. t.join();
  12769. ASSERT_FALSE(svr.is_running());
  12770. });
  12771. svr.wait_until_ready();
  12772. Client cli(HOST, port);
  12773. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12774. auto res = cli.Get(path);
  12775. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12776. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12777. // Not a coding we recognize, so the payload comes back untouched
  12778. EXPECT_EQ(body, res->body) << path;
  12779. }
  12780. }
  12781. // A content coding cpp-httplib recognizes but was not built with must be
  12782. // reported as such. Handing the still-compressed payload back to the caller
  12783. // would silently corrupt it.
  12784. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12785. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12786. Server svr;
  12787. // "image/jpeg" keeps the server from applying a content coding of its own,
  12788. // so the hand-crafted Content-Encoding below survives.
  12789. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12790. res.set_content(gzipped, "image/jpeg");
  12791. res.set_header("Content-Encoding", "gzip");
  12792. });
  12793. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12794. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12795. res.set_content(gzipped, "image/jpeg");
  12796. res.set_header("Content-Encoding", "GZIP");
  12797. });
  12798. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12799. auto se = detail::scope_exit([&] {
  12800. svr.stop();
  12801. t.join();
  12802. ASSERT_FALSE(svr.is_running());
  12803. });
  12804. svr.wait_until_ready();
  12805. Client cli(HOST, PORT);
  12806. {
  12807. auto res = cli.Get("/gzipped");
  12808. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12810. EXPECT_EQ("Hello World!", res->body);
  12811. #else
  12812. ASSERT_FALSE(res);
  12813. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12814. #endif
  12815. }
  12816. {
  12817. // open_stream() must behave the same way.
  12818. auto handle = cli.open_stream("GET", "/gzipped");
  12819. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12820. ASSERT_TRUE(handle.is_valid());
  12821. std::string received;
  12822. char buf[256];
  12823. ssize_t n;
  12824. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12825. received.append(buf, static_cast<size_t>(n));
  12826. }
  12827. EXPECT_EQ("Hello World!", received);
  12828. #else
  12829. EXPECT_FALSE(handle.is_valid());
  12830. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12831. #endif
  12832. }
  12833. {
  12834. // A differently-cased coding must not be mistaken for an unknown one, or
  12835. // the body would be handed back still compressed.
  12836. auto res = cli.Get("/gzipped-uppercase");
  12837. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12839. EXPECT_EQ("Hello World!", res->body);
  12840. #else
  12841. ASSERT_FALSE(res);
  12842. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12843. #endif
  12844. }
  12845. }
  12846. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12847. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12848. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12849. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12850. // body a second time and appending a second Content-Encoding field line, so
  12851. // clients that decode one coding per listed value handed back raw gzip bytes.
  12852. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12853. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12854. Server svr;
  12855. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12856. // keeps the server from applying a coding of its own.
  12857. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12858. res.set_content(gzipped, "text/plain");
  12859. res.set_header("Content-Encoding", "gzip");
  12860. });
  12861. auto port = svr.bind_to_any_port(HOST);
  12862. thread t = thread([&]() { svr.listen_after_bind(); });
  12863. auto se = detail::scope_exit([&] {
  12864. svr.stop();
  12865. t.join();
  12866. ASSERT_FALSE(svr.is_running());
  12867. });
  12868. svr.wait_until_ready();
  12869. Client cli(HOST, port);
  12870. Headers headers = {{"Accept-Encoding", "gzip"}};
  12871. auto res = cli.Get("/pre-gzipped", headers);
  12872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12873. EXPECT_EQ(StatusCode::OK_200, res->status);
  12874. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12875. EXPECT_EQ("Hello World!", res->body);
  12876. }
  12877. // set_compress(false) sends every handler response as it is, buffered or
  12878. // streamed
  12879. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12880. const std::string text(1000, 'a');
  12881. Server svr;
  12882. svr.set_compress(false);
  12883. svr.Get("/buffered", [&](const Request &, Response &res) {
  12884. res.set_content(text, "text/plain");
  12885. });
  12886. svr.Get("/streamed", [&](const Request &, Response &res) {
  12887. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12888. sink.write(text.data(), text.size());
  12889. sink.done();
  12890. return true;
  12891. });
  12892. });
  12893. auto port = svr.bind_to_any_port(HOST);
  12894. ASSERT_LT(0, port);
  12895. thread t = thread([&] { svr.listen_after_bind(); });
  12896. auto se = detail::scope_exit([&] {
  12897. svr.stop();
  12898. t.join();
  12899. ASSERT_FALSE(svr.is_running());
  12900. });
  12901. svr.wait_until_ready();
  12902. Client cli(HOST, port);
  12903. cli.set_decompress(false);
  12904. for (auto path : {"/buffered", "/streamed"}) {
  12905. SCOPED_TRACE(path);
  12906. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12908. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12909. EXPECT_EQ(text, res->body);
  12910. }
  12911. }
  12912. // A chunked provider settles its coding where the headers are written and
  12913. // reuses it at write time. Both ends of that have to hold: a handler's own
  12914. // Content-Encoding suppresses the coding, and a response without one is still
  12915. // compressed as it always was.
  12916. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12917. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12918. const std::string plain = "Hello World! Hello World! Hello World!";
  12919. Server svr;
  12920. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12921. res.set_header("Content-Encoding", "gzip");
  12922. res.set_chunked_content_provider(
  12923. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12924. sink.write(gzipped.data(), gzipped.size());
  12925. sink.done();
  12926. return true;
  12927. });
  12928. });
  12929. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12930. res.set_chunked_content_provider(
  12931. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12932. sink.write(plain.data(), plain.size());
  12933. sink.done();
  12934. return true;
  12935. });
  12936. });
  12937. auto port = svr.bind_to_any_port(HOST);
  12938. thread t = thread([&]() { svr.listen_after_bind(); });
  12939. auto se = detail::scope_exit([&] {
  12940. svr.stop();
  12941. t.join();
  12942. ASSERT_FALSE(svr.is_running());
  12943. });
  12944. svr.wait_until_ready();
  12945. Client cli(HOST, port);
  12946. Headers headers = {{"Accept-Encoding", "gzip"}};
  12947. {
  12948. auto res = cli.Get("/pre-gzipped", headers);
  12949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12950. EXPECT_EQ(StatusCode::OK_200, res->status);
  12951. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12952. EXPECT_EQ("Hello World!", res->body);
  12953. }
  12954. {
  12955. auto res = cli.Get("/negotiated", headers);
  12956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12957. EXPECT_EQ(StatusCode::OK_200, res->status);
  12958. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12959. EXPECT_EQ(plain, res->body);
  12960. }
  12961. }
  12962. #endif
  12963. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12964. // the same message as the comma-joined one, so both have to be read the same
  12965. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12966. // single gzip coding, and a body the sender says was encoded twice was handed
  12967. // back after one pass, still compressed but presented as decoded.
  12968. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12969. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12970. Server svr;
  12971. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12972. res.set_content(body, "image/jpeg");
  12973. res.headers.emplace("Content-Encoding", "gzip");
  12974. res.headers.emplace("Content-Encoding", "gzip");
  12975. });
  12976. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12977. res.set_content(body, "image/jpeg");
  12978. res.set_header("Content-Encoding", "gzip, gzip");
  12979. });
  12980. auto port = svr.bind_to_any_port(HOST);
  12981. thread t = thread([&]() { svr.listen_after_bind(); });
  12982. auto se = detail::scope_exit([&] {
  12983. svr.stop();
  12984. t.join();
  12985. ASSERT_FALSE(svr.is_running());
  12986. });
  12987. svr.wait_until_ready();
  12988. Client cli(HOST, port);
  12989. // Two codings is not something cpp-httplib decodes, so both representations
  12990. // take the pass-through path rather than one of them being gunzipped once.
  12991. for (const char *path : {"/split", "/joined"}) {
  12992. auto res = cli.Get(path);
  12993. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12994. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12995. EXPECT_EQ(body, res->body) << path;
  12996. }
  12997. }
  12998. // Regression test for DoS vulnerability: a malicious server sending a response
  12999. // without Content-Length header must not cause unbounded memory consumption on
  13000. // the client side. The client should stop reading after a reasonable limit,
  13001. // similar to the server-side set_payload_max_length protection.
  13002. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13003. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13004. #ifndef _WIN32
  13005. signal(SIGPIPE, SIG_IGN);
  13006. #endif
  13007. auto server_thread = std::thread([] {
  13008. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13009. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13010. default_socket_options(srv);
  13011. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13013. sockaddr_in addr{};
  13014. addr.sin_family = AF_INET;
  13015. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13016. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13017. int opt = 1;
  13018. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13019. #ifdef _WIN32
  13020. reinterpret_cast<const char *>(&opt),
  13021. #else
  13022. &opt,
  13023. #endif
  13024. sizeof(opt));
  13025. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13026. ::listen(srv, 1);
  13027. sockaddr_in cli_addr{};
  13028. socklen_t cli_len = sizeof(cli_addr);
  13029. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13030. if (cli != INVALID_SOCKET) {
  13031. char buf[4096];
  13032. ::recv(cli, buf, sizeof(buf), 0);
  13033. // Malicious response: no Content-Length, no chunked encoding
  13034. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13035. "Connection: close\r\n"
  13036. "\r\n";
  13037. ::send(cli,
  13038. #ifdef _WIN32
  13039. static_cast<const char *>(response_header.c_str()),
  13040. static_cast<int>(response_header.size()),
  13041. #else
  13042. response_header.c_str(), response_header.size(),
  13043. #endif
  13044. 0);
  13045. // Send 10MB of data
  13046. std::string chunk(64 * 1024, 'A');
  13047. size_t total_sent = 0;
  13048. while (total_sent < MALICIOUS_DATA_SIZE) {
  13049. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13050. auto sent = ::send(cli,
  13051. #ifdef _WIN32
  13052. static_cast<const char *>(chunk.c_str()),
  13053. static_cast<int>(to_send),
  13054. #else
  13055. chunk.c_str(), to_send,
  13056. #endif
  13057. 0);
  13058. if (sent <= 0) break;
  13059. total_sent += static_cast<size_t>(sent);
  13060. }
  13061. detail::close_socket(cli);
  13062. }
  13063. detail::close_socket(srv);
  13064. });
  13065. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13066. size_t total_read = 0;
  13067. {
  13068. Client cli("127.0.0.1", PORT + 2);
  13069. cli.set_read_timeout(5, 0);
  13070. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13071. auto stream = cli.open_stream("GET", "/malicious");
  13072. ASSERT_TRUE(stream.is_valid());
  13073. char buffer[64 * 1024];
  13074. ssize_t n;
  13075. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13076. total_read += static_cast<size_t>(n);
  13077. }
  13078. } // StreamHandle and Client destroyed here, closing the socket
  13079. server_thread.join();
  13080. // With set_payload_max_length, the client must stop reading before consuming
  13081. // all 10MB. The read loop should be cut off at or near the configured limit.
  13082. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13083. << "Client read " << total_read << " bytes, exceeding the configured "
  13084. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13085. }
  13086. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13087. // the entire response body without truncation.
  13088. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13089. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13090. #ifndef _WIN32
  13091. signal(SIGPIPE, SIG_IGN);
  13092. #endif
  13093. auto server_thread = std::thread([] {
  13094. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13095. default_socket_options(srv);
  13096. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13097. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13098. sockaddr_in addr{};
  13099. addr.sin_family = AF_INET;
  13100. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13101. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13102. int opt = 1;
  13103. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13104. #ifdef _WIN32
  13105. reinterpret_cast<const char *>(&opt),
  13106. #else
  13107. &opt,
  13108. #endif
  13109. sizeof(opt));
  13110. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13111. ::listen(srv, 1);
  13112. sockaddr_in cli_addr{};
  13113. socklen_t cli_len = sizeof(cli_addr);
  13114. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13115. if (cli != INVALID_SOCKET) {
  13116. char buf[4096];
  13117. ::recv(cli, buf, sizeof(buf), 0);
  13118. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13119. "Connection: close\r\n"
  13120. "\r\n";
  13121. ::send(cli,
  13122. #ifdef _WIN32
  13123. static_cast<const char *>(response_header.c_str()),
  13124. static_cast<int>(response_header.size()),
  13125. #else
  13126. response_header.c_str(), response_header.size(),
  13127. #endif
  13128. 0);
  13129. std::string chunk(64 * 1024, 'A');
  13130. size_t total_sent = 0;
  13131. while (total_sent < DATA_SIZE) {
  13132. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13133. auto sent = ::send(cli,
  13134. #ifdef _WIN32
  13135. static_cast<const char *>(chunk.c_str()),
  13136. static_cast<int>(to_send),
  13137. #else
  13138. chunk.c_str(), to_send,
  13139. #endif
  13140. 0);
  13141. if (sent <= 0) break;
  13142. total_sent += static_cast<size_t>(sent);
  13143. }
  13144. #ifdef _WIN32
  13145. ::shutdown(cli, SD_SEND);
  13146. #else
  13147. ::shutdown(cli, SHUT_WR);
  13148. #endif
  13149. // Drain until the client closes its end, ensuring all data is delivered
  13150. char drain[1024];
  13151. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13152. detail::close_socket(cli);
  13153. }
  13154. detail::close_socket(srv);
  13155. });
  13156. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13157. size_t total_read = 0;
  13158. {
  13159. Client cli("127.0.0.1", PORT + 2);
  13160. cli.set_read_timeout(5, 0);
  13161. cli.set_payload_max_length(0); // 0 means no limit
  13162. auto stream = cli.open_stream("GET", "/data");
  13163. ASSERT_TRUE(stream.is_valid());
  13164. char buffer[64 * 1024];
  13165. ssize_t n;
  13166. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13167. total_read += static_cast<size_t>(n);
  13168. }
  13169. }
  13170. server_thread.join();
  13171. EXPECT_EQ(total_read, DATA_SIZE)
  13172. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13173. << " bytes without truncation, but only read " << total_read << " bytes.";
  13174. }
  13175. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13176. // enormous Content-Length must not cause the client to pre-allocate a huge
  13177. // response body buffer. The reservation is capped at payload_max_length_, and
  13178. // the read itself fails when the body exceeds the limit.
  13179. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13180. #ifndef _WIN32
  13181. signal(SIGPIPE, SIG_IGN);
  13182. #endif
  13183. auto server_thread = std::thread([] {
  13184. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13185. default_socket_options(srv);
  13186. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13187. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13188. sockaddr_in addr{};
  13189. addr.sin_family = AF_INET;
  13190. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13191. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13192. int opt = 1;
  13193. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13194. #ifdef _WIN32
  13195. reinterpret_cast<const char *>(&opt),
  13196. #else
  13197. &opt,
  13198. #endif
  13199. sizeof(opt));
  13200. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13201. ::listen(srv, 1);
  13202. sockaddr_in cli_addr{};
  13203. socklen_t cli_len = sizeof(cli_addr);
  13204. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13205. if (cli != INVALID_SOCKET) {
  13206. char buf[4096];
  13207. ::recv(cli, buf, sizeof(buf), 0);
  13208. // Malicious response: claim a 20GB body but send only a tiny payload.
  13209. std::string response = "HTTP/1.1 200 OK\r\n"
  13210. "Content-Length: 20000000000\r\n"
  13211. "\r\n"
  13212. "abc";
  13213. ::send(cli,
  13214. #ifdef _WIN32
  13215. static_cast<const char *>(response.c_str()),
  13216. static_cast<int>(response.size()),
  13217. #else
  13218. response.c_str(), response.size(),
  13219. #endif
  13220. 0);
  13221. detail::close_socket(cli);
  13222. }
  13223. detail::close_socket(srv);
  13224. });
  13225. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13226. {
  13227. Client cli("127.0.0.1", PORT + 2);
  13228. cli.set_read_timeout(5, 0);
  13229. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13230. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13231. // (server claims more bytes than payload_max_length permits), but it must
  13232. // not exhaust memory before getting there.
  13233. auto res = cli.Get("/malicious");
  13234. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13235. }
  13236. server_thread.join();
  13237. }
  13238. // Verify that content_receiver bypasses the default payload_max_length,
  13239. // allowing streaming downloads larger than 100MB without requiring an explicit
  13240. // set_payload_max_length call.
  13241. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13242. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13243. #ifndef _WIN32
  13244. signal(SIGPIPE, SIG_IGN);
  13245. #endif
  13246. auto server_thread = std::thread([] {
  13247. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13248. default_socket_options(srv);
  13249. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13250. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13251. sockaddr_in addr{};
  13252. addr.sin_family = AF_INET;
  13253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13254. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13255. int opt = 1;
  13256. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13257. #ifdef _WIN32
  13258. reinterpret_cast<const char *>(&opt),
  13259. #else
  13260. &opt,
  13261. #endif
  13262. sizeof(opt));
  13263. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13264. ::listen(srv, 1);
  13265. sockaddr_in cli_addr{};
  13266. socklen_t cli_len = sizeof(cli_addr);
  13267. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13268. if (cli != INVALID_SOCKET) {
  13269. char buf[4096];
  13270. ::recv(cli, buf, sizeof(buf), 0);
  13271. // Response with Content-Length larger than default 100MB limit
  13272. auto content_length = std::to_string(DATA_SIZE);
  13273. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13274. "Content-Length: " +
  13275. content_length +
  13276. "\r\n"
  13277. "Connection: close\r\n"
  13278. "\r\n";
  13279. ::send(cli,
  13280. #ifdef _WIN32
  13281. static_cast<const char *>(response_header.c_str()),
  13282. static_cast<int>(response_header.size()),
  13283. #else
  13284. response_header.c_str(), response_header.size(),
  13285. #endif
  13286. 0);
  13287. std::string chunk(64 * 1024, 'A');
  13288. size_t total_sent = 0;
  13289. while (total_sent < DATA_SIZE) {
  13290. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13291. auto sent = ::send(cli,
  13292. #ifdef _WIN32
  13293. static_cast<const char *>(chunk.c_str()),
  13294. static_cast<int>(to_send),
  13295. #else
  13296. chunk.c_str(), to_send,
  13297. #endif
  13298. 0);
  13299. if (sent <= 0) break;
  13300. total_sent += static_cast<size_t>(sent);
  13301. }
  13302. detail::close_socket(cli);
  13303. }
  13304. detail::close_socket(srv);
  13305. });
  13306. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13307. size_t total_received = 0;
  13308. {
  13309. Client cli("127.0.0.1", PORT + 2);
  13310. cli.set_read_timeout(10, 0);
  13311. // Do NOT call set_payload_max_length — use the default 100MB limit
  13312. auto res =
  13313. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13314. total_received += data_length;
  13315. return true;
  13316. });
  13317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13318. EXPECT_EQ(StatusCode::OK_200, res->status);
  13319. }
  13320. server_thread.join();
  13321. EXPECT_EQ(total_received, DATA_SIZE)
  13322. << "With content_receiver, the client should read all " << DATA_SIZE
  13323. << " bytes despite the default 100MB payload_max_length, but only read "
  13324. << total_received << " bytes.";
  13325. }
  13326. // Verify that an explicit set_payload_max_length smaller than the response is
  13327. // enforced even when a content_receiver is used.
  13328. TEST(ClientVulnerabilityTest,
  13329. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13330. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13331. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13332. #ifndef _WIN32
  13333. signal(SIGPIPE, SIG_IGN);
  13334. #endif
  13335. auto server_thread = std::thread([] {
  13336. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13337. default_socket_options(srv);
  13338. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13339. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13340. sockaddr_in addr{};
  13341. addr.sin_family = AF_INET;
  13342. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13343. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13344. int opt = 1;
  13345. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13346. #ifdef _WIN32
  13347. reinterpret_cast<const char *>(&opt),
  13348. #else
  13349. &opt,
  13350. #endif
  13351. sizeof(opt));
  13352. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13353. ::listen(srv, 1);
  13354. sockaddr_in cli_addr{};
  13355. socklen_t cli_len = sizeof(cli_addr);
  13356. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13357. if (cli != INVALID_SOCKET) {
  13358. char buf[4096];
  13359. ::recv(cli, buf, sizeof(buf), 0);
  13360. auto content_length = std::to_string(DATA_SIZE);
  13361. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13362. "Content-Length: " +
  13363. content_length +
  13364. "\r\n"
  13365. "Connection: close\r\n"
  13366. "\r\n";
  13367. ::send(cli,
  13368. #ifdef _WIN32
  13369. static_cast<const char *>(response_header.c_str()),
  13370. static_cast<int>(response_header.size()),
  13371. #else
  13372. response_header.c_str(), response_header.size(),
  13373. #endif
  13374. 0);
  13375. std::string chunk(64 * 1024, 'A');
  13376. size_t total_sent = 0;
  13377. while (total_sent < DATA_SIZE) {
  13378. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13379. auto sent = ::send(cli,
  13380. #ifdef _WIN32
  13381. static_cast<const char *>(chunk.c_str()),
  13382. static_cast<int>(to_send),
  13383. #else
  13384. chunk.c_str(), to_send,
  13385. #endif
  13386. 0);
  13387. if (sent <= 0) break;
  13388. total_sent += static_cast<size_t>(sent);
  13389. }
  13390. detail::close_socket(cli);
  13391. }
  13392. detail::close_socket(srv);
  13393. });
  13394. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13395. size_t total_received = 0;
  13396. {
  13397. Client cli("127.0.0.1", PORT + 2);
  13398. cli.set_read_timeout(10, 0);
  13399. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13400. auto res =
  13401. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13402. total_received += data_length;
  13403. return true;
  13404. });
  13405. // Should fail because 200MB exceeds the explicit 150MB limit
  13406. EXPECT_FALSE(res);
  13407. }
  13408. server_thread.join();
  13409. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13410. << "Client with content_receiver should respect the explicit "
  13411. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13412. << total_received << " bytes.";
  13413. }
  13414. // Verify that an explicit set_payload_max_length larger than the response
  13415. // allows the content_receiver to read all data successfully.
  13416. TEST(ClientVulnerabilityTest,
  13417. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13418. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13419. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13420. #ifndef _WIN32
  13421. signal(SIGPIPE, SIG_IGN);
  13422. #endif
  13423. auto server_thread = std::thread([] {
  13424. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13425. default_socket_options(srv);
  13426. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13427. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13428. sockaddr_in addr{};
  13429. addr.sin_family = AF_INET;
  13430. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13431. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13432. int opt = 1;
  13433. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13434. #ifdef _WIN32
  13435. reinterpret_cast<const char *>(&opt),
  13436. #else
  13437. &opt,
  13438. #endif
  13439. sizeof(opt));
  13440. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13441. ::listen(srv, 1);
  13442. sockaddr_in cli_addr{};
  13443. socklen_t cli_len = sizeof(cli_addr);
  13444. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13445. if (cli != INVALID_SOCKET) {
  13446. char buf[4096];
  13447. ::recv(cli, buf, sizeof(buf), 0);
  13448. auto content_length = std::to_string(DATA_SIZE);
  13449. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13450. "Content-Length: " +
  13451. content_length +
  13452. "\r\n"
  13453. "Connection: close\r\n"
  13454. "\r\n";
  13455. ::send(cli,
  13456. #ifdef _WIN32
  13457. static_cast<const char *>(response_header.c_str()),
  13458. static_cast<int>(response_header.size()),
  13459. #else
  13460. response_header.c_str(), response_header.size(),
  13461. #endif
  13462. 0);
  13463. std::string chunk(64 * 1024, 'A');
  13464. size_t total_sent = 0;
  13465. while (total_sent < DATA_SIZE) {
  13466. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13467. auto sent = ::send(cli,
  13468. #ifdef _WIN32
  13469. static_cast<const char *>(chunk.c_str()),
  13470. static_cast<int>(to_send),
  13471. #else
  13472. chunk.c_str(), to_send,
  13473. #endif
  13474. 0);
  13475. if (sent <= 0) break;
  13476. total_sent += static_cast<size_t>(sent);
  13477. }
  13478. #ifdef _WIN32
  13479. ::shutdown(cli, SD_SEND);
  13480. #else
  13481. ::shutdown(cli, SHUT_WR);
  13482. #endif
  13483. char drain[1024];
  13484. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13485. detail::close_socket(cli);
  13486. }
  13487. detail::close_socket(srv);
  13488. });
  13489. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13490. size_t total_received = 0;
  13491. {
  13492. Client cli("127.0.0.1", PORT + 2);
  13493. cli.set_read_timeout(10, 0);
  13494. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13495. auto res =
  13496. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13497. total_received += data_length;
  13498. return true;
  13499. });
  13500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13501. EXPECT_EQ(StatusCode::OK_200, res->status);
  13502. }
  13503. server_thread.join();
  13504. EXPECT_EQ(total_received, DATA_SIZE)
  13505. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13506. << " bytes (larger than " << DATA_SIZE
  13507. << " bytes response), content_receiver should read all data, but only "
  13508. "read "
  13509. << total_received << " bytes.";
  13510. }
  13511. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13512. // Regression test for "zip bomb" attack on the client side: a malicious server
  13513. // sends a small gzip-compressed response that decompresses to a huge payload.
  13514. // The client must enforce payload_max_length on the decompressed size.
  13515. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13516. constexpr size_t DECOMPRESSED_SIZE =
  13517. 10 * 1024 * 1024; // 10MB after decompression
  13518. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13519. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13520. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13521. std::string compressed;
  13522. {
  13523. httplib::detail::gzip_compressor compressor;
  13524. bool ok =
  13525. compressor.compress(uncompressed.data(), uncompressed.size(),
  13526. /*last=*/true, [&](const char *buf, size_t len) {
  13527. compressed.append(buf, len);
  13528. return true;
  13529. });
  13530. ASSERT_TRUE(ok);
  13531. }
  13532. // Sanity: compressed data should be much smaller than the decompressed size
  13533. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13534. #ifndef _WIN32
  13535. signal(SIGPIPE, SIG_IGN);
  13536. #endif
  13537. // Set up the listening socket in the main thread so the server is guaranteed
  13538. // to be ready before the client connects (eliminates race condition).
  13539. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13540. default_socket_options(srv);
  13541. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13542. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13543. sockaddr_in addr{};
  13544. addr.sin_family = AF_INET;
  13545. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13546. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13547. int opt = 1;
  13548. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13549. #ifdef _WIN32
  13550. reinterpret_cast<const char *>(&opt),
  13551. #else
  13552. &opt,
  13553. #endif
  13554. sizeof(opt));
  13555. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13556. ASSERT_EQ(0, ::listen(srv, 1));
  13557. auto server_thread = std::thread([&compressed, srv] {
  13558. sockaddr_in cli_addr{};
  13559. socklen_t cli_len = sizeof(cli_addr);
  13560. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13561. if (cli != INVALID_SOCKET) {
  13562. // Read the full HTTP request (until \r\n\r\n)
  13563. char buf[4096];
  13564. size_t total = 0;
  13565. while (total < sizeof(buf)) {
  13566. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13567. if (n <= 0) break;
  13568. total += static_cast<size_t>(n);
  13569. // Check for end of headers
  13570. if (total >= 4) {
  13571. std::string req(buf, total);
  13572. if (req.find("\r\n\r\n") != std::string::npos) break;
  13573. }
  13574. }
  13575. // Malicious response: gzip-compressed body, no Content-Length
  13576. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13577. "Content-Encoding: gzip\r\n"
  13578. "Connection: close\r\n"
  13579. "\r\n";
  13580. ::send(cli,
  13581. #ifdef _WIN32
  13582. static_cast<const char *>(response_header.c_str()),
  13583. static_cast<int>(response_header.size()),
  13584. #else
  13585. response_header.c_str(), response_header.size(),
  13586. #endif
  13587. 0);
  13588. // Send the compressed payload (small on the wire, huge when decompressed)
  13589. size_t total_sent = 0;
  13590. while (total_sent < compressed.size()) {
  13591. auto to_send = std::min(compressed.size() - total_sent,
  13592. static_cast<size_t>(64 * 1024));
  13593. auto sent =
  13594. ::send(cli,
  13595. #ifdef _WIN32
  13596. static_cast<const char *>(compressed.c_str() + total_sent),
  13597. static_cast<int>(to_send),
  13598. #else
  13599. compressed.c_str() + total_sent, to_send,
  13600. #endif
  13601. 0);
  13602. if (sent <= 0) break;
  13603. total_sent += static_cast<size_t>(sent);
  13604. }
  13605. detail::close_socket(cli);
  13606. }
  13607. });
  13608. auto se = detail::scope_exit([&] {
  13609. detail::close_socket(srv);
  13610. server_thread.join();
  13611. });
  13612. size_t total_decompressed = 0;
  13613. {
  13614. Client cli("127.0.0.1", PORT + 3);
  13615. cli.set_read_timeout(5, 0);
  13616. cli.set_decompress(true);
  13617. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13618. auto stream = cli.open_stream("GET", "/zipbomb");
  13619. ASSERT_TRUE(stream.is_valid());
  13620. char buffer[64 * 1024];
  13621. ssize_t n;
  13622. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13623. total_decompressed += static_cast<size_t>(n);
  13624. }
  13625. }
  13626. // The decompressed size must be capped by payload_max_length. Without
  13627. // protection, the client would decompress the full 10MB from a tiny
  13628. // compressed payload, enabling a zip bomb DoS attack.
  13629. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13630. << "Client decompressed " << total_decompressed
  13631. << " bytes from a gzip response. The decompressed size should be "
  13632. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13633. }
  13634. #endif
  13635. TEST(HostAndPortPropertiesTest, NoSSL) {
  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, NoSSLWithSimpleAPI) {
  13641. httplib::Client cli("www.google.com:1234");
  13642. ASSERT_EQ("www.google.com", cli.host());
  13643. ASSERT_EQ(1234, cli.port());
  13644. }
  13645. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13646. // Port number that overflows int — should not crash, client becomes invalid
  13647. httplib::Client cli("http://www.google.com:99999999999999999999");
  13648. ASSERT_FALSE(cli.is_valid());
  13649. }
  13650. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13651. // Port 99999 exceeds valid range (1-65535) — should not crash
  13652. httplib::Client cli("http://www.google.com:99999");
  13653. ASSERT_FALSE(cli.is_valid());
  13654. auto res = cli.Get("/");
  13655. EXPECT_FALSE(res);
  13656. EXPECT_EQ(Error::Connection, res.error());
  13657. }
  13658. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13659. httplib::Client cli("http://user:pass@localhost:1234");
  13660. ASSERT_FALSE(cli.is_valid());
  13661. EXPECT_FALSE(cli.Get("/"));
  13662. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13663. }
  13664. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13665. httplib::Client cli("http://www.google.com:80abc");
  13666. ASSERT_FALSE(cli.is_valid());
  13667. }
  13668. #ifdef CPPHTTPLIB_SSL_ENABLED
  13669. TEST(HostAndPortPropertiesTest, SSL) {
  13670. httplib::SSLClient cli("www.google.com");
  13671. ASSERT_EQ("www.google.com", cli.host());
  13672. ASSERT_EQ(443, cli.port());
  13673. }
  13674. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13675. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13676. std::string cert;
  13677. read_file(CA_CERT_FILE, cert);
  13678. httplib::SSLClient httplib_client("www.google.com");
  13679. // Load CA store first time
  13680. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13681. // Load CA store second time (update)
  13682. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13683. // Verify client is still valid and can make connections
  13684. httplib_client.enable_server_certificate_verification(true);
  13685. auto res = httplib_client.Get("/");
  13686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13687. // Google may return 200 or 301 depending on various factors
  13688. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13689. res->status == StatusCode::MovedPermanently_301);
  13690. }
  13691. TEST(SSLClientTest, ServerNameIndication_Online) {
  13692. auto host = "httpbingo.org";
  13693. auto path = std::string{"/get"};
  13694. SSLClient cli(host, 443);
  13695. auto res = cli.Get(path);
  13696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13697. ASSERT_EQ(StatusCode::OK_200, res->status);
  13698. }
  13699. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13700. // Use a site that will cause SSL verification failure due to self-signed cert
  13701. SSLClient cli("self-signed.badssl.com", 443);
  13702. cli.enable_server_certificate_verification(true);
  13703. auto res = cli.Get("/");
  13704. ASSERT_TRUE(!res);
  13705. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13706. // Verify backend error is captured for SSLServerVerification
  13707. // This occurs when certificate verification fails
  13708. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13709. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13710. EXPECT_NE(0UL, res.ssl_backend_error());
  13711. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13712. res.ssl_error());
  13713. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13714. #if !defined(_WIN32) || \
  13715. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13716. // On non-Windows or when Windows Schannel is disabled, the error comes
  13717. // from OpenSSL's verification
  13718. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13719. res.ssl_backend_error());
  13720. #endif
  13721. #endif
  13722. }
  13723. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13724. // Use a site where hostname doesn't match the certificate
  13725. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13726. SSLClient cli("wrong.host.badssl.com", 443);
  13727. cli.enable_server_certificate_verification(true);
  13728. cli.enable_server_hostname_verification(true);
  13729. auto res = cli.Get("/");
  13730. ASSERT_TRUE(!res);
  13731. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13732. // Verify backend error is captured for hostname verification failure
  13733. EXPECT_NE(0UL, res.ssl_backend_error());
  13734. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13735. res.ssl_error());
  13736. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13737. #if !defined(_WIN32) || \
  13738. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13739. // On non-Windows or when Windows Schannel is disabled, the error comes
  13740. // from OpenSSL's hostname verification
  13741. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13742. res.ssl_backend_error());
  13743. #endif
  13744. #endif
  13745. }
  13746. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13747. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13748. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13749. SSLClient cli("www.google.com", 443);
  13750. cli.enable_server_certificate_verification(true);
  13751. auto res = cli.Get("/");
  13752. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13753. }
  13754. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13755. SSLClient cli("www.google.com", 443);
  13756. cli.enable_server_certificate_verification(true);
  13757. cli.enable_windows_certificate_verification(false);
  13758. auto res = cli.Get("/");
  13759. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13760. }
  13761. // The server sends an intermediate cross-signed by a root Windows trusts,
  13762. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13763. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13764. SSLClient cli("accounts.spotify.com", 443);
  13765. auto res = cli.Get("/");
  13766. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13767. << " ssl_backend_error=" << res.ssl_backend_error();
  13768. }
  13769. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13770. // policy status, which no backend reports for a self-signed certificate.
  13771. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13772. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13773. ASSERT_TRUE(svr.is_valid());
  13774. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13775. auto se = detail::scope_exit([&] {
  13776. svr.stop();
  13777. t.join();
  13778. ASSERT_FALSE(svr.is_running());
  13779. });
  13780. svr.wait_until_ready();
  13781. SSLClient cli("127.0.0.1", PORT);
  13782. cli.set_connection_timeout(30);
  13783. auto res = cli.Get("/");
  13784. ASSERT_FALSE(res);
  13785. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13786. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13787. }
  13788. #endif
  13789. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13790. Client cli("https://google.com");
  13791. auto res = cli.Get("/");
  13792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13793. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13794. }
  13795. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13796. SSLClient cli("google.com");
  13797. cli.set_ca_cert_path(CA_CERT_FILE);
  13798. auto res = cli.Get("/");
  13799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13800. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13801. }
  13802. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13803. SSLClient cli("google.com");
  13804. cli.enable_server_certificate_verification(true);
  13805. cli.set_ca_cert_path("hello");
  13806. auto res = cli.Get("/");
  13807. ASSERT_TRUE(!res);
  13808. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13809. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13810. // should be set
  13811. EXPECT_EQ(0, res.ssl_error());
  13812. // Verify backend error is captured for SSLLoadingCerts
  13813. // This error occurs when loading CA certificates fails
  13814. EXPECT_NE(0UL, res.ssl_backend_error());
  13815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13816. // OpenSSL specific error codes:
  13817. // > openssl errstr 0x80000002
  13818. // error:80000002:system library::No such file or directory
  13819. // > openssl errstr 0xA000126
  13820. // error:0A000126:SSL routines::unexpected eof while reading
  13821. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13822. res.ssl_backend_error() == 0xA000126);
  13823. #endif
  13824. }
  13825. TEST(SSLClientTest, ServerCertificateVerification4) {
  13826. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13827. ASSERT_TRUE(svr.is_valid());
  13828. svr.Get("/test", [&](const Request &, Response &res) {
  13829. res.set_content("test", "text/plain");
  13830. svr.stop();
  13831. ASSERT_TRUE(true);
  13832. });
  13833. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13834. auto se = detail::scope_exit([&] {
  13835. t.join();
  13836. ASSERT_FALSE(svr.is_running());
  13837. });
  13838. svr.wait_until_ready();
  13839. SSLClient cli("127.0.0.1", PORT);
  13840. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13841. cli.enable_server_certificate_verification(true);
  13842. cli.set_connection_timeout(30);
  13843. auto res = cli.Get("/test");
  13844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13845. ASSERT_EQ(StatusCode::OK_200, res->status);
  13846. }
  13847. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13848. std::string cert;
  13849. read_file(CA_CERT_FILE, cert);
  13850. SSLClient cli("google.com");
  13851. cli.load_ca_cert_store(cert.data(), cert.size());
  13852. const auto res = cli.Get("/");
  13853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13854. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13855. }
  13856. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13857. // clang-format off
  13858. static constexpr char cert[] =
  13859. "GlobalSign Root CA\n"
  13860. "==================\n"
  13861. "-----BEGIN CERTIFICATE-----\n"
  13862. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13863. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13864. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13865. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13866. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13867. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13868. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13869. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13870. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13871. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13872. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13873. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13874. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13875. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13876. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13877. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13878. "-----END CERTIFICATE-----\n";
  13879. // clang-format on
  13880. SSLClient cli("google.com");
  13881. cli.load_ca_cert_store(cert, sizeof(cert));
  13882. const auto res = cli.Get("/");
  13883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13884. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13885. }
  13886. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13887. SSLClient cli("www.youtube.com");
  13888. cli.set_ca_cert_path(CA_CERT_FILE);
  13889. cli.enable_server_certificate_verification(true);
  13890. cli.set_follow_location(true);
  13891. auto res = cli.Get("/");
  13892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13893. ASSERT_EQ(StatusCode::OK_200, res->status);
  13894. }
  13895. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13896. SSLClient cli("wWw.YouTube.Com");
  13897. cli.set_ca_cert_path(CA_CERT_FILE);
  13898. cli.enable_server_certificate_verification(true);
  13899. cli.enable_server_hostname_verification(true);
  13900. cli.set_follow_location(true);
  13901. auto res = cli.Get("/");
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. ASSERT_EQ(StatusCode::OK_200, res->status);
  13904. }
  13905. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13906. SSLClient cli("gOoGlE.COm");
  13907. cli.enable_server_certificate_verification(true);
  13908. cli.enable_server_hostname_verification(true);
  13909. cli.set_follow_location(true);
  13910. auto res = cli.Get("/");
  13911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13912. ASSERT_EQ(StatusCode::OK_200, res->status);
  13913. }
  13914. TEST(SSLClientTest, Issue2004_Online) {
  13915. Client client("https://google.com");
  13916. client.set_follow_location(true);
  13917. auto res = client.Get("/");
  13918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13919. ASSERT_EQ(StatusCode::OK_200, res->status);
  13920. auto body = res->body;
  13921. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13922. }
  13923. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13924. // Create SSLClient with invalid cert/key to make is_valid() return false
  13925. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13926. "nonexistent_key.pem");
  13927. // is_valid() should be false due to cert loading failure
  13928. ASSERT_FALSE(cli.is_valid());
  13929. auto res = cli.Get("/");
  13930. ASSERT_FALSE(res);
  13931. EXPECT_EQ(Error::SSLConnection, res.error());
  13932. }
  13933. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13934. // Test for Issue #2251: SSL error not properly reported when client cert
  13935. // and key paths are swapped or mismatched
  13936. // This simulates the scenario where user accidentally swaps the cert and key
  13937. // files
  13938. // Using client cert file as private key and vice versa (completely wrong)
  13939. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13940. // Should fail validation due to cert/key mismatch
  13941. ASSERT_FALSE(cli.is_valid());
  13942. // Attempt to make a request should fail with proper error
  13943. auto res = cli.Get("/");
  13944. ASSERT_FALSE(res);
  13945. EXPECT_EQ(Error::SSLConnection, res.error());
  13946. // SSL error should be recorded in the Result object (this is the key fix for
  13947. // Issue #2251)
  13948. auto backend_error = res.ssl_backend_error();
  13949. EXPECT_NE(0u, backend_error);
  13950. }
  13951. // Tests cert/key mismatch detection at the TLS context level
  13952. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13953. // Test that using mismatched cert/key causes connection failure.
  13954. // We verify this at the SSLClient level rather than through internal
  13955. // TLS API functions.
  13956. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13957. cli.enable_server_certificate_verification(false);
  13958. cli.set_connection_timeout(2);
  13959. // The mismatch should cause a connection or handshake error
  13960. auto res = cli.Get("/test");
  13961. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13962. // Either way, the request should fail
  13963. EXPECT_FALSE(res);
  13964. }
  13965. #endif
  13966. #if 0
  13967. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13968. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13969. ASSERT_TRUE(cli != nullptr);
  13970. cli->set_address_family(AF_INET6);
  13971. cli->set_interface("en0");
  13972. auto res = cli->Get("/get");
  13973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13974. ASSERT_EQ(StatusCode::OK_200, res->status);
  13975. }
  13976. #endif
  13977. // Client certificate tests - work with all TLS backends
  13978. #ifdef CPPHTTPLIB_SSL_ENABLED
  13979. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13980. void ClientCertPresent(
  13981. const std::string &client_cert_file,
  13982. const std::string &client_private_key_file,
  13983. const std::string &client_encrypted_private_key_pass = std::string(),
  13984. const ClientCertServerSetup &setup = nullptr) {
  13985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13986. ASSERT_TRUE(svr.is_valid());
  13987. if (setup) { setup(svr); }
  13988. svr.Get("/test", [&](const Request &req, Response &res) {
  13989. res.set_content("test", "text/plain");
  13990. auto cert = req.peer_cert();
  13991. ASSERT_TRUE(static_cast<bool>(cert));
  13992. std::string common_name = cert.subject_cn();
  13993. EXPECT_EQ("Common Name", common_name);
  13994. });
  13995. auto port = svr.bind_to_any_port(HOST);
  13996. ASSERT_LT(0, port);
  13997. thread t = thread([&]() { svr.listen_after_bind(); });
  13998. auto se = detail::scope_exit([&] {
  13999. svr.stop();
  14000. t.join();
  14001. ASSERT_FALSE(svr.is_running());
  14002. });
  14003. svr.wait_until_ready();
  14004. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14005. client_encrypted_private_key_pass);
  14006. cli.enable_server_certificate_verification(false);
  14007. cli.set_connection_timeout(30);
  14008. auto res = cli.Get("/test");
  14009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14010. ASSERT_EQ(StatusCode::OK_200, res->status);
  14011. }
  14012. TEST(SSLClientServerTest, ClientCertPresent) {
  14013. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14014. }
  14015. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14016. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14017. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14018. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14019. }
  14020. // Expects svr, which must require client certificates, to reject a client
  14021. // that has none
  14022. void RejectsClientWithoutCert(SSLServer &svr) {
  14023. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14024. auto port = svr.bind_to_any_port(HOST);
  14025. ASSERT_LT(0, port);
  14026. thread t = thread([&]() { svr.listen_after_bind(); });
  14027. auto se = detail::scope_exit([&] {
  14028. svr.stop();
  14029. t.join();
  14030. ASSERT_FALSE(svr.is_running());
  14031. });
  14032. svr.wait_until_ready();
  14033. SSLClient cli(HOST, port);
  14034. cli.set_connection_timeout(30);
  14035. // Skip the server certificate check, so that the request fails because the
  14036. // client certificate is missing rather than because cert.pem is not trusted
  14037. cli.enable_server_certificate_verification(false);
  14038. auto res = cli.Get("/test");
  14039. ASSERT_FALSE(res);
  14040. // The server rejects the client during the handshake, or on TLS 1.3 right
  14041. // after it, which the client notices on its first write or read
  14042. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14043. res.error() == Error::Write || res.error() == Error::Read)
  14044. << to_string(res.error());
  14045. if (res.error() == Error::SSLConnection) {
  14046. EXPECT_NE(0UL, res.ssl_backend_error());
  14047. }
  14048. // A rejection noticed on the write keeps the TLS error the write hit
  14049. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14050. }
  14051. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14052. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14053. ASSERT_TRUE(svr.is_valid());
  14054. if (setup) { setup(svr); }
  14055. RejectsClientWithoutCert(svr);
  14056. }
  14057. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14058. // A server that requires client certificates must keep requiring them after
  14059. // setup changes it, and keep accepting a client that has one
  14060. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14061. ClientCertMissing(setup);
  14062. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14063. setup);
  14064. }
  14065. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14066. ClientCertStillRequired([](SSLServer &svr) {
  14067. ASSERT_TRUE(tls::set_verify_callback(
  14068. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14069. });
  14070. }
  14071. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14072. ClientCertStillRequired([](SSLServer &svr) {
  14073. ASSERT_TRUE(tls::set_verify_callback(
  14074. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14075. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14076. });
  14077. }
  14078. // The client verifies the server certificate during the handshake, so a
  14079. // server that fails the check never gets the client certificate, even when a
  14080. // verifier of the client's own accepts it
  14081. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14082. struct Case {
  14083. const char *trusted_ca;
  14084. const char *host;
  14085. Error error;
  14086. };
  14087. // cert2.pem names localhost: the first client does not trust it, and the
  14088. // second trusts it but asks for another name
  14089. for (const auto &c :
  14090. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14091. Case{SERVER_CERT2_FILE, "example.com",
  14092. Error::SSLServerHostnameVerification}}) {
  14093. for (auto with_verifier : {false, true}) {
  14094. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14095. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14096. CLIENT_CA_CERT_FILE);
  14097. ASSERT_TRUE(svr.is_valid());
  14098. std::atomic<bool> got_client_cert{false};
  14099. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14100. [&](const tls::VerifyContext &) {
  14101. got_client_cert = true;
  14102. return true;
  14103. }));
  14104. auto port = svr.bind_to_any_port("127.0.0.1");
  14105. ASSERT_LT(0, port);
  14106. thread t = thread([&] { svr.listen_after_bind(); });
  14107. svr.wait_until_ready();
  14108. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14109. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14110. cli.set_ca_cert_path(c.trusted_ca);
  14111. if (with_verifier) {
  14112. cli.set_server_certificate_verifier(
  14113. [](const tls::VerifyContext &) { return true; });
  14114. }
  14115. auto res = cli.Get("/");
  14116. EXPECT_FALSE(res);
  14117. EXPECT_EQ(c.error, res.error());
  14118. svr.stop();
  14119. t.join();
  14120. EXPECT_FALSE(got_client_cert);
  14121. }
  14122. }
  14123. }
  14124. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14125. std::string cert_pem, key_pem, ca_pem;
  14126. read_file(SERVER_CERT_FILE, cert_pem);
  14127. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14128. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14129. ASSERT_TRUE(
  14130. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14131. }
  14132. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14134. ASSERT_TRUE(svr.is_valid());
  14135. UpdateCertsPemWithClientCA(svr);
  14136. RejectsClientWithoutCert(svr);
  14137. }
  14138. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14139. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14140. }
  14141. // A TLS error from one request must not show up in a later request's Result
  14142. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14144. ASSERT_TRUE(svr.is_valid());
  14145. svr.Get("/test", [](const Request &, Response &res) {
  14146. res.set_content("test", "text/plain");
  14147. });
  14148. auto port = svr.bind_to_any_port(HOST);
  14149. ASSERT_LT(0, port);
  14150. thread t = thread([&]() { svr.listen_after_bind(); });
  14151. auto se = detail::scope_exit([&] {
  14152. svr.stop();
  14153. t.join();
  14154. ASSERT_FALSE(svr.is_running());
  14155. });
  14156. svr.wait_until_ready();
  14157. SSLClient cli(HOST, port);
  14158. cli.set_connection_timeout(30);
  14159. cli.enable_server_hostname_verification(false);
  14160. // cert.pem is not trusted, so the handshake fails
  14161. ASSERT_FALSE(cli.Get("/test"));
  14162. cli.enable_server_certificate_verification(false);
  14163. auto res = cli.Get("/test");
  14164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14165. EXPECT_EQ(0, res.ssl_error());
  14166. EXPECT_EQ(0UL, res.ssl_backend_error());
  14167. }
  14168. // PEM memory-based constructor tests (works with all TLS backends).
  14169. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14170. // terminator after it.
  14171. void PemMemoryClientCertPresent(
  14172. const std::string &client_cert_file,
  14173. const std::string &client_private_key_file,
  14174. const std::string &client_encrypted_private_key_pass = std::string(),
  14175. bool exact_size = false) {
  14176. // Read PEM files into memory
  14177. std::string server_cert_pem, server_key_pem;
  14178. std::string client_ca_pem;
  14179. std::string client_cert_pem, client_key_pem;
  14180. read_file(SERVER_CERT_FILE, server_cert_pem);
  14181. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14182. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14183. read_file(client_cert_file, client_cert_pem);
  14184. read_file(client_private_key_file, client_key_pem);
  14185. std::list<std::vector<char>> exact_copies;
  14186. auto data = [&](const std::string &pem) -> const char * {
  14187. if (!exact_size) { return pem.c_str(); }
  14188. exact_copies.emplace_back(pem.begin(), pem.end());
  14189. return exact_copies.back().data();
  14190. };
  14191. // Create server with PEM memory
  14192. SSLServer::PemMemory server_pem = {
  14193. data(server_cert_pem),
  14194. server_cert_pem.size(),
  14195. data(server_key_pem),
  14196. server_key_pem.size(),
  14197. data(client_ca_pem),
  14198. client_ca_pem.size(),
  14199. nullptr // no password for server key
  14200. };
  14201. SSLServer svr(server_pem);
  14202. ASSERT_TRUE(svr.is_valid());
  14203. svr.Get("/test", [&](const Request &req, Response &res) {
  14204. res.set_content("test", "text/plain");
  14205. auto cert = req.peer_cert();
  14206. ASSERT_TRUE(static_cast<bool>(cert));
  14207. EXPECT_EQ("Common Name", cert.subject_cn());
  14208. });
  14209. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14210. auto se = detail::scope_exit([&] {
  14211. svr.stop();
  14212. t.join();
  14213. ASSERT_FALSE(svr.is_running());
  14214. });
  14215. svr.wait_until_ready();
  14216. // Create client with PEM memory
  14217. const char *password = client_encrypted_private_key_pass.empty()
  14218. ? nullptr
  14219. : client_encrypted_private_key_pass.c_str();
  14220. SSLClient::PemMemory client_pem = {
  14221. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14222. client_key_pem.size(), password};
  14223. SSLClient cli(HOST, PORT, client_pem);
  14224. cli.enable_server_certificate_verification(false);
  14225. cli.set_connection_timeout(30);
  14226. auto res = cli.Get("/test");
  14227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14228. ASSERT_EQ(StatusCode::OK_200, res->status);
  14229. }
  14230. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14231. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14232. }
  14233. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14234. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14235. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14236. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14237. }
  14238. // A server built from PEM memory with a client CA requires client certificates,
  14239. // also when the CA is a NUL-terminated string passed with a length of 0
  14240. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14241. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14242. read_file(SERVER_CERT_FILE, server_cert_pem);
  14243. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14244. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14245. SSLServer::PemMemory server_pem = {
  14246. server_cert_pem.c_str(),
  14247. server_cert_pem.size(),
  14248. server_key_pem.c_str(),
  14249. server_key_pem.size(),
  14250. client_ca_pem.c_str(),
  14251. client_ca_pem.size(),
  14252. nullptr // no password for server key
  14253. };
  14254. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14255. SCOPED_TRACE(client_ca_pem_len);
  14256. server_pem.client_ca_pem_len = client_ca_pem_len;
  14257. SSLServer svr(server_pem);
  14258. ASSERT_TRUE(svr.is_valid());
  14259. RejectsClientWithoutCert(svr);
  14260. }
  14261. // An empty CA fails to load instead of turning the check off
  14262. server_pem.client_ca_pem = "";
  14263. server_pem.client_ca_pem_len = 0;
  14264. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14265. }
  14266. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14267. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14268. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14269. true);
  14270. }
  14271. // A length shorter than the PEM cuts it short, so it no longer loads
  14272. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14273. std::string cert, key;
  14274. read_file(SERVER_CERT_FILE, cert);
  14275. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14276. for (auto cut_cert : {true, false}) {
  14277. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14278. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14279. SSLServer::PemMemory server_pem = {
  14280. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14281. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14282. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14283. key_len, nullptr};
  14284. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14285. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14286. key.c_str(), key_len, nullptr};
  14287. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14288. }
  14289. }
  14290. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14291. class NoListenSSLServer : public SSLServer {
  14292. public:
  14293. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14294. const char *client_ca_cert_file_path,
  14295. const char *client_ca_cert_dir_path = nullptr)
  14296. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14297. client_ca_cert_dir_path),
  14298. stop_(false) {}
  14299. std::atomic_bool stop_;
  14300. private:
  14301. bool process_and_close_socket(socket_t /*sock*/) override {
  14302. // Don't create SSL context
  14303. while (!stop_.load()) {
  14304. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14305. }
  14306. return true;
  14307. }
  14308. };
  14309. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14310. CLIENT_CA_CERT_FILE);
  14311. ASSERT_TRUE(svr.is_valid());
  14312. svr.Get("/test", [&](const Request &, Response &res) {
  14313. res.set_content("test", "text/plain");
  14314. });
  14315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14316. auto se = detail::scope_exit([&] {
  14317. svr.stop_ = true;
  14318. svr.stop();
  14319. t.join();
  14320. ASSERT_FALSE(svr.is_running());
  14321. });
  14322. svr.wait_until_ready();
  14323. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14324. cli.enable_server_certificate_verification(false);
  14325. cli.set_connection_timeout(1);
  14326. auto res = cli.Get("/test");
  14327. ASSERT_TRUE(!res);
  14328. EXPECT_EQ(Error::SSLConnection, res.error());
  14329. // Timeout results in WantRead error code (maps to backend-specific value)
  14330. EXPECT_NE(0, res.ssl_error());
  14331. }
  14332. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14333. // Test SSLServer with client certificate verification using the standard
  14334. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14336. CLIENT_CA_CERT_DIR);
  14337. ASSERT_TRUE(svr.is_valid());
  14338. svr.Get("/test", [&](const Request &req, Response &res) {
  14339. res.set_content("test", "text/plain");
  14340. auto cert = req.peer_cert();
  14341. ASSERT_TRUE(static_cast<bool>(cert));
  14342. auto common_name = cert.subject_cn();
  14343. EXPECT_EQ("Common Name", common_name);
  14344. });
  14345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. ASSERT_FALSE(svr.is_running());
  14350. });
  14351. svr.wait_until_ready();
  14352. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14353. cli.enable_server_certificate_verification(false);
  14354. cli.set_connection_timeout(30);
  14355. auto res = cli.Get("/test");
  14356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14357. ASSERT_EQ(StatusCode::OK_200, res->status);
  14358. }
  14359. // Test verify_hostname on every backend: a host is named by a SAN only
  14360. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14361. using namespace httplib::tls;
  14362. // We need a running server to test against
  14363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14364. ASSERT_TRUE(svr.is_valid());
  14365. svr.Get("/test", [](const Request &, Response &res) {
  14366. res.set_content("ok", "text/plain");
  14367. });
  14368. thread t([&]() { svr.listen(HOST, PORT); });
  14369. auto se = detail::scope_exit([&] {
  14370. svr.stop();
  14371. t.join();
  14372. });
  14373. svr.wait_until_ready();
  14374. bool verify_callback_called = false;
  14375. bool verify_result_wrong = false;
  14376. SSLClient cli(HOST, PORT);
  14377. cli.enable_server_certificate_verification(true);
  14378. cli.set_ca_cert_path(CA_CERT_FILE);
  14379. cli.set_connection_timeout(5);
  14380. // Note: Test certificate has CN="Common Name", not "localhost"
  14381. bool verify_result_cn = false;
  14382. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14383. verify_callback_called = true;
  14384. if (!ctx.cert) return false;
  14385. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14386. verify_result_cn = ctx.check_hostname("Common Name");
  14387. // Test 2: wrong hostname should not match
  14388. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14389. return true; // Accept for the purpose of this test
  14390. });
  14391. auto res = cli.Get("/test");
  14392. // The request may succeed or fail depending on cert configuration
  14393. // but the callback should have been called
  14394. ASSERT_TRUE(verify_callback_called)
  14395. << "Verify callback should have been called";
  14396. EXPECT_FALSE(verify_result_cn)
  14397. << "verify_hostname must not match the certificate CN (no SAN)";
  14398. // Wrong hostname should not match
  14399. EXPECT_FALSE(verify_result_wrong)
  14400. << "verify_hostname should not match 'wronghost.example.com'";
  14401. }
  14402. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14403. // backend verifies it.
  14404. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14405. // Certificate CN is "localhost" and it carries no SAN.
  14406. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14407. ASSERT_TRUE(svr.is_valid());
  14408. svr.Get("/test", [](const Request &, Response &res) {
  14409. res.set_content("ok", "text/plain");
  14410. });
  14411. auto port = svr.bind_to_any_port(HOST);
  14412. thread t([&]() { svr.listen_after_bind(); });
  14413. auto se = detail::scope_exit([&] {
  14414. svr.stop();
  14415. t.join();
  14416. });
  14417. svr.wait_until_ready();
  14418. SSLClient cli("localhost", port);
  14419. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14420. cli.enable_server_certificate_verification(true);
  14421. cli.set_connection_timeout(5);
  14422. auto res = cli.Get("/test");
  14423. ASSERT_FALSE(res);
  14424. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14425. // The same certificate is accepted once host name verification is off, so the
  14426. // failure above is the host name and not the chain.
  14427. cli.enable_server_hostname_verification(false);
  14428. res = cli.Get("/test");
  14429. ASSERT_TRUE(res) << to_string(res.error());
  14430. EXPECT_EQ(StatusCode::OK_200, res->status);
  14431. }
  14432. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14433. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14434. // X509_check_ip behavior and must hold for every backend.
  14435. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14436. using namespace httplib::tls;
  14437. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14438. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14439. ASSERT_TRUE(svr.is_valid());
  14440. svr.Get("/test", [](const Request &, Response &res) {
  14441. res.set_content("ok", "text/plain");
  14442. });
  14443. thread t([&]() { svr.listen(HOST, PORT); });
  14444. auto se = detail::scope_exit([&] {
  14445. svr.stop();
  14446. t.join();
  14447. });
  14448. svr.wait_until_ready();
  14449. bool verify_callback_called = false;
  14450. bool ip_matched_via_cn = true;
  14451. SSLClient cli(HOST, PORT);
  14452. cli.enable_server_certificate_verification(true);
  14453. cli.set_ca_cert_path(CA_CERT_FILE);
  14454. cli.set_connection_timeout(5);
  14455. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14456. verify_callback_called = true;
  14457. if (!ctx.cert) return false;
  14458. // The IP appears only in the CN, so it must NOT be accepted.
  14459. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14460. return true; // Accept for the purpose of this test
  14461. });
  14462. cli.Get("/test");
  14463. ASSERT_TRUE(verify_callback_called)
  14464. << "Verify callback should have been called";
  14465. EXPECT_FALSE(ip_matched_via_cn)
  14466. << "An IP host must not be authenticated via the certificate CN";
  14467. }
  14468. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14469. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14470. using namespace httplib::tls;
  14471. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14472. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14473. ASSERT_TRUE(svr.is_valid());
  14474. svr.Get("/test", [](const Request &, Response &res) {
  14475. res.set_content("ok", "text/plain");
  14476. });
  14477. thread t([&]() { svr.listen(HOST, PORT); });
  14478. auto se = detail::scope_exit([&] {
  14479. svr.stop();
  14480. t.join();
  14481. });
  14482. svr.wait_until_ready();
  14483. bool verify_callback_called = false;
  14484. bool san_matched = false;
  14485. bool wrong_ipv6_matched = true;
  14486. bool cn_ipv6_matched = true;
  14487. SSLClient cli(HOST, PORT);
  14488. cli.enable_server_certificate_verification(true);
  14489. cli.set_ca_cert_path(CA_CERT_FILE);
  14490. cli.set_connection_timeout(5);
  14491. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14492. verify_callback_called = true;
  14493. if (!ctx.cert) return false;
  14494. // Matches the IPv6 iPAddress SAN.
  14495. san_matched = ctx.check_hostname("2001:db8::1");
  14496. // A different IPv6 address must not match.
  14497. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14498. // "::1" lives only in the CN, so it must not be accepted.
  14499. cn_ipv6_matched = ctx.check_hostname("::1");
  14500. return true; // Accept for the purpose of this test
  14501. });
  14502. cli.Get("/test");
  14503. ASSERT_TRUE(verify_callback_called)
  14504. << "Verify callback should have been called";
  14505. EXPECT_TRUE(san_matched)
  14506. << "verify_hostname should match an IPv6 iPAddress SAN";
  14507. EXPECT_FALSE(wrong_ipv6_matched)
  14508. << "verify_hostname should not match a non-matching IPv6 address";
  14509. EXPECT_FALSE(cn_ipv6_matched)
  14510. << "An IPv6 host must not be authenticated via the certificate CN";
  14511. }
  14512. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14513. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14514. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14515. using namespace httplib::tls;
  14516. // SANs: DNS:a.zz, IP:42.46.122.122
  14517. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14518. ASSERT_TRUE(svr.is_valid());
  14519. svr.Get("/test", [](const Request &, Response &res) {
  14520. res.set_content("ok", "text/plain");
  14521. });
  14522. auto port = svr.bind_to_any_port(HOST);
  14523. thread t([&]() { svr.listen_after_bind(); });
  14524. auto se = detail::scope_exit([&] {
  14525. svr.stop();
  14526. t.join();
  14527. });
  14528. svr.wait_until_ready();
  14529. bool verify_callback_called = false;
  14530. bool dns_san_matched = false;
  14531. bool ip_san_matched = false;
  14532. bool ip_matched_via_dns_san = true;
  14533. bool dns_matched_via_ip_san = true;
  14534. bool cn_matched_next_to_dns_san = true;
  14535. SSLClient cli(HOST, port);
  14536. cli.enable_server_certificate_verification(true);
  14537. cli.set_ca_cert_path(CA_CERT_FILE);
  14538. cli.set_connection_timeout(5);
  14539. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14540. verify_callback_called = true;
  14541. if (!ctx.cert) return false;
  14542. dns_san_matched = ctx.check_hostname("a.zz");
  14543. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14544. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14545. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14546. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14547. return true; // Accept for the purpose of this test
  14548. });
  14549. cli.Get("/test");
  14550. ASSERT_TRUE(verify_callback_called)
  14551. << "Verify callback should have been called";
  14552. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14553. EXPECT_TRUE(ip_san_matched)
  14554. << "verify_hostname should match an iPAddress SAN";
  14555. EXPECT_FALSE(ip_matched_via_dns_san)
  14556. << "An IP host must not be authenticated via a dNSName SAN";
  14557. EXPECT_FALSE(dns_matched_via_ip_san)
  14558. << "A DNS host must not be authenticated via an iPAddress SAN";
  14559. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14560. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14561. }
  14562. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14563. // "www.*.example.test" names one host and not every host under example.test.
  14564. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14565. using namespace httplib::tls;
  14566. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14567. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14568. ASSERT_TRUE(svr.is_valid());
  14569. svr.Get("/test", [](const Request &, Response &res) {
  14570. res.set_content("ok", "text/plain");
  14571. });
  14572. auto port = svr.bind_to_any_port(HOST);
  14573. thread t([&]() { svr.listen_after_bind(); });
  14574. auto se = detail::scope_exit([&] {
  14575. svr.stop();
  14576. t.join();
  14577. });
  14578. svr.wait_until_ready();
  14579. bool verify_callback_called = false;
  14580. bool leftmost_wildcard_matched = false;
  14581. bool wildcard_spanned_labels = true;
  14582. bool inner_wildcard_matched = true;
  14583. SSLClient cli(HOST, port);
  14584. cli.enable_server_certificate_verification(true);
  14585. cli.set_ca_cert_path(CA_CERT_FILE);
  14586. cli.set_connection_timeout(5);
  14587. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14588. verify_callback_called = true;
  14589. if (!ctx.cert) return false;
  14590. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14591. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14592. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14593. return true; // Accept for the purpose of this test
  14594. });
  14595. cli.Get("/test");
  14596. ASSERT_TRUE(verify_callback_called)
  14597. << "Verify callback should have been called";
  14598. EXPECT_TRUE(leftmost_wildcard_matched)
  14599. << "A leftmost wildcard should match a single label";
  14600. EXPECT_FALSE(wildcard_spanned_labels)
  14601. << "A wildcard label must not match more than one label";
  14602. EXPECT_FALSE(inner_wildcard_matched)
  14603. << "A wildcard outside the leftmost label must not be honoured";
  14604. }
  14605. // sans() must report each SAN entry under its own type.
  14606. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14607. using namespace httplib::tls;
  14608. // SANs: DNS:a.zz, IP:42.46.122.122
  14609. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14610. ASSERT_TRUE(svr.is_valid());
  14611. svr.Get("/test", [](const Request &, Response &res) {
  14612. res.set_content("ok", "text/plain");
  14613. });
  14614. auto port = svr.bind_to_any_port(HOST);
  14615. thread t([&]() { svr.listen_after_bind(); });
  14616. auto se = detail::scope_exit([&] {
  14617. svr.stop();
  14618. t.join();
  14619. });
  14620. svr.wait_until_ready();
  14621. bool verify_callback_called = false;
  14622. std::vector<SanEntry> sans;
  14623. SSLClient cli(HOST, port);
  14624. cli.enable_server_certificate_verification(true);
  14625. cli.set_ca_cert_path(CA_CERT_FILE);
  14626. cli.set_connection_timeout(5);
  14627. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14628. verify_callback_called = true;
  14629. if (!ctx.cert) return false;
  14630. sans = ctx.sans();
  14631. return true; // Accept for the purpose of this test
  14632. });
  14633. cli.Get("/test");
  14634. ASSERT_TRUE(verify_callback_called)
  14635. << "Verify callback should have been called";
  14636. auto has_san = [&](SanType type, const std::string &value) {
  14637. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14638. return san.type == type && san.value == value;
  14639. });
  14640. };
  14641. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14642. << "sans() should report the dNSName SAN";
  14643. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14644. << "sans() should report the iPAddress SAN";
  14645. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14646. << "sans() must not report the dNSName SAN as an address";
  14647. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14648. << "sans() must not report the iPAddress SAN as a DNS name";
  14649. }
  14650. #endif
  14651. // mbedTLS-specific callback constructor test
  14652. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14653. #ifdef CPPHTTPLIB_SSL_ENABLED
  14654. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14656. ASSERT_TRUE(svr.is_valid());
  14657. // Set up a handler to verify client certificate is present
  14658. bool client_cert_verified = false;
  14659. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14660. // Verify that client certificate was provided
  14661. client_cert_verified = true;
  14662. res.set_content("success", "text/plain");
  14663. });
  14664. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14665. auto se = detail::scope_exit([&] {
  14666. svr.stop();
  14667. t.join();
  14668. ASSERT_FALSE(svr.is_running());
  14669. });
  14670. svr.wait_until_ready();
  14671. // Client with certificate
  14672. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14673. cli.enable_server_certificate_verification(false);
  14674. cli.set_connection_timeout(30);
  14675. auto res = cli.Get("/test");
  14676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14677. ASSERT_EQ(StatusCode::OK_200, res->status);
  14678. ASSERT_TRUE(client_cert_verified);
  14679. EXPECT_EQ("success", res->body);
  14680. }
  14681. #endif
  14682. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14683. // backends
  14684. #ifdef CPPHTTPLIB_SSL_ENABLED
  14685. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14686. using namespace httplib::tls;
  14687. // Test that when client CA cert file is provided,
  14688. // the server properly requests and validates client certificates
  14689. // Create a server with client authentication
  14690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14691. ASSERT_TRUE(svr.is_valid());
  14692. bool handler_called = false;
  14693. svr.Get("/test", [&](const Request &req, Response &res) {
  14694. handler_called = true;
  14695. // Verify that a client certificate was provided
  14696. auto cert = req.peer_cert();
  14697. ASSERT_TRUE(static_cast<bool>(cert));
  14698. // Get the issuer name
  14699. std::string issuer_str = cert.issuer_name();
  14700. ASSERT_FALSE(issuer_str.empty());
  14701. // The client certificate should be issued by our test CA
  14702. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14703. res.set_content("authenticated", "text/plain");
  14704. });
  14705. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14706. auto se = detail::scope_exit([&] {
  14707. svr.stop();
  14708. t.join();
  14709. ASSERT_FALSE(svr.is_running());
  14710. });
  14711. svr.wait_until_ready();
  14712. // Connect with a client certificate issued by the CA
  14713. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14714. cli.enable_server_certificate_verification(false);
  14715. cli.set_connection_timeout(30);
  14716. auto res = cli.Get("/test");
  14717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14718. ASSERT_EQ(StatusCode::OK_200, res->status);
  14719. ASSERT_TRUE(handler_called);
  14720. EXPECT_EQ("authenticated", res->body);
  14721. }
  14722. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14723. using namespace httplib::tls;
  14724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14725. ASSERT_TRUE(svr.is_valid());
  14726. svr.Get("/test", [](const Request &, Response &res) {
  14727. res.set_content("ok", "text/plain");
  14728. });
  14729. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14730. auto se = detail::scope_exit([&] {
  14731. svr.stop();
  14732. t.join();
  14733. });
  14734. svr.wait_until_ready();
  14735. SSLClient cli(HOST, PORT);
  14736. cli.enable_server_certificate_verification(false);
  14737. cli.set_connection_timeout(30);
  14738. bool cert_checked = false;
  14739. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14740. if (ctx.cert) {
  14741. auto sans = ctx.sans();
  14742. // Test certificate may or may not have SANs - just verify the API
  14743. // works If SANs exist, verify the types are valid
  14744. for (const auto &san : sans) {
  14745. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14746. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14747. san.type == SanType::OTHER);
  14748. EXPECT_FALSE(san.value.empty());
  14749. }
  14750. cert_checked = true;
  14751. }
  14752. return true;
  14753. });
  14754. auto res = cli.Get("/test");
  14755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14756. EXPECT_TRUE(cert_checked);
  14757. }
  14758. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14759. using namespace httplib::tls;
  14760. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14761. ASSERT_TRUE(svr.is_valid());
  14762. svr.Get("/test", [](const Request &, Response &res) {
  14763. res.set_content("ok", "text/plain");
  14764. });
  14765. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14766. auto se = detail::scope_exit([&] {
  14767. svr.stop();
  14768. t.join();
  14769. });
  14770. svr.wait_until_ready();
  14771. SSLClient cli(HOST, PORT);
  14772. cli.enable_server_certificate_verification(false);
  14773. cli.set_connection_timeout(30);
  14774. bool validity_checked = false;
  14775. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14776. if (ctx.cert) {
  14777. time_t not_before = 0, not_after = 0;
  14778. bool result = ctx.validity(not_before, not_after);
  14779. EXPECT_TRUE(result);
  14780. // Verify that not_before < now < not_after for a valid cert
  14781. time_t now = time(nullptr);
  14782. EXPECT_LT(not_before, now);
  14783. EXPECT_GT(not_after, now);
  14784. validity_checked = true;
  14785. }
  14786. return true;
  14787. });
  14788. auto res = cli.Get("/test");
  14789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14790. EXPECT_TRUE(validity_checked);
  14791. }
  14792. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14793. using namespace httplib::tls;
  14794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14795. ASSERT_TRUE(svr.is_valid());
  14796. svr.Get("/test", [](const Request &, Response &res) {
  14797. res.set_content("ok", "text/plain");
  14798. });
  14799. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14800. auto se = detail::scope_exit([&] {
  14801. svr.stop();
  14802. t.join();
  14803. });
  14804. svr.wait_until_ready();
  14805. SSLClient cli(HOST, PORT);
  14806. cli.enable_server_certificate_verification(false);
  14807. cli.set_connection_timeout(30);
  14808. bool serial_checked = false;
  14809. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14810. if (ctx.cert) {
  14811. std::string serial = ctx.serial();
  14812. EXPECT_FALSE(serial.empty());
  14813. // Serial should be a hex string
  14814. for (char c : serial) {
  14815. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14816. (c >= 'a' && c <= 'f'));
  14817. }
  14818. serial_checked = true;
  14819. }
  14820. return true;
  14821. });
  14822. auto res = cli.Get("/test");
  14823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14824. EXPECT_TRUE(serial_checked);
  14825. }
  14826. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14827. // Test 1: Valid CA file - no error should be recorded
  14828. {
  14829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14830. CLIENT_CA_CERT_FILE);
  14831. ASSERT_TRUE(svr.is_valid());
  14832. // With valid setup, last_ssl_error should be 0
  14833. EXPECT_EQ(0, svr.ssl_last_error());
  14834. }
  14835. // Test 2: Invalid CA file content
  14836. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14837. {
  14838. // Create a temporary file with completely invalid content
  14839. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14840. {
  14841. std::ofstream ofs(temp_invalid_ca);
  14842. ofs << "This is not a certificate file at all\n";
  14843. ofs << "Just plain text content\n";
  14844. }
  14845. // Create server with invalid CA file
  14846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14847. // Clean up temporary file
  14848. std::remove(temp_invalid_ca);
  14849. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14850. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14851. // Note: SSL_CTX_load_verify_locations typically fails first,
  14852. // but our error handling code path is still exercised
  14853. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14854. }
  14855. }
  14856. TEST(VerifyCallbackTest, VerifyContextFields) {
  14857. using namespace httplib::tls;
  14858. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14859. ASSERT_TRUE(svr.is_valid());
  14860. svr.Get("/test", [](const Request &, Response &res) {
  14861. res.set_content("ok", "text/plain");
  14862. });
  14863. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14864. auto se = detail::scope_exit([&] {
  14865. svr.stop();
  14866. t.join();
  14867. });
  14868. svr.wait_until_ready();
  14869. SSLClient cli(HOST, PORT);
  14870. cli.enable_server_certificate_verification(false);
  14871. cli.set_connection_timeout(30);
  14872. int callback_count = 0;
  14873. bool saw_leaf_cert = false;
  14874. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14875. if (ctx.cert) {
  14876. callback_count++;
  14877. // We should see at least one certificate (the leaf)
  14878. std::string cn = ctx.subject_cn();
  14879. if (!cn.empty()) { saw_leaf_cert = true; }
  14880. // Verify context fields are populated
  14881. EXPECT_NE(ctx.session, nullptr);
  14882. EXPECT_GE(ctx.depth, 0);
  14883. }
  14884. return true;
  14885. });
  14886. auto res = cli.Get("/test");
  14887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14888. EXPECT_GT(callback_count, 0);
  14889. EXPECT_TRUE(saw_leaf_cert);
  14890. }
  14891. // A verifier that accepts runs alongside the built-in verification, and is the
  14892. // only check once that is turned off.
  14893. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14894. using namespace httplib::tls;
  14895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14896. ASSERT_TRUE(svr.is_valid());
  14897. svr.Get("/test", [](const Request &, Response &res) {
  14898. res.set_content("ok", "text/plain");
  14899. });
  14900. auto port = svr.bind_to_any_port(HOST);
  14901. thread t([&]() { svr.listen_after_bind(); });
  14902. auto se = detail::scope_exit([&] {
  14903. svr.stop();
  14904. t.join();
  14905. });
  14906. svr.wait_until_ready();
  14907. SSLClient cli(HOST, port);
  14908. cli.enable_server_hostname_verification(false);
  14909. auto calls = 0;
  14910. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14911. calls++;
  14912. return true;
  14913. });
  14914. // cert.pem is not trusted
  14915. auto res = cli.Get("/test");
  14916. ASSERT_FALSE(res);
  14917. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14918. EXPECT_GT(calls, 0);
  14919. cli.enable_server_certificate_verification(false);
  14920. res = cli.Get("/test");
  14921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14922. EXPECT_EQ("ok", res->body);
  14923. }
  14924. // A verifier belongs to the client that set it, not to the thread that set it.
  14925. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14926. using namespace httplib::tls;
  14927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14928. ASSERT_TRUE(svr.is_valid());
  14929. svr.Get("/test", [](const Request &, Response &res) {
  14930. res.set_content("ok", "text/plain");
  14931. });
  14932. auto port = svr.bind_to_any_port(HOST);
  14933. thread t([&]() { svr.listen_after_bind(); });
  14934. auto se = detail::scope_exit([&] {
  14935. svr.stop();
  14936. t.join();
  14937. });
  14938. svr.wait_until_ready();
  14939. auto rejecting_calls = 0;
  14940. SSLClient rejecting(HOST, port);
  14941. rejecting.enable_server_certificate_verification(false);
  14942. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14943. rejecting_calls++;
  14944. return false;
  14945. });
  14946. auto accepting_calls = 0;
  14947. SSLClient accepting(HOST, port);
  14948. accepting.enable_server_certificate_verification(false);
  14949. // Set on another thread than the requests below.
  14950. thread([&]() {
  14951. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14952. accepting_calls++;
  14953. return true;
  14954. });
  14955. }).join();
  14956. // Requested on another thread than the verifier was set on.
  14957. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14958. EXPECT_GT(rejecting_calls, 0);
  14959. auto res = accepting.Get("/test");
  14960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14961. EXPECT_GT(accepting_calls, 0);
  14962. }
  14963. // A verifier replaced while a handshake runs it lives until it returns.
  14964. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14965. using namespace httplib::tls;
  14966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14967. ASSERT_TRUE(svr.is_valid());
  14968. svr.Get("/test", [](const Request &, Response &res) {
  14969. res.set_content("ok", "text/plain");
  14970. });
  14971. auto port = svr.bind_to_any_port(HOST);
  14972. thread t([&]() { svr.listen_after_bind(); });
  14973. auto se = detail::scope_exit([&] {
  14974. svr.stop();
  14975. t.join();
  14976. });
  14977. svr.wait_until_ready();
  14978. SSLClient cli(HOST, port);
  14979. cli.enable_server_certificate_verification(false);
  14980. std::promise<void> entered;
  14981. std::promise<void> replaced;
  14982. auto replaced_future = replaced.get_future();
  14983. auto first_call = true;
  14984. // Long enough to live on the heap
  14985. std::string expected(64, 'v');
  14986. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14987. if (first_call) {
  14988. first_call = false;
  14989. entered.set_value();
  14990. replaced_future.wait();
  14991. }
  14992. return expected == std::string(64, 'v');
  14993. });
  14994. thread request([&]() {
  14995. auto res = cli.Get("/test");
  14996. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14997. });
  14998. entered.get_future().wait();
  14999. cli.set_server_certificate_verifier(
  15000. [](const VerifyContext &) { return true; });
  15001. replaced.set_value();
  15002. request.join();
  15003. }
  15004. // VerifyContext::session is the same handle the other tls:: functions take.
  15005. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15006. using namespace httplib::tls;
  15007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15008. ASSERT_TRUE(svr.is_valid());
  15009. svr.Get("/test", [](const Request &, Response &res) {
  15010. res.set_content("ok", "text/plain");
  15011. });
  15012. auto port = svr.bind_to_any_port(HOST);
  15013. thread t([&]() { svr.listen_after_bind(); });
  15014. auto se = detail::scope_exit([&] {
  15015. svr.stop();
  15016. t.join();
  15017. });
  15018. svr.wait_until_ready();
  15019. SSLClient cli(HOST, port);
  15020. cli.enable_server_certificate_verification(false);
  15021. session_t verifier_session = nullptr;
  15022. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15023. verifier_session = ctx.session;
  15024. return true;
  15025. });
  15026. session_t session_verifier_session = nullptr;
  15027. cli.set_session_verifier([&](session_t session) {
  15028. session_verifier_session = session;
  15029. return SSLVerifierResponse::NoDecisionMade;
  15030. });
  15031. auto res = cli.Get("/test");
  15032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15033. EXPECT_NE(nullptr, verifier_session);
  15034. EXPECT_EQ(session_verifier_session, verifier_session);
  15035. }
  15036. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15037. using httplib::tls::TlsError;
  15038. // Test that verify_error_to_string returns empty for success
  15039. std::string success_str = TlsError::verify_error_to_string(0);
  15040. EXPECT_TRUE(success_str.empty());
  15041. // Test that verify_error_to_string returns non-empty for error codes
  15042. // Using a common error code (certificate expired)
  15043. std::string error_str =
  15044. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15045. EXPECT_FALSE(error_str.empty());
  15046. }
  15047. TEST(SessionVerifierTest, CertificateAccepted) {
  15048. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15049. ASSERT_TRUE(svr.is_valid());
  15050. svr.Get("/test", [](const Request &, Response &res) {
  15051. res.set_content("ok", "text/plain");
  15052. });
  15053. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15054. auto se = detail::scope_exit([&] {
  15055. svr.stop();
  15056. t.join();
  15057. });
  15058. svr.wait_until_ready();
  15059. SSLClient cli(HOST, PORT);
  15060. cli.enable_server_certificate_verification(false);
  15061. cli.set_connection_timeout(30);
  15062. bool callback_called = false;
  15063. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15064. EXPECT_NE(session, nullptr);
  15065. callback_called = true;
  15066. return SSLVerifierResponse::CertificateAccepted;
  15067. });
  15068. auto res = cli.Get("/test");
  15069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15070. EXPECT_EQ(200, res->status);
  15071. EXPECT_TRUE(callback_called);
  15072. }
  15073. TEST(SessionVerifierTest, CertificateRejected) {
  15074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15075. ASSERT_TRUE(svr.is_valid());
  15076. svr.Get("/test", [](const Request &, Response &res) {
  15077. res.set_content("ok", "text/plain");
  15078. });
  15079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15080. auto se = detail::scope_exit([&] {
  15081. svr.stop();
  15082. t.join();
  15083. });
  15084. svr.wait_until_ready();
  15085. SSLClient cli(HOST, PORT);
  15086. cli.enable_server_certificate_verification(false);
  15087. cli.set_connection_timeout(30);
  15088. bool callback_called = false;
  15089. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15090. EXPECT_NE(session, nullptr);
  15091. callback_called = true;
  15092. return SSLVerifierResponse::CertificateRejected;
  15093. });
  15094. auto res = cli.Get("/test");
  15095. EXPECT_FALSE(res);
  15096. EXPECT_TRUE(callback_called);
  15097. }
  15098. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15100. ASSERT_TRUE(svr.is_valid());
  15101. svr.Get("/test", [](const Request &, Response &res) {
  15102. res.set_content("ok", "text/plain");
  15103. });
  15104. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15105. auto se = detail::scope_exit([&] {
  15106. svr.stop();
  15107. t.join();
  15108. });
  15109. svr.wait_until_ready();
  15110. // NoDecisionMade with verification disabled should succeed (no default check)
  15111. SSLClient cli(HOST, PORT);
  15112. cli.enable_server_certificate_verification(false);
  15113. cli.set_connection_timeout(30);
  15114. bool callback_called = false;
  15115. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15116. EXPECT_NE(session, nullptr);
  15117. callback_called = true;
  15118. return SSLVerifierResponse::NoDecisionMade;
  15119. });
  15120. auto res = cli.Get("/test");
  15121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15122. EXPECT_EQ(200, res->status);
  15123. EXPECT_TRUE(callback_called);
  15124. }
  15125. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15127. ASSERT_TRUE(svr.is_valid());
  15128. svr.Get("/test", [](const Request &, Response &res) {
  15129. res.set_content("ok", "text/plain");
  15130. });
  15131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15132. auto se = detail::scope_exit([&] {
  15133. svr.stop();
  15134. t.join();
  15135. });
  15136. svr.wait_until_ready();
  15137. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15138. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15139. // so we only check that the request fails, not whether the callback was
  15140. // called.
  15141. SSLClient cli(HOST, PORT);
  15142. cli.enable_server_certificate_verification(true);
  15143. cli.set_connection_timeout(30);
  15144. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15145. EXPECT_NE(session, nullptr);
  15146. return SSLVerifierResponse::NoDecisionMade;
  15147. });
  15148. auto res = cli.Get("/test");
  15149. EXPECT_FALSE(res);
  15150. }
  15151. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15152. // Test SSL server using PemMemory constructor with client CA certificates
  15153. // Read PEM files
  15154. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15155. read_file(SERVER_CERT_FILE, server_cert_pem);
  15156. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15157. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15158. // Create SSLServer with PemMemory constructor including client CA
  15159. SSLServer::PemMemory server_pem = {
  15160. server_cert_pem.c_str(),
  15161. server_cert_pem.size(),
  15162. server_key_pem.c_str(),
  15163. server_key_pem.size(),
  15164. client_ca_pem.c_str(),
  15165. client_ca_pem.size(),
  15166. nullptr // no password for server key
  15167. };
  15168. SSLServer svr(server_pem);
  15169. ASSERT_TRUE(svr.is_valid());
  15170. // No SSL error should be recorded for valid setup
  15171. EXPECT_EQ(0, svr.ssl_last_error());
  15172. // Set up server endpoints
  15173. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15174. res.set_content("ok", "text/plain");
  15175. });
  15176. // Start server in a thread
  15177. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15178. svr.wait_until_ready();
  15179. // Connect with client certificate (using constructor with paths)
  15180. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15181. cli.enable_server_certificate_verification(false);
  15182. auto res = cli.Get("/test-pem-ca");
  15183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15184. EXPECT_EQ(200, res->status);
  15185. EXPECT_EQ("ok", res->body);
  15186. svr.stop();
  15187. server_thread.join();
  15188. }
  15189. #endif
  15190. #ifdef _WIN32
  15191. TEST(CleanupTest, WSACleanup) {
  15192. int ret = WSACleanup();
  15193. ASSERT_EQ(0, ret);
  15194. }
  15195. #endif
  15196. #ifndef CPPHTTPLIB_SSL_ENABLED
  15197. TEST(NoSSLSupport, SimpleInterface) {
  15198. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15199. }
  15200. #endif
  15201. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15202. TEST(InvalidScheme, SimpleInterface) {
  15203. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15204. }
  15205. #endif
  15206. TEST(NoScheme, SimpleInterface) {
  15207. Client cli("yahoo.com:80");
  15208. ASSERT_TRUE(cli.is_valid());
  15209. }
  15210. TEST(SendAPI, SimpleInterface_Online) {
  15211. Client cli("http://yahoo.com");
  15212. Request req;
  15213. req.method = "GET";
  15214. req.path = "/";
  15215. auto res = cli.send(req);
  15216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15217. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15218. }
  15219. TEST(SendAPI, WithParamsInRequest) {
  15220. Server svr;
  15221. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15222. EXPECT_TRUE(req.has_param("test"));
  15223. EXPECT_EQ("test_value", req.get_param_value("test"));
  15224. });
  15225. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15226. auto se = detail::scope_exit([&] {
  15227. svr.stop();
  15228. t.join();
  15229. ASSERT_FALSE(svr.is_running());
  15230. });
  15231. svr.wait_until_ready();
  15232. Client cli(HOST, PORT);
  15233. {
  15234. Request req;
  15235. req.method = "GET";
  15236. req.path = "/";
  15237. req.params.emplace("test", "test_value");
  15238. auto res = cli.send(req);
  15239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15240. }
  15241. {
  15242. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15244. }
  15245. }
  15246. TEST(ClientImplMethods, GetSocketTest) {
  15247. httplib::Server svr;
  15248. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15249. res.status = StatusCode::OK_200;
  15250. });
  15251. auto port = svr.bind_to_any_port("127.0.0.1");
  15252. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15253. auto se = detail::scope_exit([&] {
  15254. svr.stop();
  15255. thread.join();
  15256. ASSERT_FALSE(svr.is_running());
  15257. });
  15258. svr.wait_until_ready();
  15259. {
  15260. httplib::Client cli("127.0.0.1", port);
  15261. cli.set_keep_alive(true);
  15262. // Use the behavior of cpp-httplib of opening the connection
  15263. // only when the first request happens. If that changes,
  15264. // this test would be obsolete.
  15265. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15266. // This also implicitly tests the server. But other tests would fail much
  15267. // earlier than this one to be considered.
  15268. auto res = cli.Get("/");
  15269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15270. EXPECT_EQ(StatusCode::OK_200, res->status);
  15271. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15272. }
  15273. }
  15274. #ifdef CPPHTTPLIB_SSL_ENABLED
  15275. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15276. Client cli("http://yahoo.com");
  15277. auto res = cli.Get("/");
  15278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15279. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15280. cli.set_follow_location(true);
  15281. res = cli.Get("/");
  15282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15283. EXPECT_EQ(StatusCode::OK_200, res->status);
  15284. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15285. }
  15286. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15287. Client cli("https://yahoo.com");
  15288. auto res = cli.Get("/");
  15289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15290. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15291. cli.set_follow_location(true);
  15292. res = cli.Get("/");
  15293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15294. EXPECT_EQ(StatusCode::OK_200, res->status);
  15295. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15296. }
  15297. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15298. Client cli("https://yahoo.com");
  15299. auto res = cli.Get("/");
  15300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15301. ASSERT_FALSE(!res);
  15302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15303. ASSERT_FALSE(res == nullptr);
  15304. ASSERT_TRUE(res != nullptr);
  15305. EXPECT_EQ(Error::Success, res.error());
  15306. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15307. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15308. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15309. cli.set_follow_location(true);
  15310. res = cli.Get("/");
  15311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15312. EXPECT_EQ(Error::Success, res.error());
  15313. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15314. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15315. EXPECT_EQ(StatusCode::OK_200, res->status);
  15316. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15317. }
  15318. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15319. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15320. Client cli("https://cdnjs.cloudflare.com");
  15321. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15322. Headers{{"Accept-Encoding", "br"}});
  15323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15324. EXPECT_EQ(StatusCode::OK_200, res->status);
  15325. EXPECT_EQ(287630U, res->body.size());
  15326. EXPECT_EQ("application/javascript; charset=utf-8",
  15327. res->get_header_value("Content-Type"));
  15328. }
  15329. #endif
  15330. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15331. #undef REDIR_HOST // Silence compiler warning
  15332. #define REDIR_HOST "https://httpbingo.org"
  15333. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15334. Client cli(REDIR_HOST);
  15335. cli.set_follow_location(true);
  15336. auto res =
  15337. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15339. EXPECT_EQ(StatusCode::OK_200, res->status);
  15340. }
  15341. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15342. Client cli(REDIR_HOST);
  15343. cli.set_follow_location(true);
  15344. Params params;
  15345. params.emplace("url", "http://example.com");
  15346. params.emplace("status_code", "302");
  15347. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15349. EXPECT_EQ(StatusCode::OK_200, res->status);
  15350. }
  15351. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15352. Client cli(REDIR_HOST);
  15353. cli.set_follow_location(true);
  15354. Params params;
  15355. params.emplace("url", "http://example.com");
  15356. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15358. EXPECT_EQ(StatusCode::OK_200, res->status);
  15359. }
  15360. TEST(HttpToHttpsRedirectTest, CertFile) {
  15361. auto ssl_port = PORT + 1;
  15362. Server svr;
  15363. ASSERT_TRUE(svr.is_valid());
  15364. svr.Get("/index", [&](const Request &, Response &res) {
  15365. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15366. "/index");
  15367. svr.stop();
  15368. });
  15369. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15370. ASSERT_TRUE(ssl_svr.is_valid());
  15371. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15372. res.set_content("test", "text/plain");
  15373. ssl_svr.stop();
  15374. });
  15375. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15376. thread t2 =
  15377. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15378. auto se = detail::scope_exit([&] {
  15379. t2.join();
  15380. t.join();
  15381. ASSERT_FALSE(svr.is_running());
  15382. });
  15383. svr.wait_until_ready();
  15384. ssl_svr.wait_until_ready();
  15385. Client cli("127.0.0.1", PORT);
  15386. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15387. cli.enable_server_certificate_verification(true);
  15388. cli.set_follow_location(true);
  15389. cli.set_connection_timeout(30);
  15390. auto res = cli.Get("/index");
  15391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15392. ASSERT_EQ(StatusCode::OK_200, res->status);
  15393. }
  15394. TEST(SSLClientRedirectTest, CertFile) {
  15395. auto ssl_port = PORT + 1;
  15396. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15397. ASSERT_TRUE(ssl_svr1.is_valid());
  15398. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15399. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15400. "/index");
  15401. ssl_svr1.stop();
  15402. });
  15403. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15404. ASSERT_TRUE(ssl_svr2.is_valid());
  15405. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15406. res.set_content("test", "text/plain");
  15407. ssl_svr2.stop();
  15408. });
  15409. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15410. thread t2 =
  15411. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15412. auto se = detail::scope_exit([&] {
  15413. t2.join();
  15414. t.join();
  15415. ASSERT_FALSE(ssl_svr1.is_running());
  15416. });
  15417. ssl_svr1.wait_until_ready();
  15418. ssl_svr2.wait_until_ready();
  15419. SSLClient cli("127.0.0.1", PORT);
  15420. std::string cert;
  15421. read_file(SERVER_CERT2_FILE, cert);
  15422. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15423. cli.enable_server_certificate_verification(true);
  15424. cli.set_follow_location(true);
  15425. cli.set_connection_timeout(30);
  15426. auto res = cli.Get("/index");
  15427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15428. ASSERT_EQ(StatusCode::OK_200, res->status);
  15429. }
  15430. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15431. // another port, so the client follows it with a new client.
  15432. static Result GetThroughTlsRedirectToDifferentPort(
  15433. const std::function<void(SSLClient &)> &setup,
  15434. const char *target_cert = SERVER_CERT2_FILE,
  15435. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15436. auto ssl_port = PORT + 1;
  15437. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15438. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15439. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15440. "/index");
  15441. });
  15442. SSLServer ssl_svr2(target_cert, target_key);
  15443. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15444. res.set_content("test", "text/plain");
  15445. });
  15446. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15447. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15448. auto se = detail::scope_exit([&] {
  15449. ssl_svr2.stop();
  15450. ssl_svr1.stop();
  15451. t2.join();
  15452. t.join();
  15453. });
  15454. ssl_svr1.wait_until_ready();
  15455. ssl_svr2.wait_until_ready();
  15456. SSLClient cli("127.0.0.1", PORT);
  15457. cli.set_follow_location(true);
  15458. cli.set_connection_timeout(30);
  15459. setup(cli);
  15460. return cli.Get("/index");
  15461. }
  15462. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15463. auto calls = 0;
  15464. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15465. cli.enable_server_certificate_verification(false);
  15466. // Accept the first server only.
  15467. cli.set_session_verifier([&](tls::session_t) {
  15468. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15469. : SSLVerifierResponse::CertificateRejected;
  15470. });
  15471. });
  15472. ASSERT_FALSE(res);
  15473. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15474. EXPECT_EQ(2, calls);
  15475. }
  15476. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15477. std::string pinned;
  15478. auto res = GetThroughTlsRedirectToDifferentPort(
  15479. [&](SSLClient &cli) {
  15480. cli.enable_server_certificate_verification(false);
  15481. // Pin the first certificate seen.
  15482. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15483. if (pinned.empty()) { pinned = ctx.serial(); }
  15484. return ctx.serial() == pinned;
  15485. });
  15486. },
  15487. // A certificate other than the first server's.
  15488. SERVER_CERT_FILE);
  15489. EXPECT_FALSE(res);
  15490. EXPECT_FALSE(pinned.empty());
  15491. }
  15492. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15493. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15494. std::string cert;
  15495. read_file(SERVER_CERT2_FILE, cert);
  15496. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15497. });
  15498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15499. EXPECT_EQ(StatusCode::OK_200, res->status);
  15500. }
  15501. // The target's certificate is signed by the root CA, which the first server's
  15502. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15503. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15504. auto res = GetThroughTlsRedirectToDifferentPort(
  15505. [](SSLClient &cli) {
  15506. std::string root_ca, cert;
  15507. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15508. read_file(SERVER_CERT2_FILE, cert);
  15509. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15510. cli.load_ca_cert_store(cert.data(), cert.size());
  15511. cli.enable_server_hostname_verification(false);
  15512. },
  15513. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15515. EXPECT_EQ(StatusCode::OK_200, res->status);
  15516. }
  15517. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15518. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15519. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15520. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15521. auto res = GetThroughTlsRedirectToDifferentPort(
  15522. [](SSLClient &cli) {
  15523. std::string root_ca, cert;
  15524. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15525. read_file(SERVER_CERT2_FILE, cert);
  15526. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15527. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15528. cli.enable_server_hostname_verification(false);
  15529. },
  15530. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15531. ASSERT_FALSE(res);
  15532. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15533. }
  15534. #endif
  15535. #endif
  15536. #ifdef CPPHTTPLIB_SSL_ENABLED
  15537. // Test that set_ca_cert_store() skips system certs (consistent with
  15538. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15539. // should be trusted - system certs should NOT be loaded.
  15540. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15541. // Load a specific cert that is NOT a system CA cert
  15542. std::string cert;
  15543. read_file(SERVER_CERT2_FILE, cert);
  15544. SSLClient cli("google.com");
  15545. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15546. cli.enable_server_certificate_verification(true);
  15547. // This should FAIL because:
  15548. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15549. // 2. System certs should NOT be loaded when custom store is set
  15550. // If system certs WERE loaded, this would succeed
  15551. auto res = cli.Get("/");
  15552. ASSERT_FALSE(res);
  15553. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15554. }
  15555. // Same as above, but through the native store handle path. Regression test:
  15556. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15557. // merged system certs into the user-provided store.
  15558. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15559. std::string cert;
  15560. read_file(SERVER_CERT2_FILE, cert);
  15561. SSLClient cli("google.com");
  15562. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15563. cli.enable_server_certificate_verification(true);
  15564. auto res = cli.Get("/");
  15565. ASSERT_FALSE(res);
  15566. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15567. }
  15568. // A custom store set via the native handle must still verify a server whose
  15569. // cert it does contain.
  15570. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15571. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15572. ASSERT_TRUE(svr.is_valid());
  15573. svr.Get("/test", [&](const Request &, Response &res) {
  15574. res.set_content("test", "text/plain");
  15575. });
  15576. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15577. auto se = detail::scope_exit([&] {
  15578. svr.stop();
  15579. t.join();
  15580. ASSERT_FALSE(svr.is_running());
  15581. });
  15582. svr.wait_until_ready();
  15583. SSLClient cli("127.0.0.1", PORT);
  15584. std::string cert;
  15585. read_file(SERVER_CERT2_FILE, cert);
  15586. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15587. cli.enable_server_certificate_verification(true);
  15588. cli.set_connection_timeout(30);
  15589. auto res = cli.Get("/test");
  15590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15591. ASSERT_EQ(StatusCode::OK_200, res->status);
  15592. }
  15593. // CA certs loaded through the universal Client must be transferred to the
  15594. // client created internally for following an HTTPS redirect. Regression test:
  15595. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15596. // the CA data for redirect transfer.
  15597. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15598. auto ssl_port = PORT + 1;
  15599. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15600. ASSERT_TRUE(ssl_svr1.is_valid());
  15601. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15602. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15603. "/index");
  15604. });
  15605. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15606. ASSERT_TRUE(ssl_svr2.is_valid());
  15607. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15608. res.set_content("test", "text/plain");
  15609. });
  15610. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15611. thread t2 =
  15612. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15613. auto se = detail::scope_exit([&] {
  15614. ssl_svr2.stop();
  15615. ssl_svr1.stop();
  15616. t2.join();
  15617. t.join();
  15618. ASSERT_FALSE(ssl_svr1.is_running());
  15619. });
  15620. ssl_svr1.wait_until_ready();
  15621. ssl_svr2.wait_until_ready();
  15622. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15623. std::string cert;
  15624. read_file(SERVER_CERT2_FILE, cert);
  15625. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15626. cli.enable_server_certificate_verification(true);
  15627. cli.set_follow_location(true);
  15628. cli.set_connection_timeout(30);
  15629. auto res = cli.Get("/index");
  15630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15631. ASSERT_EQ(StatusCode::OK_200, res->status);
  15632. }
  15633. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15634. // so a host signed by a system CA verifies even though a custom CA is set
  15635. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15636. std::string cert;
  15637. read_file(SERVER_CERT2_FILE, cert);
  15638. SSLClient cli("google.com");
  15639. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15640. cli.enable_system_ca(true);
  15641. cli.enable_server_certificate_verification(true);
  15642. auto res = cli.Get("/");
  15643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15644. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15645. }
  15646. // The custom CA remains effective when combined with the system CA
  15647. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15648. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15649. ASSERT_TRUE(svr.is_valid());
  15650. svr.Get("/test", [&](const Request &, Response &res) {
  15651. res.set_content("test", "text/plain");
  15652. });
  15653. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15654. auto se = detail::scope_exit([&] {
  15655. svr.stop();
  15656. t.join();
  15657. ASSERT_FALSE(svr.is_running());
  15658. });
  15659. svr.wait_until_ready();
  15660. SSLClient cli("127.0.0.1", PORT);
  15661. std::string cert;
  15662. read_file(SERVER_CERT2_FILE, cert);
  15663. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15664. cli.enable_system_ca(true);
  15665. cli.enable_server_certificate_verification(true);
  15666. cli.set_connection_timeout(30);
  15667. auto res = cli.Get("/test");
  15668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15669. ASSERT_EQ(StatusCode::OK_200, res->status);
  15670. }
  15671. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15672. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15673. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15674. static CFDictionaryRef
  15675. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15676. const SecTrustSettingsResult *result) {
  15677. auto constraint =
  15678. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15679. &kCFTypeDictionaryValueCallBacks);
  15680. if (policy) {
  15681. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15682. }
  15683. if (policy_string) {
  15684. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15685. kCFStringEncodingUTF8);
  15686. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15687. CFRelease(str);
  15688. }
  15689. if (result) {
  15690. auto number_value = static_cast<SInt32>(*result);
  15691. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15692. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15693. CFRelease(number);
  15694. }
  15695. return constraint;
  15696. }
  15697. static SecTrustSettingsResult
  15698. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15699. auto trust_settings =
  15700. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15701. for (auto constraint : constraints) {
  15702. CFArrayAppendValue(trust_settings, constraint);
  15703. CFRelease(constraint);
  15704. }
  15705. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15706. CFRelease(trust_settings);
  15707. return result;
  15708. }
  15709. // The system CA loader takes a Keychain certificate as a trusted root only
  15710. // when its Trust Settings say so for SSL, not merely because it has some.
  15711. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15712. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15713. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15714. const auto deny = kSecTrustSettingsResultDeny;
  15715. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15716. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15717. auto x509_policy = SecPolicyCreateBasicX509();
  15718. // "Always Trust", which stores no constraint at all
  15719. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15720. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15721. ssl_trust_settings_result(
  15722. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15723. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15724. ssl_trust_settings_result(
  15725. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15726. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15727. ssl_trust_settings_result(
  15728. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15729. // "Never Trust", for everything or for SSL
  15730. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15731. ssl_trust_settings_result(
  15732. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15733. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15734. ssl_trust_settings_result(
  15735. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15736. // Trusted for another policy, for one host, or not at all
  15737. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15738. ssl_trust_settings_result(
  15739. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15740. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15741. ssl_trust_settings_result({make_usage_constraint(
  15742. ssl_policy, "www.example.com", &trust_root)}));
  15743. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15744. ssl_trust_settings_result(
  15745. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15746. // The first constraint that applies to SSL decides
  15747. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15748. ssl_trust_settings_result(
  15749. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15750. make_usage_constraint(nullptr, nullptr, &deny)}));
  15751. CFRelease(x509_policy);
  15752. CFRelease(ssl_policy);
  15753. }
  15754. #endif
  15755. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15756. // skip chain verification entirely (only the certificate identity was
  15757. // checked), so a server presenting an untrusted certificate with a matching
  15758. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15759. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15760. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15761. ASSERT_TRUE(svr.is_valid());
  15762. svr.Get("/test", [&](const Request &, Response &res) {
  15763. res.set_content("test", "text/plain");
  15764. });
  15765. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15766. auto se = detail::scope_exit([&] {
  15767. svr.stop();
  15768. t.join();
  15769. ASSERT_FALSE(svr.is_running());
  15770. });
  15771. svr.wait_until_ready();
  15772. SSLClient cli("127.0.0.1", PORT);
  15773. std::string cert;
  15774. // A trusted CA that did not sign the server certificate. The server cert
  15775. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15776. // this connection.
  15777. read_file(CLIENT_CA_CERT_FILE, cert);
  15778. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15779. cli.enable_server_certificate_verification(true);
  15780. cli.set_connection_timeout(30);
  15781. auto res = cli.Get("/test");
  15782. ASSERT_FALSE(res);
  15783. }
  15784. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15785. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15786. // CA that failed to come through fails verification instead of trusting them.
  15787. // (wolfSSL does not list the system CAs it loaded.)
  15788. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15789. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15790. ASSERT_TRUE(svr.is_valid());
  15791. auto port = svr.bind_to_any_port("127.0.0.1");
  15792. ASSERT_LT(0, port);
  15793. thread t = thread([&] { svr.listen_after_bind(); });
  15794. auto se = detail::scope_exit([&] {
  15795. svr.stop();
  15796. t.join();
  15797. ASSERT_FALSE(svr.is_running());
  15798. });
  15799. svr.wait_until_ready();
  15800. // The CAs a client trusts once its first request has loaded them
  15801. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15802. Client cli("https://127.0.0.1:" + std::to_string(port));
  15803. setup(cli);
  15804. cli.Get("/");
  15805. return tls::get_ca_names(cli.tls_context()).size();
  15806. };
  15807. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15808. EXPECT_EQ(0u,
  15809. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15810. }
  15811. #endif
  15812. // A TLS setting changed between requests applies to the next one, not just to
  15813. // the next connection
  15814. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15815. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15816. ASSERT_TRUE(svr.is_valid());
  15817. svr.Get("/", [](const Request &req, Response &res) {
  15818. res.set_content(std::to_string(req.remote_port), "text/plain");
  15819. });
  15820. auto port = svr.bind_to_any_port("127.0.0.1");
  15821. ASSERT_LT(0, port);
  15822. thread t = thread([&] { svr.listen_after_bind(); });
  15823. auto se = detail::scope_exit([&] {
  15824. svr.stop();
  15825. t.join();
  15826. ASSERT_FALSE(svr.is_running());
  15827. });
  15828. svr.wait_until_ready();
  15829. SSLClient cli("127.0.0.1", port);
  15830. cli.set_keep_alive(true);
  15831. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15832. cli.enable_server_certificate_verification(false);
  15833. // The port the request went out from, so a new one means a new connection
  15834. auto client_port = [&] {
  15835. auto res = cli.Get("/");
  15836. return res ? res->body : std::string();
  15837. };
  15838. auto last = client_port();
  15839. ASSERT_FALSE(last.empty());
  15840. // Setting a value it already has keeps the connection
  15841. cli.enable_server_certificate_verification(false);
  15842. cli.enable_server_hostname_verification(true);
  15843. EXPECT_EQ(last, client_port());
  15844. cli.enable_server_certificate_verification(true);
  15845. auto res = cli.Get("/");
  15846. EXPECT_FALSE(res);
  15847. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15848. std::string ca;
  15849. read_file(SERVER_CERT2_FILE, ca);
  15850. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15851. last = client_port();
  15852. ASSERT_FALSE(last.empty());
  15853. std::vector<std::function<void()>> setters = {
  15854. [&] { cli.enable_server_hostname_verification(false); },
  15855. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15856. [&] {
  15857. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15858. },
  15859. [&] {
  15860. cli.set_server_certificate_verifier(
  15861. [](const tls::VerifyContext &) { return true; });
  15862. },
  15863. [&] {
  15864. cli.set_session_verifier(
  15865. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15866. },
  15867. };
  15868. for (const auto &setter : setters) {
  15869. setter();
  15870. auto next = client_port();
  15871. ASSERT_FALSE(next.empty());
  15872. EXPECT_NE(last, next);
  15873. last = next;
  15874. }
  15875. cli.set_session_verifier(
  15876. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15877. auto handle = cli.open_stream("GET", "/");
  15878. EXPECT_FALSE(handle.is_valid());
  15879. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15880. }
  15881. // A PEM given to create_ca_store() needs no NUL after it
  15882. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15883. std::string pem;
  15884. read_file(SERVER_CERT2_FILE, pem);
  15885. auto buf = pem + "X";
  15886. auto store = tls::create_ca_store(buf.data(), pem.size());
  15887. EXPECT_TRUE(store != nullptr);
  15888. SSLClient cli("localhost");
  15889. cli.set_ca_cert_store(store);
  15890. }
  15891. // enable_system_ca(false) prevents system CA loading entirely
  15892. TEST(SSLClientTest, DisableSystemCa_Online) {
  15893. SSLClient cli("google.com");
  15894. cli.enable_system_ca(false);
  15895. cli.enable_server_certificate_verification(true);
  15896. auto res = cli.Get("/");
  15897. ASSERT_FALSE(res);
  15898. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15899. // itself when the CA chain is empty
  15900. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15901. res.error() == Error::SSLConnection);
  15902. }
  15903. // The universal Client forwards enable_system_ca()
  15904. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15905. std::string cert;
  15906. read_file(SERVER_CERT2_FILE, cert);
  15907. Client cli("https://google.com");
  15908. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15909. cli.enable_system_ca(true);
  15910. cli.enable_server_certificate_verification(true);
  15911. auto res = cli.Get("/");
  15912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15913. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15914. }
  15915. // The system CA policy must carry over to the client created internally for
  15916. // following a cross-host HTTPS redirect
  15917. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15918. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15919. ASSERT_TRUE(svr.is_valid());
  15920. svr.Get("/index", [&](const Request &, Response &res) {
  15921. res.set_redirect("https://www.google.com/");
  15922. });
  15923. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15924. auto se = detail::scope_exit([&] {
  15925. svr.stop();
  15926. t.join();
  15927. ASSERT_FALSE(svr.is_running());
  15928. });
  15929. svr.wait_until_ready();
  15930. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15931. std::string cert;
  15932. read_file(SERVER_CERT2_FILE, cert);
  15933. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15934. cli.enable_system_ca(true);
  15935. cli.enable_server_certificate_verification(true);
  15936. cli.set_follow_location(true);
  15937. cli.set_connection_timeout(30);
  15938. // Receiving any response proves the redirect client completed the TLS
  15939. // handshake with a system-CA-signed host
  15940. auto res = cli.Get("/index");
  15941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15942. }
  15943. TEST(MultipartFormDataTest, LargeData) {
  15944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15945. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15946. const ContentReader &content_reader) {
  15947. if (req.is_multipart_form_data()) {
  15948. std::vector<FormData> items;
  15949. content_reader(
  15950. [&](const FormData &file) {
  15951. items.push_back(file);
  15952. return true;
  15953. },
  15954. [&](const char *data, size_t data_length) {
  15955. items.back().content.append(data, data_length);
  15956. return true;
  15957. });
  15958. EXPECT_TRUE(std::string(items[0].name) == "document");
  15959. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15960. EXPECT_TRUE(items[0].filename == "2MB_data");
  15961. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15962. EXPECT_TRUE(items[1].name == "hello");
  15963. EXPECT_TRUE(items[1].content == "world");
  15964. EXPECT_TRUE(items[1].filename == "");
  15965. EXPECT_TRUE(items[1].content_type == "");
  15966. } else {
  15967. std::string body;
  15968. content_reader([&](const char *data, size_t data_length) {
  15969. body.append(data, data_length);
  15970. return true;
  15971. });
  15972. }
  15973. });
  15974. auto port = svr.bind_to_any_port(HOST);
  15975. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15976. auto se = detail::scope_exit([&] {
  15977. svr.stop();
  15978. t.join();
  15979. ASSERT_FALSE(svr.is_running());
  15980. });
  15981. svr.wait_until_ready();
  15982. {
  15983. std::string data(1024 * 1024 * 2, '.');
  15984. std::stringstream buffer;
  15985. buffer << data;
  15986. SSLClient cli(HOST, port);
  15987. cli.enable_server_certificate_verification(false);
  15988. UploadFormDataItems items{
  15989. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15990. {"hello", "world", "", ""},
  15991. };
  15992. auto res = cli.Post("/post", items);
  15993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15994. ASSERT_EQ(StatusCode::OK_200, res->status);
  15995. }
  15996. }
  15997. TEST(MultipartFormDataTest, DataProviderItems) {
  15998. std::random_device seed_gen;
  15999. std::mt19937 random(seed_gen());
  16000. std::string rand1;
  16001. rand1.resize(1000);
  16002. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16003. std::string rand2;
  16004. rand2.resize(3000);
  16005. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16007. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16008. const ContentReader &content_reader) {
  16009. ASSERT_FALSE(req.is_multipart_form_data());
  16010. std::string body;
  16011. content_reader([&](const char *data, size_t data_length) {
  16012. body.append(data, data_length);
  16013. return true;
  16014. });
  16015. EXPECT_EQ(body, "");
  16016. });
  16017. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16018. const ContentReader &content_reader) {
  16019. ASSERT_TRUE(req.is_multipart_form_data());
  16020. std::vector<FormData> items;
  16021. content_reader(
  16022. [&](const FormData &file) {
  16023. items.push_back(file);
  16024. return true;
  16025. },
  16026. [&](const char *data, size_t data_length) {
  16027. items.back().content.append(data, data_length);
  16028. return true;
  16029. });
  16030. ASSERT_TRUE(items.size() == 2);
  16031. EXPECT_EQ(std::string(items[0].name), "name1");
  16032. EXPECT_EQ(items[0].content, "Testing123");
  16033. EXPECT_EQ(items[0].filename, "filename1");
  16034. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16035. EXPECT_EQ(items[1].name, "name2");
  16036. EXPECT_EQ(items[1].content, "Testing456");
  16037. EXPECT_EQ(items[1].filename, "");
  16038. EXPECT_EQ(items[1].content_type, "");
  16039. });
  16040. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16041. const ContentReader &content_reader) {
  16042. ASSERT_TRUE(req.is_multipart_form_data());
  16043. std::vector<FormData> items;
  16044. content_reader(
  16045. [&](const FormData &file) {
  16046. items.push_back(file);
  16047. return true;
  16048. },
  16049. [&](const char *data, size_t data_length) {
  16050. items.back().content.append(data, data_length);
  16051. return true;
  16052. });
  16053. ASSERT_TRUE(items.size() == 2);
  16054. EXPECT_EQ(items[0].name, "name3");
  16055. EXPECT_EQ(items[0].content, rand1);
  16056. EXPECT_EQ(items[0].filename, "filename3");
  16057. EXPECT_EQ(items[0].content_type, "");
  16058. EXPECT_EQ(items[1].name, "name4");
  16059. EXPECT_EQ(items[1].content, rand2);
  16060. EXPECT_EQ(items[1].filename, "filename4");
  16061. EXPECT_EQ(items[1].content_type, "");
  16062. });
  16063. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16064. const ContentReader &content_reader) {
  16065. ASSERT_TRUE(req.is_multipart_form_data());
  16066. std::vector<FormData> items;
  16067. content_reader(
  16068. [&](const FormData &file) {
  16069. items.push_back(file);
  16070. return true;
  16071. },
  16072. [&](const char *data, size_t data_length) {
  16073. items.back().content.append(data, data_length);
  16074. return true;
  16075. });
  16076. ASSERT_TRUE(items.size() == 4);
  16077. EXPECT_EQ(std::string(items[0].name), "name1");
  16078. EXPECT_EQ(items[0].content, "Testing123");
  16079. EXPECT_EQ(items[0].filename, "filename1");
  16080. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16081. EXPECT_EQ(items[1].name, "name2");
  16082. EXPECT_EQ(items[1].content, "Testing456");
  16083. EXPECT_EQ(items[1].filename, "");
  16084. EXPECT_EQ(items[1].content_type, "");
  16085. EXPECT_EQ(items[2].name, "name3");
  16086. EXPECT_EQ(items[2].content, rand1);
  16087. EXPECT_EQ(items[2].filename, "filename3");
  16088. EXPECT_EQ(items[2].content_type, "");
  16089. EXPECT_EQ(items[3].name, "name4");
  16090. EXPECT_EQ(items[3].content, rand2);
  16091. EXPECT_EQ(items[3].filename, "filename4");
  16092. EXPECT_EQ(items[3].content_type, "");
  16093. });
  16094. auto port = svr.bind_to_any_port("localhost");
  16095. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16096. auto se = detail::scope_exit([&] {
  16097. svr.stop();
  16098. t.join();
  16099. ASSERT_FALSE(svr.is_running());
  16100. });
  16101. svr.wait_until_ready();
  16102. {
  16103. SSLClient cli("localhost", port);
  16104. cli.enable_server_certificate_verification(false);
  16105. UploadFormDataItems items{
  16106. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16107. {"name2", "Testing456", "", ""}, // not a file
  16108. };
  16109. {
  16110. auto res = cli.Post("/post-none", {}, {}, {});
  16111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16112. ASSERT_EQ(StatusCode::OK_200, res->status);
  16113. }
  16114. FormDataProviderItems providers;
  16115. {
  16116. auto res =
  16117. cli.Post("/post-items", {}, items, providers); // empty providers
  16118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16119. ASSERT_EQ(StatusCode::OK_200, res->status);
  16120. }
  16121. providers.push_back({"name3",
  16122. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16123. // test the offset is given correctly at each step
  16124. if (!offset)
  16125. sink.os.write(rand1.data(), 30);
  16126. else if (offset == 30)
  16127. sink.os.write(rand1.data() + 30, 300);
  16128. else if (offset == 330)
  16129. sink.os.write(rand1.data() + 330, 670);
  16130. else if (offset == rand1.size())
  16131. sink.done();
  16132. return true;
  16133. },
  16134. "filename3",
  16135. {}});
  16136. providers.push_back({"name4",
  16137. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16138. // test the offset is given correctly at each step
  16139. if (!offset)
  16140. sink.os.write(rand2.data(), 2000);
  16141. else if (offset == 2000)
  16142. sink.os.write(rand2.data() + 2000, 1);
  16143. else if (offset == 2001)
  16144. sink.os.write(rand2.data() + 2001, 999);
  16145. else if (offset == rand2.size())
  16146. sink.done();
  16147. return true;
  16148. },
  16149. "filename4",
  16150. {}});
  16151. {
  16152. auto res = cli.Post("/post-providers", {}, {}, providers);
  16153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16154. ASSERT_EQ(StatusCode::OK_200, res->status);
  16155. }
  16156. {
  16157. auto res = cli.Post("/post-both", {}, items, providers);
  16158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16159. ASSERT_EQ(StatusCode::OK_200, res->status);
  16160. }
  16161. }
  16162. }
  16163. TEST(MultipartFormDataTest, BadHeader) {
  16164. Server svr;
  16165. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16166. res.set_content("ok", "text/plain");
  16167. });
  16168. thread t = thread([&] { svr.listen(HOST, PORT); });
  16169. auto se = detail::scope_exit([&] {
  16170. svr.stop();
  16171. t.join();
  16172. ASSERT_FALSE(svr.is_running());
  16173. });
  16174. svr.wait_until_ready();
  16175. const std::string body =
  16176. "This is the preamble. It is to be ignored, though it\r\n"
  16177. "is a handy place for composition agents to include an\r\n"
  16178. "explanatory note to non-MIME conformant readers.\r\n"
  16179. "\r\n"
  16180. "\r\n"
  16181. "--simple boundary\r\n"
  16182. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16183. ": BAD...\r\n"
  16184. "\r\n"
  16185. "value1\r\n"
  16186. "--simple boundary\r\n"
  16187. "Content-Disposition: form-data; name=\"field2\"; "
  16188. "filename=\"example.txt\"\r\n"
  16189. "\r\n"
  16190. "value2\r\n"
  16191. "--simple boundary--\r\n"
  16192. "This is the epilogue. It is also to be ignored.\r\n";
  16193. std::string content_type =
  16194. R"(multipart/form-data; boundary="simple boundary")";
  16195. Client cli(HOST, PORT);
  16196. auto res = cli.Post("/post", body, content_type.c_str());
  16197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16198. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16199. }
  16200. TEST(MultipartFormDataTest, WithPreamble) {
  16201. Server svr;
  16202. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16203. res.set_content("ok", "text/plain");
  16204. });
  16205. thread t = thread([&] { svr.listen(HOST, PORT); });
  16206. auto se = detail::scope_exit([&] {
  16207. svr.stop();
  16208. t.join();
  16209. ASSERT_FALSE(svr.is_running());
  16210. });
  16211. svr.wait_until_ready();
  16212. const std::string body =
  16213. "This is the preamble. It is to be ignored, though it\r\n"
  16214. "is a handy place for composition agents to include an\r\n"
  16215. "explanatory note to non-MIME conformant readers.\r\n"
  16216. "\r\n"
  16217. "\r\n"
  16218. "--simple boundary\r\n"
  16219. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16220. "\r\n"
  16221. "value1\r\n"
  16222. "--simple boundary\r\n"
  16223. "Content-Disposition: form-data; name=\"field2\"; "
  16224. "filename=\"example.txt\"\r\n"
  16225. "\r\n"
  16226. "value2\r\n"
  16227. "--simple boundary--\r\n"
  16228. "This is the epilogue. It is also to be ignored.\r\n";
  16229. std::string content_type =
  16230. R"(multipart/form-data; boundary="simple boundary")";
  16231. Client cli(HOST, PORT);
  16232. auto res = cli.Post("/post", body, content_type.c_str());
  16233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16234. EXPECT_EQ(StatusCode::OK_200, res->status);
  16235. }
  16236. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16237. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16238. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16239. const ContentReader &content_reader) {
  16240. if (req.is_multipart_form_data()) {
  16241. std::vector<FormData> items;
  16242. content_reader(
  16243. [&](const FormData &file) {
  16244. items.push_back(file);
  16245. return true;
  16246. },
  16247. [&](const char *data, size_t data_length) {
  16248. items.back().content.append(data, data_length);
  16249. return true;
  16250. });
  16251. EXPECT_TRUE(std::string(items[0].name) == "document");
  16252. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16253. EXPECT_TRUE(items[0].filename == "2MB_data");
  16254. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16255. EXPECT_TRUE(items[1].name == "hello");
  16256. EXPECT_TRUE(items[1].content == "world");
  16257. EXPECT_TRUE(items[1].filename == "");
  16258. EXPECT_TRUE(items[1].content_type == "");
  16259. } else {
  16260. std::string body;
  16261. content_reader([&](const char *data, size_t data_length) {
  16262. body.append(data, data_length);
  16263. return true;
  16264. });
  16265. }
  16266. });
  16267. auto port = svr.bind_to_any_port("localhost");
  16268. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16269. auto se = detail::scope_exit([&] {
  16270. svr.stop();
  16271. t.join();
  16272. ASSERT_FALSE(svr.is_running());
  16273. });
  16274. svr.wait_until_ready();
  16275. {
  16276. std::string data(1024 * 1024 * 2, '.');
  16277. std::stringstream buffer;
  16278. buffer << data;
  16279. SSLClient cli("localhost", port);
  16280. cli.enable_server_certificate_verification(false);
  16281. UploadFormDataItems items{
  16282. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16283. {"hello", "world", "", ""},
  16284. };
  16285. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16287. ASSERT_EQ(StatusCode::OK_200, res->status);
  16288. }
  16289. }
  16290. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16291. std::string data(1024 * 1024 * 2, '&');
  16292. std::stringstream buffer;
  16293. buffer << data;
  16294. Client cli("https://localhost:8080");
  16295. UploadFormDataItems items{
  16296. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16297. {"hello", "world", "", ""},
  16298. };
  16299. for (const char &c : " \t\r\n") {
  16300. auto res =
  16301. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16302. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16303. ASSERT_FALSE(res);
  16304. }
  16305. }
  16306. TEST(MultipartFormDataTest, PutFormData) {
  16307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16308. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16309. const ContentReader &content_reader) {
  16310. if (req.is_multipart_form_data()) {
  16311. std::vector<FormData> items;
  16312. content_reader(
  16313. [&](const FormData &file) {
  16314. items.push_back(file);
  16315. return true;
  16316. },
  16317. [&](const char *data, size_t data_length) {
  16318. items.back().content.append(data, data_length);
  16319. return true;
  16320. });
  16321. EXPECT_TRUE(std::string(items[0].name) == "document");
  16322. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16323. EXPECT_TRUE(items[0].filename == "2MB_data");
  16324. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16325. EXPECT_TRUE(items[1].name == "hello");
  16326. EXPECT_TRUE(items[1].content == "world");
  16327. EXPECT_TRUE(items[1].filename == "");
  16328. EXPECT_TRUE(items[1].content_type == "");
  16329. } else {
  16330. std::string body;
  16331. content_reader([&](const char *data, size_t data_length) {
  16332. body.append(data, data_length);
  16333. return true;
  16334. });
  16335. }
  16336. });
  16337. auto port = svr.bind_to_any_port("localhost");
  16338. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16339. auto se = detail::scope_exit([&] {
  16340. svr.stop();
  16341. t.join();
  16342. ASSERT_FALSE(svr.is_running());
  16343. });
  16344. svr.wait_until_ready();
  16345. {
  16346. std::string data(1024 * 1024 * 2, '&');
  16347. std::stringstream buffer;
  16348. buffer << data;
  16349. SSLClient cli("localhost", port);
  16350. cli.enable_server_certificate_verification(false);
  16351. UploadFormDataItems items{
  16352. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16353. {"hello", "world", "", ""},
  16354. };
  16355. auto res = cli.Put("/put", items);
  16356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16357. ASSERT_EQ(StatusCode::OK_200, res->status);
  16358. }
  16359. }
  16360. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16362. svr.Put("/put_customboundary",
  16363. [&](const Request &req, const Response & /*res*/,
  16364. const ContentReader &content_reader) {
  16365. if (req.is_multipart_form_data()) {
  16366. std::vector<FormData> items;
  16367. content_reader(
  16368. [&](const FormData &file) {
  16369. items.push_back(file);
  16370. return true;
  16371. },
  16372. [&](const char *data, size_t data_length) {
  16373. items.back().content.append(data, data_length);
  16374. return true;
  16375. });
  16376. EXPECT_TRUE(std::string(items[0].name) == "document");
  16377. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16378. EXPECT_TRUE(items[0].filename == "2MB_data");
  16379. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16380. EXPECT_TRUE(items[1].name == "hello");
  16381. EXPECT_TRUE(items[1].content == "world");
  16382. EXPECT_TRUE(items[1].filename == "");
  16383. EXPECT_TRUE(items[1].content_type == "");
  16384. } else {
  16385. std::string body;
  16386. content_reader([&](const char *data, size_t data_length) {
  16387. body.append(data, data_length);
  16388. return true;
  16389. });
  16390. }
  16391. });
  16392. auto port = svr.bind_to_any_port("localhost");
  16393. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16394. auto se = detail::scope_exit([&] {
  16395. svr.stop();
  16396. t.join();
  16397. ASSERT_FALSE(svr.is_running());
  16398. });
  16399. svr.wait_until_ready();
  16400. {
  16401. std::string data(1024 * 1024 * 2, '&');
  16402. std::stringstream buffer;
  16403. buffer << data;
  16404. SSLClient cli("localhost", port);
  16405. cli.enable_server_certificate_verification(false);
  16406. UploadFormDataItems items{
  16407. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16408. {"hello", "world", "", ""},
  16409. };
  16410. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16412. ASSERT_EQ(StatusCode::OK_200, res->status);
  16413. }
  16414. }
  16415. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16416. std::string data(1024 * 1024 * 2, '&');
  16417. std::stringstream buffer;
  16418. buffer << data;
  16419. Client cli("https://localhost:8080");
  16420. cli.enable_server_certificate_verification(false);
  16421. UploadFormDataItems items{
  16422. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16423. {"hello", "world", "", ""},
  16424. };
  16425. for (const char &c : " \t\r\n") {
  16426. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16427. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16428. ASSERT_FALSE(res);
  16429. }
  16430. }
  16431. TEST(MultipartFormDataTest, AlternateFilename) {
  16432. auto handled = false;
  16433. Server svr;
  16434. svr.Post("/test", [&](const Request &req, Response &res) {
  16435. ASSERT_EQ(2u, req.form.files.size());
  16436. ASSERT_EQ(1u, req.form.fields.size());
  16437. // Test files
  16438. const auto &file1 = req.form.get_file("file1");
  16439. ASSERT_EQ("file1", file1.name);
  16440. ASSERT_EQ("A.txt", file1.filename);
  16441. ASSERT_EQ("text/plain", file1.content_type);
  16442. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16443. const auto &file2 = req.form.get_file("file2");
  16444. ASSERT_EQ("file2", file2.name);
  16445. ASSERT_EQ("a.html", file2.filename);
  16446. ASSERT_EQ("text/html", file2.content_type);
  16447. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16448. file2.content);
  16449. // Test text field
  16450. const auto &text = req.form.get_field("text");
  16451. ASSERT_EQ("text default", text);
  16452. res.set_content("ok", "text/plain");
  16453. handled = true;
  16454. });
  16455. thread t = thread([&] { svr.listen(HOST, PORT); });
  16456. auto se = detail::scope_exit([&] {
  16457. svr.stop();
  16458. t.join();
  16459. ASSERT_FALSE(svr.is_running());
  16460. ASSERT_TRUE(handled);
  16461. });
  16462. svr.wait_until_ready();
  16463. auto req = "POST /test HTTP/1.1\r\n"
  16464. "Host: localhost\r\n"
  16465. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16466. "Content-Length: 399\r\n"
  16467. "\r\n"
  16468. "----------\r\n"
  16469. "Content-Disposition: form-data; name=\"text\"\r\n"
  16470. "\r\n"
  16471. "text default\r\n"
  16472. "----------\r\n"
  16473. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16474. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16475. "Content-Type: text/plain\r\n"
  16476. "\r\n"
  16477. "Content of a.txt.\r\n"
  16478. "\r\n"
  16479. "----------\r\n"
  16480. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16481. "\"a.html\"\r\n"
  16482. "Content-Type: text/html\r\n"
  16483. "\r\n"
  16484. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16485. "\r\n"
  16486. "------------\r\n";
  16487. ASSERT_TRUE(send_request(1, req));
  16488. }
  16489. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16490. auto handled = false;
  16491. Server svr;
  16492. svr.Post("/test", [&](const Request &req, Response &res) {
  16493. // Case-insensitive "utf-8''" prefix with a long value
  16494. const auto &file = req.form.get_file("file1");
  16495. ASSERT_EQ("file1", file.name);
  16496. // 8000 chars exercises both the Content-Disposition parser and the
  16497. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16498. // Prior to the fix, std::regex_match on this header would cause O(N)
  16499. // stack recursion in libstdc++, leading to SIGSEGV.
  16500. std::string expected_filename(8000, 'A');
  16501. ASSERT_EQ(expected_filename, file.filename);
  16502. res.set_content("ok", "text/plain");
  16503. handled = true;
  16504. });
  16505. thread t = thread([&] { svr.listen(HOST, PORT); });
  16506. auto se = detail::scope_exit([&] {
  16507. svr.stop();
  16508. t.join();
  16509. ASSERT_FALSE(svr.is_running());
  16510. ASSERT_TRUE(handled);
  16511. });
  16512. svr.wait_until_ready();
  16513. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16514. // Regression test for GHSA-qq6v-r583-3h69
  16515. std::string long_filename(8000, 'A');
  16516. std::string body = "----------\r\n"
  16517. "Content-Disposition: form-data; name=\"file1\"; "
  16518. "filename*=\"Utf-8''" +
  16519. long_filename +
  16520. "\"\r\n"
  16521. "\r\n"
  16522. "hello\r\n"
  16523. "------------\r\n";
  16524. auto req = "POST /test HTTP/1.1\r\n"
  16525. "Host: localhost\r\n"
  16526. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16527. "Content-Length: " +
  16528. std::to_string(body.size()) + "\r\n\r\n" + body;
  16529. ASSERT_TRUE(send_request(1, req));
  16530. }
  16531. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16532. auto handled = false;
  16533. Server svr;
  16534. svr.Post("/test", [&](const Request &req, Response &) {
  16535. ASSERT_EQ(2u, req.form.fields.size());
  16536. const auto &text1 = req.form.get_field("text1");
  16537. ASSERT_EQ("text1", text1);
  16538. const auto &text2 = req.form.get_field("text2");
  16539. ASSERT_EQ("text2", text2);
  16540. handled = true;
  16541. });
  16542. thread t = thread([&] { svr.listen(HOST, PORT); });
  16543. auto se = detail::scope_exit([&] {
  16544. svr.stop();
  16545. t.join();
  16546. ASSERT_FALSE(svr.is_running());
  16547. ASSERT_TRUE(handled);
  16548. });
  16549. svr.wait_until_ready();
  16550. auto req = "POST /test HTTP/1.1\r\n"
  16551. "Host: localhost\r\n"
  16552. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16553. "Content-Length: 146\r\n"
  16554. "\r\n----------\r\n"
  16555. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16556. "\r\n"
  16557. "text1"
  16558. "\r\n----------\r\n"
  16559. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16560. "\r\n"
  16561. "text2"
  16562. "\r\n------------";
  16563. std::string response;
  16564. ASSERT_TRUE(send_request(1, req, &response));
  16565. ASSERT_EQ("200", response.substr(9, 3));
  16566. }
  16567. TEST(MultipartFormDataTest, ContentLength) {
  16568. auto handled = false;
  16569. Server svr;
  16570. svr.Post("/test", [&](const Request &req, Response &) {
  16571. ASSERT_EQ(2u, req.form.fields.size());
  16572. const auto &text1 = req.form.get_field("text1");
  16573. ASSERT_EQ("text1", text1);
  16574. const auto &text2 = req.form.get_field("text2");
  16575. ASSERT_EQ("text2", text2);
  16576. handled = true;
  16577. });
  16578. thread t = thread([&] { svr.listen(HOST, PORT); });
  16579. auto se = detail::scope_exit([&] {
  16580. svr.stop();
  16581. t.join();
  16582. ASSERT_FALSE(svr.is_running());
  16583. ASSERT_TRUE(handled);
  16584. });
  16585. svr.wait_until_ready();
  16586. auto req = "POST /test HTTP/1.1\r\n"
  16587. "Host: localhost\r\n"
  16588. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16589. "Content-Length: 167\r\n"
  16590. "\r\n----------\r\n"
  16591. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16592. "Content-Length: 5\r\n"
  16593. "\r\n"
  16594. "text1"
  16595. "\r\n----------\r\n"
  16596. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16597. "\r\n"
  16598. "text2"
  16599. "\r\n------------\r\n";
  16600. std::string response;
  16601. ASSERT_TRUE(send_request(1, req, &response));
  16602. ASSERT_EQ("200", response.substr(9, 3));
  16603. }
  16604. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16605. auto handled = false;
  16606. Server svr;
  16607. svr.Post("/test", [&](const Request &req, Response &) {
  16608. ASSERT_EQ(2u, req.form.fields.size());
  16609. const auto &text1 = req.form.get_field("text1");
  16610. ASSERT_EQ("text1", text1);
  16611. // TODO: Add header access for text fields if needed
  16612. const auto &text2 = req.form.get_field("text2");
  16613. ASSERT_EQ("text2", text2);
  16614. // TODO: Header access for text fields needs to be implemented
  16615. // auto &headers = it->second.headers;
  16616. // ASSERT_EQ(3U, headers.size());
  16617. // auto custom_header = headers.find("x-whatever");
  16618. // ASSERT_TRUE(custom_header != headers.end());
  16619. // ASSERT_NE("customvalue", custom_header->second);
  16620. // ASSERT_EQ("CustomValue", custom_header->second);
  16621. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16622. handled = true;
  16623. });
  16624. thread t = thread([&] { svr.listen(HOST, PORT); });
  16625. auto se = detail::scope_exit([&] {
  16626. svr.stop();
  16627. t.join();
  16628. ASSERT_FALSE(svr.is_running());
  16629. ASSERT_TRUE(handled);
  16630. });
  16631. svr.wait_until_ready();
  16632. auto req = "POST /test HTTP/1.1\r\n"
  16633. "Host: localhost\r\n"
  16634. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16635. "Content-Length: 232\r\n"
  16636. "\r\n----------\r\n"
  16637. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16638. "Content-Length: 5\r\n"
  16639. "X-Test: 1\r\n"
  16640. "\r\n"
  16641. "text1"
  16642. "\r\n----------\r\n"
  16643. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16644. "Content-Type: text/plain\r\n"
  16645. "X-Whatever: CustomValue\r\n"
  16646. "\r\n"
  16647. "text2"
  16648. "\r\n------------\r\n"
  16649. "That should be disregarded. Not even read";
  16650. std::string response;
  16651. ASSERT_TRUE(send_request(1, req, &response));
  16652. ASSERT_EQ("200", response.substr(9, 3));
  16653. }
  16654. TEST(MultipartFormDataTest, LargeHeader) {
  16655. auto handled = false;
  16656. Server svr;
  16657. svr.Post("/test", [&](const Request &req, Response &) {
  16658. ASSERT_EQ(1u, req.form.fields.size());
  16659. const auto &text = req.form.get_field("name1");
  16660. ASSERT_EQ("text1", text);
  16661. handled = true;
  16662. });
  16663. thread t = thread([&] { svr.listen(HOST, PORT); });
  16664. auto se = detail::scope_exit([&] {
  16665. svr.stop();
  16666. t.join();
  16667. ASSERT_FALSE(svr.is_running());
  16668. ASSERT_TRUE(handled);
  16669. });
  16670. svr.wait_until_ready();
  16671. auto boundary = std::string("cpp-httplib-multipart-data");
  16672. std::string content = "--" + boundary +
  16673. "\r\n"
  16674. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16675. "\r\n"
  16676. "text1\r\n"
  16677. "--" +
  16678. boundary + "--\r\n";
  16679. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16680. "Host: localhost\r\n"
  16681. "Content-Type: multipart/form-data;boundary=" +
  16682. boundary +
  16683. "\r\n"
  16684. "Content-Length: " +
  16685. std::to_string(content.size()) +
  16686. "\r\n"
  16687. "Dummy-Header: ";
  16688. std::string header_suffix = "\r\n"
  16689. "\r\n";
  16690. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16691. size_t header_dummy_size =
  16692. read_buff_size -
  16693. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16694. auto header_dummy = std::string(header_dummy_size, '@');
  16695. auto req = header_prefix + header_dummy + header_suffix + content;
  16696. std::string response;
  16697. ASSERT_TRUE(send_request(1, req, &response));
  16698. ASSERT_EQ("200", response.substr(9, 3));
  16699. }
  16700. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16701. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16702. // (not chunked Transfer-Encoding) after the streaming refactor.
  16703. auto handled = false;
  16704. Server svr;
  16705. svr.Post("/upload", [&](const Request &req, Response &res) {
  16706. auto cl_it = req.headers.find("Content-Length");
  16707. EXPECT_TRUE(cl_it != req.headers.end());
  16708. auto te_it = req.headers.find("Transfer-Encoding");
  16709. EXPECT_TRUE(te_it == req.headers.end());
  16710. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16711. res.set_content("ok", "text/plain");
  16712. handled = true;
  16713. });
  16714. auto port = svr.bind_to_any_port(HOST);
  16715. auto t = thread([&] { svr.listen_after_bind(); });
  16716. auto se = detail::scope_exit([&] {
  16717. svr.stop();
  16718. t.join();
  16719. ASSERT_FALSE(svr.is_running());
  16720. ASSERT_TRUE(handled);
  16721. });
  16722. svr.wait_until_ready();
  16723. UploadFormDataItems items = {
  16724. {"field1", "hello", "", "text/plain"},
  16725. {"file1", "world", "test.txt", "application/octet-stream"},
  16726. };
  16727. Client cli(HOST, port);
  16728. auto res = cli.Post("/upload", {}, items);
  16729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16730. EXPECT_EQ(StatusCode::OK_200, res->status);
  16731. }
  16732. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16733. // Verify that make_multipart_content_provider coalesces many small segments
  16734. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16735. constexpr size_t kItemCount = 1000;
  16736. UploadFormDataItems items;
  16737. items.reserve(kItemCount);
  16738. for (size_t i = 0; i < kItemCount; i++) {
  16739. items.push_back(
  16740. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16741. }
  16742. const std::string boundary = "----test-boundary";
  16743. auto content_length = detail::get_multipart_content_length(items, boundary);
  16744. auto provider = detail::make_multipart_content_provider(items, boundary);
  16745. // Drive the provider the same way write_content_with_progress does
  16746. size_t write_count = 0;
  16747. size_t total_bytes = 0;
  16748. DataSink sink;
  16749. size_t offset = 0;
  16750. sink.write = [&](const char *d, size_t l) -> bool {
  16751. (void)d;
  16752. write_count++;
  16753. total_bytes += l;
  16754. offset += l;
  16755. return true;
  16756. };
  16757. sink.is_writable = []() -> bool { return true; };
  16758. while (offset < content_length) {
  16759. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16760. }
  16761. EXPECT_EQ(content_length, total_bytes);
  16762. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16763. // With buffering into 64KB blocks, write_count should be much smaller.
  16764. auto segment_count = 3 * kItemCount + 1;
  16765. EXPECT_LT(write_count, segment_count / 10);
  16766. }
  16767. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16768. // Integration test: send many UploadFormDataItems and verify the server
  16769. // receives all of them correctly (#2410).
  16770. constexpr size_t kItemCount = 500;
  16771. auto handled = false;
  16772. Server svr;
  16773. svr.Post("/upload", [&](const Request &req, Response &res) {
  16774. EXPECT_EQ(kItemCount, req.form.fields.size());
  16775. for (size_t i = 0; i < kItemCount; i++) {
  16776. auto key = "field" + std::to_string(i);
  16777. auto val = "value" + std::to_string(i);
  16778. auto it = req.form.fields.find(key);
  16779. if (it != req.form.fields.end()) {
  16780. EXPECT_EQ(val, it->second.content);
  16781. } else {
  16782. ADD_FAILURE() << "Missing field: " << key;
  16783. }
  16784. }
  16785. res.set_content("ok", "text/plain");
  16786. handled = true;
  16787. });
  16788. auto port = svr.bind_to_any_port(HOST);
  16789. auto t = thread([&] { svr.listen_after_bind(); });
  16790. auto se = detail::scope_exit([&] {
  16791. svr.stop();
  16792. t.join();
  16793. ASSERT_FALSE(svr.is_running());
  16794. ASSERT_TRUE(handled);
  16795. });
  16796. svr.wait_until_ready();
  16797. UploadFormDataItems items;
  16798. items.reserve(kItemCount);
  16799. for (size_t i = 0; i < kItemCount; i++) {
  16800. items.push_back(
  16801. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16802. }
  16803. Client cli(HOST, port);
  16804. auto res = cli.Post("/upload", items);
  16805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16806. EXPECT_EQ(StatusCode::OK_200, res->status);
  16807. }
  16808. TEST(MultipartFormDataTest, MakeFileProvider) {
  16809. // Verify make_file_provider sends a file's contents correctly.
  16810. const std::string file_content(4096, 'Z');
  16811. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16812. {
  16813. std::ofstream ofs(tmp_path, std::ios::binary);
  16814. ofs.write(file_content.data(),
  16815. static_cast<std::streamsize>(file_content.size()));
  16816. }
  16817. auto handled = false;
  16818. Server svr;
  16819. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16820. const ContentReader &content_reader) {
  16821. ASSERT_TRUE(req.is_multipart_form_data());
  16822. std::vector<FormData> items;
  16823. content_reader(
  16824. [&](const FormData &file) {
  16825. items.push_back(file);
  16826. return true;
  16827. },
  16828. [&](const char *data, size_t data_length) {
  16829. items.back().content.append(data, data_length);
  16830. return true;
  16831. });
  16832. ASSERT_EQ(1u, items.size());
  16833. EXPECT_EQ("myfile", items[0].name);
  16834. EXPECT_EQ("data.bin", items[0].filename);
  16835. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16836. EXPECT_EQ(file_content, items[0].content);
  16837. handled = true;
  16838. });
  16839. auto port = svr.bind_to_any_port(HOST);
  16840. auto t = thread([&] { svr.listen_after_bind(); });
  16841. auto se = detail::scope_exit([&] {
  16842. svr.stop();
  16843. t.join();
  16844. ASSERT_FALSE(svr.is_running());
  16845. ASSERT_TRUE(handled);
  16846. std::remove(tmp_path.c_str());
  16847. });
  16848. svr.wait_until_ready();
  16849. FormDataProviderItems providers;
  16850. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16851. "application/octet-stream"));
  16852. Client cli(HOST, port);
  16853. auto res = cli.Post("/upload", {}, {}, providers);
  16854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16855. EXPECT_EQ(StatusCode::OK_200, res->status);
  16856. }
  16857. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16858. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16859. // (100) headers is rejected with a 400 Bad Request response.
  16860. Server svr;
  16861. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16862. res.set_content("ok", "text/plain");
  16863. });
  16864. thread t = thread([&] { svr.listen(HOST, PORT); });
  16865. auto se = detail::scope_exit([&] {
  16866. svr.stop();
  16867. t.join();
  16868. ASSERT_FALSE(svr.is_running());
  16869. });
  16870. svr.wait_until_ready();
  16871. // Build a multipart part with 101 custom headers (exceeding
  16872. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16873. std::stringstream body;
  16874. body << "--simpleboundary\r\n"
  16875. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16876. for (int i = 0; i < 101; i++) {
  16877. body << "X-Custom-Header-" << i << ": value\r\n";
  16878. }
  16879. body << "\r\n"
  16880. << "value1\r\n"
  16881. << "--simpleboundary--\r\n";
  16882. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16883. Client cli(HOST, PORT);
  16884. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16886. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16887. }
  16888. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16889. // A body that never contains the declared boundary must not be accumulated
  16890. // while the parser waits for it. Buffering it would also make every read
  16891. // rescan everything seen so far, which is quadratic in the body size.
  16892. Server svr;
  16893. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16894. res.set_content("ok", "text/plain");
  16895. });
  16896. auto port = svr.bind_to_any_port(HOST);
  16897. thread t = thread([&] { svr.listen_after_bind(); });
  16898. auto se = detail::scope_exit([&] {
  16899. svr.stop();
  16900. t.join();
  16901. ASSERT_FALSE(svr.is_running());
  16902. });
  16903. svr.wait_until_ready();
  16904. Client cli(HOST, port);
  16905. cli.set_read_timeout(60, 0);
  16906. cli.set_write_timeout(60, 0);
  16907. // '-' is the worst case: it matches the first character of the boundary, so
  16908. // every position has to be checked against it.
  16909. auto post_dashes = [&](size_t size) {
  16910. const std::string body(size, '-');
  16911. auto start = std::chrono::steady_clock::now();
  16912. auto res =
  16913. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16914. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16915. std::chrono::steady_clock::now() - start)
  16916. .count();
  16917. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16918. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16919. return ms;
  16920. };
  16921. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16922. // Windows.
  16923. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16924. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16925. // Comparing the two sizes rather than checking an absolute duration keeps
  16926. // this meaningful across build types and CI load, both of which move the
  16927. // absolute numbers by more than an order of magnitude. Four times the bytes
  16928. // costs about four times the time when parsing is linear, and about sixteen
  16929. // times when the body is buffered and rescanned.
  16930. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16931. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16932. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16933. << "ms, which suggests the body is being buffered and rescanned";
  16934. }
  16935. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16936. // A boundary can only be followed by CRLF or by "--", so anything else is
  16937. // malformed no matter what comes next. The parser must say so right away
  16938. // instead of buffering the rest of the declared body.
  16939. Server svr;
  16940. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16941. res.set_content("ok", "text/plain");
  16942. });
  16943. auto port = svr.bind_to_any_port(HOST);
  16944. thread t = thread([&] { svr.listen_after_bind(); });
  16945. auto se = detail::scope_exit([&] {
  16946. svr.stop();
  16947. t.join();
  16948. ASSERT_FALSE(svr.is_running());
  16949. });
  16950. svr.wait_until_ready();
  16951. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16952. // buffers instead of failing would still be waiting for the remaining bytes.
  16953. const std::string body = "--zzzz\r\n"
  16954. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16955. "\r\n"
  16956. "text1"
  16957. "\r\n--zzzzXX";
  16958. const std::string req = "POST /post HTTP/1.1\r\n"
  16959. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16960. "Content-Length: 1048576\r\n"
  16961. "\r\n" +
  16962. body;
  16963. std::string response;
  16964. ASSERT_TRUE(send_request(3, req, &response, port));
  16965. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16966. EXPECT_EQ("400", response.substr(9, 3));
  16967. }
  16968. // Posts a multipart body split into two writes, so that the server sees the
  16969. // split at whatever offset the caller chose, and expects the single "text1"
  16970. // field to come through.
  16971. static void expect_split_multipart_ok(const std::string &body1,
  16972. const std::string &body2) {
  16973. auto handled = false;
  16974. Server svr;
  16975. svr.Post("/post", [&](const Request &req, Response &) {
  16976. EXPECT_EQ(1u, req.form.fields.size());
  16977. EXPECT_EQ("text1", req.form.get_field("text1"));
  16978. handled = true;
  16979. });
  16980. auto port = svr.bind_to_any_port(HOST);
  16981. thread t = thread([&] { svr.listen_after_bind(); });
  16982. auto se = detail::scope_exit([&] {
  16983. svr.stop();
  16984. t.join();
  16985. ASSERT_FALSE(svr.is_running());
  16986. ASSERT_TRUE(handled);
  16987. });
  16988. svr.wait_until_ready();
  16989. // "Connection: close" makes the server close once it has answered, so the
  16990. // response drain ends immediately instead of idling until the read timeout.
  16991. const std::string head =
  16992. "POST /post HTTP/1.1\r\n"
  16993. "Host: localhost\r\n"
  16994. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16995. "Connection: close\r\n"
  16996. "Content-Length: " +
  16997. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16998. std::string response;
  16999. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17000. ASSERT_GE(response.size(), 12u) << "no response";
  17001. EXPECT_EQ("200", response.substr(9, 3));
  17002. }
  17003. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17004. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17005. // ignored, including when it does not arrive in the same read as the
  17006. // close-delimiter itself.
  17007. expect_split_multipart_ok("--zzzz\r\n"
  17008. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17009. "\r\n"
  17010. "text1"
  17011. "\r\n--zzzz--",
  17012. "\r\nthis epilogue must be ignored\r\n");
  17013. }
  17014. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17015. // The initial boundary may be preceded by a preamble of any length and may
  17016. // straddle a read boundary. Discarding data while waiting for it must not
  17017. // throw away a partial boundary sitting at the end of the buffer.
  17018. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17019. "zz\r\n"
  17020. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17021. "\r\n"
  17022. "text1"
  17023. "\r\n--zzzz--\r\n");
  17024. }
  17025. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17026. // The received boundary was only checked for being non-empty, so it could be
  17027. // as long as a header is allowed to be. The parser scans the body for
  17028. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17029. // costs a nearly full comparison at nearly every position, making the
  17030. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17031. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17032. Server svr;
  17033. svr.Post("/post", [](const Request &req, Response &res) {
  17034. EXPECT_EQ(1u, req.form.fields.size());
  17035. EXPECT_EQ("text1", req.form.get_field("text1"));
  17036. res.set_content("ok", "text/plain");
  17037. });
  17038. auto port = svr.bind_to_any_port(HOST);
  17039. thread t = thread([&] { svr.listen_after_bind(); });
  17040. auto se = detail::scope_exit([&] {
  17041. svr.stop();
  17042. t.join();
  17043. ASSERT_FALSE(svr.is_running());
  17044. });
  17045. svr.wait_until_ready();
  17046. Client cli(HOST, port);
  17047. auto post_with_boundary_of_length = [&](size_t len) {
  17048. const std::string boundary(len, 'a');
  17049. const std::string body =
  17050. "--" + boundary +
  17051. "\r\n"
  17052. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17053. "\r\n"
  17054. "text1"
  17055. "\r\n--" +
  17056. boundary + "--\r\n";
  17057. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17058. };
  17059. auto res = post_with_boundary_of_length(70);
  17060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17061. EXPECT_EQ(StatusCode::OK_200, res->status);
  17062. res = post_with_boundary_of_length(71);
  17063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17064. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17065. }
  17066. TEST(MakeFileBodyTest, Basic) {
  17067. const std::string file_content(4096, 'Z');
  17068. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17069. {
  17070. std::ofstream ofs(tmp_path, std::ios::binary);
  17071. ofs.write(file_content.data(),
  17072. static_cast<std::streamsize>(file_content.size()));
  17073. }
  17074. auto handled = false;
  17075. Server svr;
  17076. svr.Post("/upload", [&](const Request &req, Response &res) {
  17077. EXPECT_EQ(file_content, req.body);
  17078. handled = true;
  17079. res.status = StatusCode::OK_200;
  17080. });
  17081. auto port = svr.bind_to_any_port(HOST);
  17082. auto t = thread([&] { svr.listen_after_bind(); });
  17083. auto se = detail::scope_exit([&] {
  17084. svr.stop();
  17085. t.join();
  17086. ASSERT_FALSE(svr.is_running());
  17087. ASSERT_TRUE(handled);
  17088. std::remove(tmp_path.c_str());
  17089. });
  17090. svr.wait_until_ready();
  17091. auto fb = make_file_body(tmp_path);
  17092. ASSERT_GT(fb.first, 0u);
  17093. Client cli(HOST, port);
  17094. auto res =
  17095. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17097. EXPECT_EQ(StatusCode::OK_200, res->status);
  17098. }
  17099. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17100. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17101. {
  17102. std::ofstream ofs(path, std::ios::binary);
  17103. const std::string content(100, 'A');
  17104. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17105. }
  17106. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17107. auto body = make_file_body(path);
  17108. ASSERT_EQ(100u, body.first);
  17109. ASSERT_TRUE(static_cast<bool>(body.second));
  17110. // Rewritten shorter after its length was measured - and, on a server, after
  17111. // that length has already gone out as Content-Length.
  17112. {
  17113. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17114. const std::string content(10, 'A');
  17115. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17116. }
  17117. std::string written;
  17118. DataSink sink;
  17119. sink.write = [&](const char *d, size_t l) {
  17120. written.append(d, l);
  17121. return true;
  17122. };
  17123. // The provider has to report failure. write_content_with_progress() advances
  17124. // its offset only by what was written, so a provider that returns true
  17125. // without completing the length it promised is called again straight away,
  17126. // and again.
  17127. EXPECT_FALSE(body.second(0, body.first, sink));
  17128. EXPECT_EQ(std::string(10, 'A'), written);
  17129. }
  17130. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17131. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17132. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17133. {
  17134. std::ofstream ofs(path, std::ios::binary);
  17135. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17136. }
  17137. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17138. auto body = make_file_body(path);
  17139. ASSERT_EQ(content.size(), body.first);
  17140. ASSERT_TRUE(static_cast<bool>(body.second));
  17141. std::string written;
  17142. DataSink sink;
  17143. sink.write = [&](const char *d, size_t l) {
  17144. written.append(d, l);
  17145. return true;
  17146. };
  17147. EXPECT_TRUE(body.second(0, body.first, sink));
  17148. EXPECT_EQ(content, written);
  17149. }
  17150. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17151. static constexpr unsigned int number_of_tasks{1000000};
  17152. std::atomic_uint count{0};
  17153. std::unique_ptr<TaskQueue> task_queue{
  17154. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17155. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17156. auto queued = task_queue->enqueue(
  17157. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17158. EXPECT_TRUE(queued);
  17159. }
  17160. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17161. task_queue->shutdown();
  17162. #else
  17163. EXPECT_NO_THROW(task_queue->shutdown());
  17164. #endif
  17165. EXPECT_EQ(number_of_tasks, count.load());
  17166. }
  17167. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17168. static constexpr unsigned int number_of_tasks{1000000};
  17169. static constexpr unsigned int qlimit{2};
  17170. unsigned int queued_count{0};
  17171. std::atomic_uint count{0};
  17172. std::unique_ptr<TaskQueue> task_queue{
  17173. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17174. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17175. if (task_queue->enqueue(
  17176. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17177. queued_count++;
  17178. }
  17179. }
  17180. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17181. task_queue->shutdown();
  17182. #else
  17183. EXPECT_NO_THROW(task_queue->shutdown());
  17184. #endif
  17185. EXPECT_EQ(queued_count, count.load());
  17186. EXPECT_TRUE(queued_count <= number_of_tasks);
  17187. EXPECT_TRUE(queued_count >= qlimit);
  17188. }
  17189. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17190. // Use a short idle timeout so a dynamic thread spawns, times out and
  17191. // exits during the test, and the pool keeps working afterwards.
  17192. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17193. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17194. /*idle_timeout_sec=*/1}};
  17195. std::atomic_uint count{0};
  17196. std::condition_variable cv;
  17197. std::mutex mtx;
  17198. bool release = false;
  17199. // Block the base thread so the second task spawns a dynamic thread.
  17200. EXPECT_TRUE(task_queue->enqueue([&] {
  17201. std::unique_lock<std::mutex> lock(mtx);
  17202. while (!release) {
  17203. cv.wait(lock);
  17204. }
  17205. count++;
  17206. }));
  17207. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17208. // Let the dynamic thread finish its task and exceed the idle timeout.
  17209. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17210. {
  17211. std::unique_lock<std::mutex> lock(mtx);
  17212. release = true;
  17213. }
  17214. cv.notify_all();
  17215. // The pool must still accept and run tasks after the dynamic thread exited.
  17216. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17217. task_queue->shutdown();
  17218. EXPECT_EQ(3u, count.load());
  17219. }
  17220. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17221. static constexpr size_t number_of_tasks{32};
  17222. std::unique_ptr<TaskQueue> task_queue{
  17223. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17224. // Let the base threads go idle so the burst below finds them waiting.
  17225. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17226. std::mutex mtx;
  17227. std::condition_variable cv;
  17228. size_t running = 0;
  17229. bool release = false;
  17230. for (size_t i = 0; i < number_of_tasks; i++) {
  17231. EXPECT_TRUE(task_queue->enqueue([&] {
  17232. std::unique_lock<std::mutex> lock(mtx);
  17233. running++;
  17234. cv.notify_all();
  17235. cv.wait(lock, [&] { return release; });
  17236. }));
  17237. }
  17238. {
  17239. std::unique_lock<std::mutex> lock(mtx);
  17240. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17241. [&] { return running == number_of_tasks; }));
  17242. release = true;
  17243. }
  17244. cv.notify_all();
  17245. task_queue->shutdown();
  17246. }
  17247. TEST(TaskQueueTest, MaxQueuedRequests) {
  17248. static constexpr unsigned int qlimit{3};
  17249. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17250. std::condition_variable sem_cv;
  17251. std::mutex sem_mtx;
  17252. int credits = 0;
  17253. bool queued;
  17254. /* Fill up the queue with tasks that will block until we give them credits to
  17255. * complete. */
  17256. for (unsigned int n = 0; n <= qlimit;) {
  17257. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17258. std::unique_lock<std::mutex> lock(sem_mtx);
  17259. while (credits <= 0) {
  17260. sem_cv.wait(lock);
  17261. }
  17262. /* Consume the credit and signal the test code if they are all gone. */
  17263. if (--credits == 0) { sem_cv.notify_one(); }
  17264. });
  17265. if (n < qlimit) {
  17266. /* The first qlimit enqueues must succeed. */
  17267. EXPECT_TRUE(queued);
  17268. } else {
  17269. /* The last one will succeed only when the worker thread
  17270. * starts and dequeues the first blocking task. Although
  17271. * not necessary for the correctness of this test, we sleep for
  17272. * a short while to avoid busy waiting. */
  17273. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17274. }
  17275. if (queued) { n++; }
  17276. }
  17277. /* Further enqueues must fail since the queue is full. */
  17278. for (auto i = 0; i < 4; i++) {
  17279. queued = task_queue->enqueue([] {});
  17280. EXPECT_FALSE(queued);
  17281. }
  17282. /* Give the credits to allow the previous tasks to complete. */
  17283. {
  17284. std::unique_lock<std::mutex> lock(sem_mtx);
  17285. credits += qlimit + 1;
  17286. }
  17287. sem_cv.notify_all();
  17288. /* Wait for all the credits to be consumed. */
  17289. {
  17290. std::unique_lock<std::mutex> lock(sem_mtx);
  17291. while (credits > 0) {
  17292. sem_cv.wait(lock);
  17293. }
  17294. }
  17295. /* Check that we are able again to enqueue at least qlimit tasks. */
  17296. for (unsigned int i = 0; i < qlimit; i++) {
  17297. queued = task_queue->enqueue([] {});
  17298. EXPECT_TRUE(queued);
  17299. }
  17300. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17301. task_queue->shutdown();
  17302. #else
  17303. EXPECT_NO_THROW(task_queue->shutdown());
  17304. #endif
  17305. }
  17306. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17307. Server svr;
  17308. std::string method;
  17309. std::string body;
  17310. auto has_content_length = false;
  17311. auto has_transfer_encoding = false;
  17312. std::atomic<int> bad_requests{0};
  17313. // Leftover body bytes get parsed as a malformed request and answered with
  17314. // 400
  17315. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17316. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17317. });
  17318. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17319. res.set_redirect("/down", StatusCode::SeeOther_303);
  17320. });
  17321. svr.Get("/down", [&](const Request &req, Response &res) {
  17322. method = req.method;
  17323. body = req.body;
  17324. has_content_length = req.has_header("Content-Length");
  17325. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17326. res.set_content("ok", "text/plain");
  17327. });
  17328. auto port = svr.bind_to_any_port(HOST);
  17329. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17330. auto se = detail::scope_exit([&] {
  17331. svr.stop();
  17332. thread.join();
  17333. ASSERT_FALSE(svr.is_running());
  17334. });
  17335. svr.wait_until_ready();
  17336. const std::string payload = "SECRET-BODY";
  17337. auto check = [&](Client &cli, const Result &res) {
  17338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17339. EXPECT_EQ(StatusCode::OK_200, res->status);
  17340. EXPECT_EQ("ok", res->body);
  17341. EXPECT_EQ("GET", method);
  17342. EXPECT_TRUE(body.empty());
  17343. EXPECT_FALSE(has_content_length);
  17344. EXPECT_FALSE(has_transfer_encoding);
  17345. // Nothing of the original body may be left on the connection
  17346. auto res2 = cli.Get("/down");
  17347. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17348. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17349. EXPECT_EQ("ok", res2->body);
  17350. EXPECT_EQ(0, bad_requests);
  17351. };
  17352. // With content length
  17353. {
  17354. Client cli(HOST, port);
  17355. cli.set_keep_alive(true);
  17356. cli.set_follow_location(true);
  17357. auto res = cli.Post(
  17358. "/up", payload.size(),
  17359. [&](size_t offset, size_t length, DataSink &sink) {
  17360. return sink.write(payload.data() + offset, length);
  17361. },
  17362. "text/plain");
  17363. check(cli, res);
  17364. }
  17365. // Without content length (chunked)
  17366. {
  17367. Client cli(HOST, port);
  17368. cli.set_keep_alive(true);
  17369. cli.set_follow_location(true);
  17370. auto res = cli.Post(
  17371. "/up",
  17372. [&](size_t /*offset*/, DataSink &sink) {
  17373. sink.write(payload.data(), payload.size());
  17374. sink.done();
  17375. return true;
  17376. },
  17377. "text/plain");
  17378. check(cli, res);
  17379. }
  17380. }
  17381. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17382. Server svr;
  17383. std::string target;
  17384. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17385. // Echo the still-encoded name back in the Location
  17386. const std::string prefix = "/start/";
  17387. res.status = StatusCode::Found_302;
  17388. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17389. });
  17390. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17391. target = req.target;
  17392. res.set_content("ok", "text/plain");
  17393. });
  17394. auto port = svr.bind_to_any_port(HOST);
  17395. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17396. auto se = detail::scope_exit([&] {
  17397. svr.stop();
  17398. thread.join();
  17399. ASSERT_FALSE(svr.is_running());
  17400. });
  17401. svr.wait_until_ready();
  17402. // Decoding the Location path would turn the first four into a path
  17403. // separator, a query delimiter, a fragment delimiter and a different
  17404. // percent-encoded octet. The rest must keep reaching the server as they are.
  17405. const std::vector<std::string> names = {
  17406. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17407. };
  17408. for (auto path_encode : {true, false}) {
  17409. Client cli(HOST, port);
  17410. cli.set_follow_location(true);
  17411. cli.set_path_encode(path_encode);
  17412. for (const auto &name : names) {
  17413. target.clear();
  17414. auto res = cli.Get("/start/" + name);
  17415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17416. EXPECT_EQ(StatusCode::OK_200, res->status);
  17417. EXPECT_EQ("/dest/" + name, target);
  17418. }
  17419. }
  17420. }
  17421. TEST(RedirectTest, NotModifiedIsReturned) {
  17422. Server svr;
  17423. svr.Get("/cached", [](const Request &, Response &res) {
  17424. res.status = StatusCode::NotModified_304;
  17425. });
  17426. auto port = svr.bind_to_any_port(HOST);
  17427. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17428. auto se = detail::scope_exit([&] {
  17429. svr.stop();
  17430. thread.join();
  17431. ASSERT_FALSE(svr.is_running());
  17432. });
  17433. svr.wait_until_ready();
  17434. Client cli(HOST, port);
  17435. cli.set_follow_location(true);
  17436. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17438. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17439. }
  17440. TEST(RedirectTest, NoLocationIsReturned) {
  17441. Server svr;
  17442. svr.Get("/no-location", [](const Request &, Response &res) {
  17443. res.status = StatusCode::Found_302;
  17444. res.set_content("no location", "text/plain");
  17445. });
  17446. auto port = svr.bind_to_any_port(HOST);
  17447. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17448. auto se = detail::scope_exit([&] {
  17449. svr.stop();
  17450. thread.join();
  17451. ASSERT_FALSE(svr.is_running());
  17452. });
  17453. svr.wait_until_ready();
  17454. Client cli(HOST, port);
  17455. cli.set_follow_location(true);
  17456. auto res = cli.Get("/no-location");
  17457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17458. EXPECT_EQ(StatusCode::Found_302, res->status);
  17459. EXPECT_EQ("no location", res->body);
  17460. // The callbacks see the body of the response that is returned
  17461. auto handler_called = false;
  17462. auto progress_called = false;
  17463. std::string body;
  17464. auto res2 = cli.Get(
  17465. "/no-location",
  17466. [&](const Response &) {
  17467. handler_called = true;
  17468. return true;
  17469. },
  17470. [&](const char *data, size_t data_length) {
  17471. body.append(data, data_length);
  17472. return true;
  17473. },
  17474. [&](size_t, size_t) {
  17475. progress_called = true;
  17476. return true;
  17477. });
  17478. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17479. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17480. EXPECT_TRUE(handler_called);
  17481. EXPECT_TRUE(progress_called);
  17482. EXPECT_EQ("no location", body);
  17483. }
  17484. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17485. Server svr;
  17486. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17487. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17488. });
  17489. svr.Get("/hello", [](const Request &req, Response &res) {
  17490. res.set_content(req.get_param_value("key"), "text/plain");
  17491. });
  17492. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17493. auto se = detail::scope_exit([&] {
  17494. svr.stop();
  17495. thread.join();
  17496. ASSERT_FALSE(svr.is_running());
  17497. });
  17498. svr.wait_until_ready();
  17499. {
  17500. Client cli(HOST, PORT);
  17501. cli.set_follow_location(true);
  17502. auto res = cli.Get("/");
  17503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17504. EXPECT_EQ(StatusCode::OK_200, res->status);
  17505. EXPECT_EQ("val&key2=val2", res->body);
  17506. }
  17507. }
  17508. #endif
  17509. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17510. Server svr;
  17511. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17512. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17513. });
  17514. svr.Get("/hello", [](const Request &req, Response &res) {
  17515. res.set_content(req.get_param_value("key"), "text/plain");
  17516. });
  17517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17518. auto se = detail::scope_exit([&] {
  17519. svr.stop();
  17520. thread.join();
  17521. ASSERT_FALSE(svr.is_running());
  17522. });
  17523. svr.wait_until_ready();
  17524. {
  17525. Client cli(HOST, PORT);
  17526. cli.set_follow_location(true);
  17527. auto res = cli.Get("/");
  17528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17529. EXPECT_EQ(StatusCode::OK_200, res->status);
  17530. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17531. }
  17532. }
  17533. TEST(RedirectTest, RedirectWithPlusInPath) {
  17534. Server svr;
  17535. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17536. res.set_redirect("/a+b");
  17537. });
  17538. // Route pattern uses regex; escape + as \\+
  17539. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17540. res.set_content(req.path, "text/plain");
  17541. });
  17542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17543. auto se = detail::scope_exit([&] {
  17544. svr.stop();
  17545. thread.join();
  17546. ASSERT_FALSE(svr.is_running());
  17547. });
  17548. svr.wait_until_ready();
  17549. {
  17550. Client cli(HOST, PORT);
  17551. cli.set_follow_location(true);
  17552. auto res = cli.Get("/");
  17553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17554. EXPECT_EQ(StatusCode::OK_200, res->status);
  17555. EXPECT_EQ("/a+b", res->body);
  17556. }
  17557. }
  17558. TEST(RedirectTest, ResolveRelativeLocation) {
  17559. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17560. const std::vector<std::pair<std::string, std::string>> cases = {
  17561. {"g", "/b/c/g"},
  17562. {"./g", "/b/c/g"},
  17563. {"g/", "/b/c/g/"},
  17564. {"?y", "/b/c/d;p?y"},
  17565. {"g?y", "/b/c/g?y"},
  17566. {"#s", "/b/c/d;p?q#s"},
  17567. {"g#s", "/b/c/g#s"},
  17568. {"g?y#s", "/b/c/g?y#s"},
  17569. {";x", "/b/c/;x"},
  17570. {"g;x", "/b/c/g;x"},
  17571. {".", "/b/c/"},
  17572. {"./", "/b/c/"},
  17573. {"..", "/b/"},
  17574. {"../", "/b/"},
  17575. {"../g", "/b/g"},
  17576. {"../..", "/"},
  17577. {"../../", "/"},
  17578. {"../../g", "/g"},
  17579. {"../../../g", "/g"},
  17580. {"g.", "/b/c/g."},
  17581. {".g", "/b/c/.g"},
  17582. {"g..", "/b/c/g.."},
  17583. {"..g", "/b/c/..g"},
  17584. {"./../g", "/b/g"},
  17585. {"./g/.", "/b/c/g/"},
  17586. {"g/./h", "/b/c/g/h"},
  17587. {"g/../h", "/b/c/h"},
  17588. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17589. {"g;x=1/../y", "/b/c/y"},
  17590. {"g?y/./x", "/b/c/g?y/./x"},
  17591. {"g#s/../x", "/b/c/g#s/../x"},
  17592. // Not relative-path references, so left for parse_url.
  17593. {"/g", "/g"},
  17594. {"//g", "//g"},
  17595. {"http://g/x", "http://g/x"},
  17596. {"g:h", "g:h"},
  17597. };
  17598. for (const auto &c : cases) {
  17599. EXPECT_EQ(c.second,
  17600. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17601. << c.first;
  17602. }
  17603. // A result starting with "//" is still a path, not a network-path reference
  17604. EXPECT_EQ("/.//g",
  17605. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  17606. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  17607. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  17608. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  17609. }
  17610. TEST(RedirectTest, RemoveDotSegments) {
  17611. // RFC 3986 section 5.2.4
  17612. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17613. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17614. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17615. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17616. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17617. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17618. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17619. }
  17620. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17621. Server svr;
  17622. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17623. res.set_redirect("/dir/../target?x=1");
  17624. });
  17625. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17626. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17627. "/dir/./../target");
  17628. });
  17629. svr.Get("/target", [](const Request &req, Response &res) {
  17630. res.set_content(req.path, "text/plain");
  17631. });
  17632. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17633. auto se = detail::scope_exit([&] {
  17634. svr.stop();
  17635. th.join();
  17636. ASSERT_FALSE(svr.is_running());
  17637. });
  17638. svr.wait_until_ready();
  17639. Client cli("localhost", PORT);
  17640. cli.set_follow_location(true);
  17641. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17642. auto res = cli.Get(path);
  17643. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17644. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17645. EXPECT_EQ("/target", res->body) << path;
  17646. }
  17647. }
  17648. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17649. Server svr;
  17650. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17651. res.set_redirect(req.get_param_value("to"));
  17652. });
  17653. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17654. res.set_content(req.target, "text/plain");
  17655. });
  17656. svr.Get("/other", [](const Request &req, Response &res) {
  17657. res.set_content(req.target, "text/plain");
  17658. });
  17659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17660. auto se = detail::scope_exit([&] {
  17661. svr.stop();
  17662. thread.join();
  17663. ASSERT_FALSE(svr.is_running());
  17664. });
  17665. svr.wait_until_ready();
  17666. const std::vector<std::pair<std::string, std::string>> cases = {
  17667. {"next", "/dir/next"},
  17668. {"./next?x=1", "/dir/next?x=1"},
  17669. {"../other", "/other"},
  17670. };
  17671. for (const auto &c : cases) {
  17672. Client cli(HOST, PORT);
  17673. cli.set_follow_location(true);
  17674. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17675. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17676. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17677. EXPECT_EQ(c.second, res->body) << c.first;
  17678. }
  17679. }
  17680. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  17681. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  17682. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  17683. Server other;
  17684. std::atomic<int> other_hits{0};
  17685. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  17686. other_hits++;
  17687. res.set_content("other", "text/plain");
  17688. });
  17689. auto other_port = other.bind_to_any_port("127.0.0.1");
  17690. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  17691. Server svr;
  17692. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17693. res.set_redirect(req.get_param_value("to"));
  17694. });
  17695. svr.Get(".*", [](const Request &req, Response &res) {
  17696. res.set_content(req.path, "text/plain");
  17697. });
  17698. auto port = svr.bind_to_any_port(HOST);
  17699. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17700. auto se = detail::scope_exit([&] {
  17701. svr.stop();
  17702. thread.join();
  17703. other.stop();
  17704. other_thread.join();
  17705. ASSERT_FALSE(svr.is_running());
  17706. ASSERT_FALSE(other.is_running());
  17707. });
  17708. svr.wait_until_ready();
  17709. other.wait_until_ready();
  17710. auto authority = "127.0.0.1:" + std::to_string(other_port);
  17711. for (const auto &to :
  17712. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  17713. Client cli(HOST, port);
  17714. cli.set_follow_location(true);
  17715. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  17716. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  17717. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  17718. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  17719. }
  17720. EXPECT_EQ(0, other_hits.load());
  17721. }
  17722. #ifdef CPPHTTPLIB_SSL_ENABLED
  17723. TEST(RedirectTest, Issue2185_Online) {
  17724. SSLClient client("github.com");
  17725. client.set_follow_location(true);
  17726. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17727. "Coollab-Windows.zip");
  17728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17729. EXPECT_EQ(StatusCode::OK_200, res->status);
  17730. EXPECT_EQ(9920427U, res->body.size());
  17731. }
  17732. #endif
  17733. TEST(VulnerabilityTest, CRLFInjection) {
  17734. Server svr;
  17735. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17736. res.set_content("Hello 1", "text/plain");
  17737. });
  17738. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17739. res.set_content("Hello 2", "text/plain");
  17740. });
  17741. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17742. res.set_content("Hello 3", "text/plain");
  17743. });
  17744. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17745. res.set_content("Hello 4", "text/plain");
  17746. });
  17747. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17748. for (const auto &x : req.headers) {
  17749. auto key = x.first;
  17750. EXPECT_STRNE("evil", key.c_str());
  17751. }
  17752. });
  17753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17754. auto se = detail::scope_exit([&] {
  17755. svr.stop();
  17756. thread.join();
  17757. ASSERT_FALSE(svr.is_running());
  17758. });
  17759. svr.wait_until_ready();
  17760. {
  17761. Client cli(HOST, PORT);
  17762. cli.Post("/test1", "A=B",
  17763. "application/x-www-form-urlencoded\r\nevil: hello1");
  17764. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17765. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17766. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17767. }
  17768. }
  17769. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17770. auto server_thread = std::thread([] {
  17771. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17772. default_socket_options(srv);
  17773. sockaddr_in addr{};
  17774. addr.sin_family = AF_INET;
  17775. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17776. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17777. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17778. ::listen(srv, 1);
  17779. sockaddr_in cli_addr{};
  17780. socklen_t cli_len = sizeof(cli_addr);
  17781. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17782. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17783. std::string buf_all;
  17784. char buf[2048];
  17785. ssize_t n;
  17786. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17787. buf_all.append(buf, static_cast<size_t>(n));
  17788. size_t pos;
  17789. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17790. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17791. auto e = request_block.find("\r\n");
  17792. if (e != std::string::npos) {
  17793. auto request_line = request_block.substr(0, e);
  17794. std::string msg =
  17795. "CRLF injection detected in request line: '" + request_line + "'";
  17796. EXPECT_FALSE(true) << msg;
  17797. }
  17798. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17799. ::send(cli,
  17800. #ifdef _WIN32
  17801. static_cast<const char *>(resp.c_str()),
  17802. static_cast<int>(resp.size()),
  17803. #else
  17804. resp.c_str(), resp.size(),
  17805. #endif
  17806. 0);
  17807. buf_all.erase(0, pos + 4);
  17808. }
  17809. }
  17810. detail::close_socket(cli);
  17811. detail::close_socket(srv);
  17812. });
  17813. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17814. auto cli = Client("127.0.0.1", PORT + 1);
  17815. auto headers = Headers{
  17816. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17817. {"Connection", "keep-alive"}};
  17818. auto res = cli.Get("/hi", headers);
  17819. EXPECT_FALSE(res);
  17820. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17821. server_thread.join();
  17822. }
  17823. // A request rejected before any byte reaches the socket must fail right away
  17824. // instead of waiting for a response the server will never send.
  17825. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17826. // The kernel completes the TCP handshake from the listen backlog, so the
  17827. // client connects, but nothing ever reads, responds or closes.
  17828. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17829. default_socket_options(srv);
  17830. sockaddr_in addr{};
  17831. addr.sin_family = AF_INET;
  17832. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17833. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17834. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17835. ASSERT_EQ(0, ::listen(srv, 8));
  17836. auto cli = Client("127.0.0.1", PORT + 1);
  17837. cli.set_read_timeout(10, 0);
  17838. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17839. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17840. std::chrono::steady_clock::now() - start)
  17841. .count();
  17842. };
  17843. {
  17844. Request req;
  17845. req.method = "GE T";
  17846. req.path = "/";
  17847. auto start = std::chrono::steady_clock::now();
  17848. auto res = cli.send(req);
  17849. EXPECT_FALSE(res);
  17850. EXPECT_EQ(Error::Write, res.error());
  17851. EXPECT_LT(elapsed_ms(start), 1000);
  17852. }
  17853. {
  17854. auto start = std::chrono::steady_clock::now();
  17855. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17856. EXPECT_FALSE(res);
  17857. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17858. EXPECT_LT(elapsed_ms(start), 1000);
  17859. }
  17860. EXPECT_FALSE(cli.is_socket_open());
  17861. detail::close_socket(srv);
  17862. }
  17863. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17864. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17865. default_socket_options(srv);
  17866. sockaddr_in addr{};
  17867. addr.sin_family = AF_INET;
  17868. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17869. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17870. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17871. ASSERT_EQ(0, ::listen(srv, 1));
  17872. std::string received;
  17873. auto server_thread = std::thread([&] {
  17874. auto sock = ::accept(srv, nullptr, nullptr);
  17875. if (sock == INVALID_SOCKET) { return; }
  17876. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17877. char buf[2048];
  17878. ssize_t n;
  17879. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17880. received.append(buf, static_cast<size_t>(n));
  17881. }
  17882. detail::close_socket(sock);
  17883. });
  17884. {
  17885. auto cli = Client("127.0.0.1", PORT + 1);
  17886. // "Z" sorts after the default headers, so writing straight to the socket
  17887. // would have sent the request line and those headers before the rejection.
  17888. auto handle =
  17889. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17890. EXPECT_FALSE(handle.is_valid());
  17891. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17892. }
  17893. server_thread.join();
  17894. detail::close_socket(srv);
  17895. EXPECT_TRUE(received.empty()) << received;
  17896. }
  17897. TEST(PathParamsTest, StaticMatch) {
  17898. const auto pattern = "/users/all";
  17899. detail::PathParamsMatcher matcher(pattern);
  17900. Request request;
  17901. request.path = "/users/all";
  17902. ASSERT_TRUE(matcher.match(request));
  17903. std::unordered_map<std::string, std::string> expected_params = {};
  17904. EXPECT_EQ(request.path_params, expected_params);
  17905. }
  17906. TEST(PathParamsTest, StaticMismatch) {
  17907. const auto pattern = "/users/all";
  17908. detail::PathParamsMatcher matcher(pattern);
  17909. Request request;
  17910. request.path = "/users/1";
  17911. ASSERT_FALSE(matcher.match(request));
  17912. }
  17913. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17914. const auto pattern = "/users/:id/subscriptions";
  17915. detail::PathParamsMatcher matcher(pattern);
  17916. Request request;
  17917. request.path = "/users/42/subscriptions";
  17918. ASSERT_TRUE(matcher.match(request));
  17919. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17920. EXPECT_EQ(request.path_params, expected_params);
  17921. }
  17922. TEST(PathParamsTest, SingleParamInTheEnd) {
  17923. const auto pattern = "/users/:id";
  17924. detail::PathParamsMatcher matcher(pattern);
  17925. Request request;
  17926. request.path = "/users/24";
  17927. ASSERT_TRUE(matcher.match(request));
  17928. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17929. EXPECT_EQ(request.path_params, expected_params);
  17930. }
  17931. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17932. const auto pattern = "/users/:id/";
  17933. detail::PathParamsMatcher matcher(pattern);
  17934. Request request;
  17935. request.path = "/users/42/";
  17936. ASSERT_TRUE(matcher.match(request));
  17937. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17938. EXPECT_EQ(request.path_params, expected_params);
  17939. }
  17940. TEST(PathParamsTest, EmptyParam) {
  17941. const auto pattern = "/users/:id/";
  17942. detail::PathParamsMatcher matcher(pattern);
  17943. Request request;
  17944. request.path = "/users//";
  17945. ASSERT_TRUE(matcher.match(request));
  17946. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17947. EXPECT_EQ(request.path_params, expected_params);
  17948. }
  17949. TEST(PathParamsTest, FragmentMismatch) {
  17950. const auto pattern = "/users/:id/";
  17951. detail::PathParamsMatcher matcher(pattern);
  17952. Request request;
  17953. request.path = "/admins/24/";
  17954. ASSERT_FALSE(matcher.match(request));
  17955. }
  17956. TEST(PathParamsTest, ExtraFragments) {
  17957. const auto pattern = "/users/:id";
  17958. detail::PathParamsMatcher matcher(pattern);
  17959. Request request;
  17960. request.path = "/users/42/subscriptions";
  17961. ASSERT_FALSE(matcher.match(request));
  17962. }
  17963. TEST(PathParamsTest, MissingTrailingParam) {
  17964. const auto pattern = "/users/:id";
  17965. detail::PathParamsMatcher matcher(pattern);
  17966. Request request;
  17967. request.path = "/users";
  17968. ASSERT_FALSE(matcher.match(request));
  17969. }
  17970. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17971. const auto pattern = "/users/:id/subscriptions";
  17972. detail::PathParamsMatcher matcher(pattern);
  17973. Request request;
  17974. request.path = "/users/subscriptions";
  17975. ASSERT_FALSE(matcher.match(request));
  17976. }
  17977. TEST(PathParamsTest, MultipleParams) {
  17978. const auto pattern = "/users/:userid/subscriptions/:subid";
  17979. detail::PathParamsMatcher matcher(pattern);
  17980. Request request;
  17981. request.path = "/users/42/subscriptions/2";
  17982. ASSERT_TRUE(matcher.match(request));
  17983. std::unordered_map<std::string, std::string> expected_params = {
  17984. {"userid", "42"}, {"subid", "2"}};
  17985. EXPECT_EQ(request.path_params, expected_params);
  17986. }
  17987. TEST(PathParamsTest, SequenceOfParams) {
  17988. const auto pattern = "/values/:x/:y/:z";
  17989. detail::PathParamsMatcher matcher(pattern);
  17990. Request request;
  17991. request.path = "/values/1/2/3";
  17992. ASSERT_TRUE(matcher.match(request));
  17993. std::unordered_map<std::string, std::string> expected_params = {
  17994. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17995. EXPECT_EQ(request.path_params, expected_params);
  17996. }
  17997. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17998. const auto pattern = "/prefix:suffix";
  17999. detail::PathParamsMatcher matcher(pattern);
  18000. Request request;
  18001. request.path = "/prefix:suffix";
  18002. ASSERT_TRUE(matcher.match(request));
  18003. const std::unordered_map<std::string, std::string> expected_params = {};
  18004. EXPECT_EQ(request.path_params, expected_params);
  18005. }
  18006. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18007. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18008. // calling thread's stack on a long enough path for a quantified pattern;
  18009. // RegexMatcher must refuse to run regex matching on paths beyond
  18010. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18011. detail::RegexMatcher matcher("/files/(.*)");
  18012. Request within_limit;
  18013. within_limit.path = "/files/" + std::string(10, 'A');
  18014. EXPECT_TRUE(matcher.match(within_limit));
  18015. Request over_limit;
  18016. over_limit.path =
  18017. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18018. EXPECT_FALSE(matcher.match(over_limit));
  18019. }
  18020. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18021. Server svr;
  18022. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18023. res.set_content("ok", "text/plain");
  18024. });
  18025. auto port = svr.bind_to_any_port(HOST);
  18026. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18027. auto se = detail::scope_exit([&] {
  18028. svr.stop();
  18029. thread.join();
  18030. ASSERT_FALSE(svr.is_running());
  18031. });
  18032. svr.wait_until_ready();
  18033. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18034. // request URI limit; this used to be able to crash the process.
  18035. std::string path =
  18036. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18037. std::string req = "GET " + path +
  18038. " HTTP/1.1\r\n"
  18039. "Host: " +
  18040. std::string(HOST) + ":" + std::to_string(port) +
  18041. "\r\n"
  18042. "Connection: close\r\n"
  18043. "\r\n";
  18044. std::string response;
  18045. ASSERT_TRUE(send_request(5, req, &response, port));
  18046. EXPECT_NE(std::string::npos, response.find("404"));
  18047. }
  18048. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18049. Server svr;
  18050. auto handler = [](const Request & /*req*/, Response &res) {
  18051. res.set_content("hit", "text/plain");
  18052. };
  18053. // No regex metacharacter, so this one is compared literally
  18054. svr.Get("/literal/route", handler);
  18055. // '.' is a regex metacharacter, so this one must keep regex semantics
  18056. svr.Get("/a.c", handler);
  18057. auto port = svr.bind_to_any_port(HOST);
  18058. std::thread t([&]() { svr.listen_after_bind(); });
  18059. auto se = detail::scope_exit([&] {
  18060. svr.stop();
  18061. t.join();
  18062. ASSERT_FALSE(svr.is_running());
  18063. });
  18064. svr.wait_until_ready();
  18065. Client cli(HOST, port);
  18066. struct {
  18067. const char *path;
  18068. int status;
  18069. } cases[] = {
  18070. {"/literal/route", StatusCode::OK_200},
  18071. {"/literal/routes", StatusCode::NotFound_404},
  18072. {"/literal/rout", StatusCode::NotFound_404},
  18073. {"/abc", StatusCode::OK_200},
  18074. {"/a.c", StatusCode::OK_200},
  18075. };
  18076. for (const auto &x : cases) {
  18077. auto res = cli.Get(x.path);
  18078. ASSERT_TRUE(res) << x.path;
  18079. EXPECT_EQ(x.status, res->status) << x.path;
  18080. }
  18081. }
  18082. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18083. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18084. // from exhausting the stack, so it must only constrain routes that actually
  18085. // run a regular expression. A literal route is matched by comparison and
  18086. // stays usable at any length.
  18087. Server svr;
  18088. const std::string pattern =
  18089. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18090. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18091. res.set_content("hit", "text/plain");
  18092. });
  18093. auto port = svr.bind_to_any_port(HOST);
  18094. std::thread t([&]() { svr.listen_after_bind(); });
  18095. auto se = detail::scope_exit([&] {
  18096. svr.stop();
  18097. t.join();
  18098. ASSERT_FALSE(svr.is_running());
  18099. });
  18100. svr.wait_until_ready();
  18101. Client cli(HOST, port);
  18102. auto res = cli.Get(pattern);
  18103. ASSERT_TRUE(res);
  18104. EXPECT_EQ(StatusCode::OK_200, res->status);
  18105. }
  18106. TEST(ParseUrlTest, VariousPatterns) {
  18107. {
  18108. detail::UrlComponents uc;
  18109. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18110. EXPECT_EQ("http", uc.scheme);
  18111. EXPECT_EQ("example.com", uc.host);
  18112. EXPECT_EQ("8080", uc.port);
  18113. EXPECT_EQ("/path", uc.path);
  18114. EXPECT_EQ("?q=1", uc.query);
  18115. }
  18116. {
  18117. detail::UrlComponents uc;
  18118. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18119. EXPECT_EQ("https", uc.scheme);
  18120. EXPECT_EQ("example.com", uc.host);
  18121. EXPECT_TRUE(uc.port.empty());
  18122. EXPECT_EQ("/path", uc.path);
  18123. }
  18124. {
  18125. detail::UrlComponents uc;
  18126. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18127. EXPECT_EQ("::1", uc.host);
  18128. EXPECT_EQ("8080", uc.port);
  18129. EXPECT_EQ("/path", uc.path);
  18130. }
  18131. {
  18132. detail::UrlComponents uc;
  18133. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18134. }
  18135. {
  18136. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18137. // the path while the connection still targets the bracketed host.
  18138. detail::UrlComponents uc;
  18139. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18140. }
  18141. {
  18142. detail::UrlComponents uc;
  18143. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18144. }
  18145. {
  18146. detail::UrlComponents uc;
  18147. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18148. EXPECT_EQ("::1", uc.host);
  18149. EXPECT_TRUE(uc.port.empty());
  18150. EXPECT_EQ("/path", uc.path);
  18151. }
  18152. {
  18153. detail::UrlComponents uc;
  18154. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18155. EXPECT_TRUE(uc.scheme.empty());
  18156. EXPECT_EQ("example.com", uc.host);
  18157. EXPECT_EQ("/path", uc.path);
  18158. EXPECT_EQ("?q=1", uc.query);
  18159. }
  18160. {
  18161. detail::UrlComponents uc;
  18162. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18163. EXPECT_TRUE(uc.host.empty());
  18164. EXPECT_EQ("/path", uc.path);
  18165. EXPECT_EQ("?q=1", uc.query);
  18166. }
  18167. {
  18168. detail::UrlComponents uc;
  18169. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18170. EXPECT_EQ("example.com", uc.host);
  18171. EXPECT_EQ("8080", uc.port);
  18172. }
  18173. {
  18174. // Unix socket path — must not be parsed as host
  18175. detail::UrlComponents uc;
  18176. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18177. EXPECT_TRUE(uc.host.empty());
  18178. }
  18179. {
  18180. detail::UrlComponents uc;
  18181. ASSERT_TRUE(detail::parse_url("", uc));
  18182. EXPECT_TRUE(uc.host.empty());
  18183. EXPECT_TRUE(uc.path.empty());
  18184. }
  18185. {
  18186. detail::UrlComponents uc;
  18187. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18188. }
  18189. {
  18190. detail::UrlComponents uc;
  18191. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18192. }
  18193. {
  18194. // Accepted by parse_url; callers restrict to http/https
  18195. detail::UrlComponents uc;
  18196. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18197. EXPECT_EQ("ftp", uc.scheme);
  18198. }
  18199. {
  18200. detail::UrlComponents uc;
  18201. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18202. }
  18203. {
  18204. detail::UrlComponents uc;
  18205. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18206. }
  18207. }
  18208. TEST(ParseUrlTest, FragmentHandling) {
  18209. {
  18210. detail::UrlComponents uc;
  18211. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18212. EXPECT_EQ("/path", uc.path);
  18213. EXPECT_TRUE(uc.query.empty());
  18214. }
  18215. {
  18216. detail::UrlComponents uc;
  18217. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18218. EXPECT_TRUE(uc.path.empty());
  18219. EXPECT_TRUE(uc.query.empty());
  18220. }
  18221. }
  18222. TEST(ParseUrlTest, UserinfoHandling) {
  18223. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18224. // parsers would see evil.com as the host.
  18225. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18226. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18227. for (auto url : urls) {
  18228. detail::UrlComponents uc;
  18229. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18230. }
  18231. }
  18232. TEST(ParseUrlTest, IPv6EdgeCases) {
  18233. {
  18234. detail::UrlComponents uc;
  18235. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18236. EXPECT_TRUE(uc.scheme.empty());
  18237. EXPECT_EQ("::1", uc.host);
  18238. EXPECT_EQ("8080", uc.port);
  18239. }
  18240. {
  18241. // Zone ID '%25' is not in [a-fA-F0-9:]
  18242. detail::UrlComponents uc;
  18243. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18244. }
  18245. }
  18246. TEST(ParseUrlTest, SchemeEdgeCases) {
  18247. {
  18248. detail::UrlComponents uc;
  18249. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18250. }
  18251. {
  18252. detail::UrlComponents uc;
  18253. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18254. }
  18255. {
  18256. detail::UrlComponents uc;
  18257. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18258. }
  18259. }
  18260. TEST(ParseUrlTest, PortEdgeCases) {
  18261. {
  18262. detail::UrlComponents uc;
  18263. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18264. EXPECT_TRUE(uc.port.empty());
  18265. EXPECT_EQ("/path", uc.path);
  18266. }
  18267. {
  18268. // parse_url accepts any port string; validation is done by parse_port
  18269. detail::UrlComponents uc;
  18270. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18271. EXPECT_EQ("abc", uc.port);
  18272. }
  18273. }
  18274. TEST(ParseUrlTest, WebSocketPatterns) {
  18275. {
  18276. detail::UrlComponents uc;
  18277. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18278. EXPECT_EQ("ws", uc.scheme);
  18279. EXPECT_EQ("echo.example.com", uc.host);
  18280. EXPECT_EQ("8080", uc.port);
  18281. EXPECT_EQ("/ws", uc.path);
  18282. }
  18283. {
  18284. detail::UrlComponents uc;
  18285. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18286. EXPECT_EQ("wss", uc.scheme);
  18287. EXPECT_EQ("echo.example.com", uc.host);
  18288. EXPECT_TRUE(uc.port.empty());
  18289. EXPECT_EQ("/ws", uc.path);
  18290. }
  18291. }
  18292. TEST(ParseUrlTest, QueryOnly) {
  18293. detail::UrlComponents uc;
  18294. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18295. EXPECT_TRUE(uc.host.empty());
  18296. EXPECT_TRUE(uc.path.empty());
  18297. EXPECT_EQ("?q=1&r=2", uc.query);
  18298. }
  18299. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18300. detail::UrlComponents uc;
  18301. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18302. EXPECT_TRUE(uc.scheme.empty());
  18303. EXPECT_EQ("example.com", uc.host);
  18304. EXPECT_EQ("443", uc.port);
  18305. EXPECT_EQ("/path", uc.path);
  18306. }
  18307. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18308. // If ipv6 regex working, regex match codepath is taken.
  18309. // else port will default to 80 in Client impl
  18310. int clientImplMagicPort = 80;
  18311. int port = 4321;
  18312. // above ports must be different to avoid false negative
  18313. EXPECT_NE(clientImplMagicPort, port);
  18314. std::string ipV6TestURL = "http://[ff06::c3]";
  18315. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18316. CLIENT_PRIVATE_KEY_FILE);
  18317. EXPECT_EQ(cli.port(), port);
  18318. }
  18319. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18320. auto file_path = "./www/dir/index.html";
  18321. auto dir_path = "./www/dir";
  18322. detail::FileStat stat_file(file_path);
  18323. EXPECT_TRUE(stat_file.is_file());
  18324. EXPECT_FALSE(stat_file.is_dir());
  18325. detail::FileStat stat_dir(dir_path);
  18326. EXPECT_FALSE(stat_dir.is_file());
  18327. EXPECT_TRUE(stat_dir.is_dir());
  18328. }
  18329. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18330. // IPv4 with default HTTP port (80)
  18331. EXPECT_EQ("example.com",
  18332. detail::make_host_and_port_string("example.com", 80, false));
  18333. // IPv4 with default HTTPS port (443)
  18334. EXPECT_EQ("example.com",
  18335. detail::make_host_and_port_string("example.com", 443, true));
  18336. // IPv4 with non-default HTTP port
  18337. EXPECT_EQ("example.com:8080",
  18338. detail::make_host_and_port_string("example.com", 8080, false));
  18339. // IPv4 with non-default HTTPS port
  18340. EXPECT_EQ("example.com:8443",
  18341. detail::make_host_and_port_string("example.com", 8443, true));
  18342. // IPv6 with default HTTP port (80)
  18343. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18344. // IPv6 with default HTTPS port (443)
  18345. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18346. // IPv6 with non-default HTTP port
  18347. EXPECT_EQ("[::1]:8080",
  18348. detail::make_host_and_port_string("::1", 8080, false));
  18349. // IPv6 with non-default HTTPS port
  18350. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18351. // IPv6 full address with default port
  18352. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18353. detail::make_host_and_port_string(
  18354. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18355. // IPv6 full address with non-default port
  18356. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18357. detail::make_host_and_port_string(
  18358. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18359. // IPv6 localhost with non-default port
  18360. EXPECT_EQ("[::1]:3000",
  18361. detail::make_host_and_port_string("::1", 3000, false));
  18362. // IPv6 with zone ID (link-local address) with default port
  18363. EXPECT_EQ("[fe80::1%eth0]",
  18364. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18365. // IPv6 with zone ID (link-local address) with non-default port
  18366. EXPECT_EQ("[fe80::1%eth0]:8080",
  18367. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18368. // Edge case: Port 443 with is_ssl=false (should add port)
  18369. EXPECT_EQ("example.com:443",
  18370. detail::make_host_and_port_string("example.com", 443, false));
  18371. // Edge case: Port 80 with is_ssl=true (should add port)
  18372. EXPECT_EQ("example.com:80",
  18373. detail::make_host_and_port_string("example.com", 80, true));
  18374. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18375. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18376. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18377. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18378. // Security fix: Already bracketed IPv6 should not get double brackets
  18379. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18380. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18381. EXPECT_EQ("[::1]:8080",
  18382. detail::make_host_and_port_string("[::1]", 8080, false));
  18383. EXPECT_EQ("[2001:db8::1]:8080",
  18384. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18385. EXPECT_EQ("[fe80::1%eth0]",
  18386. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18387. EXPECT_EQ("[fe80::1%eth0]:8080",
  18388. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18389. // Edge case: Empty host (should return as-is)
  18390. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18391. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18392. // This is a known limitation but shouldn't crash
  18393. EXPECT_EQ("[host:name]",
  18394. detail::make_host_and_port_string("host:name", 80, false));
  18395. // Port number edge cases (no validation, but should not crash)
  18396. EXPECT_EQ("example.com:0",
  18397. detail::make_host_and_port_string("example.com", 0, false));
  18398. EXPECT_EQ("example.com:-1",
  18399. detail::make_host_and_port_string("example.com", -1, false));
  18400. EXPECT_EQ("example.com:65535",
  18401. detail::make_host_and_port_string("example.com", 65535, false));
  18402. EXPECT_EQ("example.com:65536",
  18403. detail::make_host_and_port_string("example.com", 65536, false));
  18404. }
  18405. namespace httplib {
  18406. namespace detail {
  18407. std::string
  18408. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18409. const std::string &host, int port);
  18410. } // namespace detail
  18411. } // namespace httplib
  18412. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18413. std::map<std::string, std::string> addr_map = {
  18414. {"ipv4.example", "192.0.2.10"},
  18415. {"ipv6.example", "2001:db8::1"},
  18416. {"name.example", "internal.example.lan"},
  18417. {"empty.example", ""}};
  18418. EXPECT_EQ("192.0.2.10:443",
  18419. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18420. EXPECT_EQ("[2001:db8::1]:443",
  18421. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18422. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18423. addr_map, "name.example", 8443));
  18424. // An empty or absent mapping keeps the hostname as the target
  18425. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18426. addr_map, "empty.example", 443));
  18427. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18428. addr_map, "other.example", 443));
  18429. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18430. }
  18431. #ifdef CPPHTTPLIB_SSL_ENABLED
  18432. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18433. httplib::SSLClient cli("roblox.com", 443);
  18434. cli.set_follow_location(true);
  18435. auto res = cli.Get("/");
  18436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18437. EXPECT_EQ(StatusCode::OK_200, res->status);
  18438. }
  18439. #endif
  18440. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18441. Server svr;
  18442. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18443. EXPECT_EQ(res.status, 400);
  18444. });
  18445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18446. auto se = detail::scope_exit([&] {
  18447. svr.stop();
  18448. thread.join();
  18449. ASSERT_FALSE(svr.is_running());
  18450. });
  18451. svr.wait_until_ready();
  18452. Client cli(HOST, PORT);
  18453. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18454. }
  18455. TEST(InvalidHeaderCharsTest, is_field_name) {
  18456. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18457. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18458. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18459. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18460. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18461. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18462. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18463. EXPECT_FALSE(detail::fields::is_field_name(""));
  18464. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18465. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18466. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18467. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18468. }
  18469. TEST(InvalidHeaderCharsTest, is_field_value) {
  18470. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18471. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18472. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18473. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18474. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18475. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18476. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18477. EXPECT_TRUE(detail::fields::is_field_value(""));
  18478. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18479. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18480. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18481. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18482. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18483. }
  18484. TEST(InvalidHeaderCharsTest, OnServer) {
  18485. Server svr;
  18486. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18487. std::string header = "Not Set";
  18488. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18489. res.set_header(header, "value");
  18490. res.set_content("Page Content Page Content", "text/plain");
  18491. });
  18492. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18493. std::string header = "Not Set";
  18494. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18495. res.set_header("X-Test", header);
  18496. res.set_content("Page Content Page Content", "text/plain");
  18497. });
  18498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18499. auto se = detail::scope_exit([&] {
  18500. svr.stop();
  18501. thread.join();
  18502. ASSERT_FALSE(svr.is_running());
  18503. });
  18504. svr.wait_until_ready();
  18505. Client cli(HOST, PORT);
  18506. {
  18507. auto res = cli.Get(
  18508. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18510. EXPECT_EQ("Page Content Page Content", res->body);
  18511. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18512. }
  18513. {
  18514. auto res = cli.Get(
  18515. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18517. EXPECT_EQ("Page Content Page Content", res->body);
  18518. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18519. }
  18520. }
  18521. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18522. auto handled = false;
  18523. Server svr;
  18524. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18525. thread t = thread([&] { svr.listen(HOST, PORT); });
  18526. auto se = detail::scope_exit([&] {
  18527. svr.stop();
  18528. t.join();
  18529. ASSERT_FALSE(svr.is_running());
  18530. ASSERT_FALSE(handled);
  18531. });
  18532. svr.wait_until_ready();
  18533. auto req = "POST /test HTTP/1.1\r\n"
  18534. "Content-Length: x\r\n"
  18535. "\r\n";
  18536. std::string response;
  18537. ASSERT_TRUE(send_request(1, req, &response));
  18538. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18539. response.substr(0, response.find("\r\n")));
  18540. }
  18541. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18542. // case-insensitive, and a server that receives a 100-continue expectation in
  18543. // an HTTP/1.0 request MUST ignore it.
  18544. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18545. std::string response;
  18546. ASSERT_TRUE(send_request(1, req, &response, port));
  18547. *got_100 = response.find("100 Continue") != std::string::npos;
  18548. }
  18549. class ExpectTokenTest : public ::testing::Test {
  18550. protected:
  18551. void SetUp() override {
  18552. svr_.Post("/p", [](const Request &, Response &res) {
  18553. res.set_content("ok", "text/plain");
  18554. });
  18555. port_ = svr_.bind_to_any_port(HOST);
  18556. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18557. svr_.wait_until_ready();
  18558. }
  18559. void TearDown() override {
  18560. svr_.stop();
  18561. if (thread_.joinable()) { thread_.join(); }
  18562. }
  18563. std::string request(const char *version, const char *expect_value) const {
  18564. return std::string("POST /p ") + version +
  18565. "\r\n"
  18566. "Host: localhost\r\n"
  18567. "Content-Length: 2\r\n"
  18568. "Connection: close\r\n"
  18569. "Expect: " +
  18570. expect_value +
  18571. "\r\n"
  18572. "\r\n"
  18573. "hi";
  18574. }
  18575. Server svr_;
  18576. int port_ = 0;
  18577. thread thread_;
  18578. };
  18579. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18580. bool got_100 = false;
  18581. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18582. EXPECT_TRUE(got_100);
  18583. }
  18584. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18585. bool got_100 = true;
  18586. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18587. EXPECT_FALSE(got_100);
  18588. }
  18589. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18590. bool got_100 = false;
  18591. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18592. EXPECT_TRUE(got_100);
  18593. }
  18594. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18595. bool got_100 = false;
  18596. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18597. EXPECT_TRUE(got_100);
  18598. }
  18599. // `100 Continue` is sent only when the server starts reading the body, so a
  18600. // request rejected before that never invites the client to send it. The
  18601. // requests below carry the expectation but withhold the body, as a client
  18602. // waiting for `100 Continue` would.
  18603. // A POST that expects `100 Continue` and withholds its two-byte body.
  18604. static std::string expect_headers_only(const std::string &path) {
  18605. return "POST " + path +
  18606. " HTTP/1.1\r\n"
  18607. "Host: localhost\r\n"
  18608. "Content-Length: 2\r\n"
  18609. "Expect: 100-continue\r\n"
  18610. "\r\n";
  18611. }
  18612. class ExpectLazyContinueTest : public ::testing::Test {
  18613. protected:
  18614. void SetUp() override {
  18615. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18616. if (req.path == "/pre-routing") {
  18617. res.status = StatusCode::Unauthorized_401;
  18618. return Server::HandlerResponse::Handled;
  18619. }
  18620. return Server::HandlerResponse::Unhandled;
  18621. });
  18622. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18623. if (req.matched_route == "/pre-request") {
  18624. res.status = StatusCode::Forbidden_403;
  18625. return Server::HandlerResponse::Handled;
  18626. }
  18627. return Server::HandlerResponse::Unhandled;
  18628. });
  18629. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18630. res.set_content("ok", "text/plain");
  18631. });
  18632. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18633. res.set_content("ok", "text/plain");
  18634. });
  18635. svr_.Post("/reader-used", [](const Request &, Response &res,
  18636. const ContentReader &content_reader) {
  18637. std::string body;
  18638. content_reader([&](const char *data, size_t len) {
  18639. body.append(data, len);
  18640. return true;
  18641. });
  18642. res.set_content(body, "text/plain");
  18643. });
  18644. svr_.Post("/reader-unused",
  18645. [](const Request &, Response &res, const ContentReader &) {
  18646. res.set_content("ignored", "text/plain");
  18647. });
  18648. port_ = svr_.bind_to_any_port(HOST);
  18649. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18650. svr_.wait_until_ready();
  18651. }
  18652. void TearDown() override {
  18653. svr_.stop();
  18654. if (thread_.joinable()) { thread_.join(); }
  18655. }
  18656. // Sends `req` and reads until the server closes the connection. Returns
  18657. // false if the read had to wait for the client-side timeout instead.
  18658. bool send_until_closed(const std::string &req, std::string *resp) const {
  18659. auto start = std::chrono::steady_clock::now();
  18660. if (!send_request(3, req, resp, port_)) { return false; }
  18661. auto elapsed = std::chrono::steady_clock::now() - start;
  18662. return elapsed < std::chrono::seconds(2);
  18663. }
  18664. // The final response comes without `100 Continue`, and the server closes
  18665. // the connection since the body may or may not follow.
  18666. void expect_final_without_interim(const std::string &path,
  18667. const char *status_line) const {
  18668. std::string resp;
  18669. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18670. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18671. EXPECT_EQ(0u, resp.find(status_line));
  18672. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18673. }
  18674. Server svr_;
  18675. int port_ = 0;
  18676. thread thread_;
  18677. };
  18678. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18679. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18680. }
  18681. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18682. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18683. }
  18684. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18685. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18686. }
  18687. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18688. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18689. }
  18690. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18691. // The body follows once `100 Continue` has had time to arrive.
  18692. auto req = expect_headers_only("/reader-used");
  18693. req.insert(req.size() - 2, "Connection: close\r\n");
  18694. std::string resp;
  18695. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18696. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18697. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18698. EXPECT_NE(std::string::npos, resp.find("hi"));
  18699. }
  18700. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18701. // Large enough for the client to add `Expect: 100-continue` itself.
  18702. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18703. std::atomic<bool> body_sent{false};
  18704. Client cli(HOST, port_);
  18705. auto res = cli.Post(
  18706. "/pre-request", length,
  18707. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18708. body_sent = true;
  18709. std::string chunk(len, 'x');
  18710. sink.write(chunk.data(), chunk.size());
  18711. return true;
  18712. },
  18713. "application/octet-stream");
  18714. ASSERT_TRUE(res);
  18715. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18716. EXPECT_FALSE(body_sent);
  18717. }
  18718. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18719. Server svr;
  18720. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18721. return StatusCode::ExpectationFailed_417;
  18722. });
  18723. svr.Post("/p", [](const Request &, Response &res) {
  18724. res.set_content("ok", "text/plain");
  18725. });
  18726. auto port = svr.bind_to_any_port(HOST);
  18727. thread t = thread([&] { svr.listen_after_bind(); });
  18728. auto se = detail::scope_exit([&] {
  18729. svr.stop();
  18730. t.join();
  18731. });
  18732. svr.wait_until_ready();
  18733. std::string resp;
  18734. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18735. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18736. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18737. // Exactly one response: the route handler must not run after the 417.
  18738. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18739. }
  18740. #ifndef _WIN32
  18741. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18742. static constexpr char reject[] = "Unauthorized";
  18743. static constexpr char accept[] = "Upload accepted";
  18744. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18745. Server svr;
  18746. svr.set_expect_100_continue_handler(
  18747. [](const Request & /*req*/, Response &res) {
  18748. res.status = StatusCode::Unauthorized_401;
  18749. res.set_content(reject, "text/plain");
  18750. return res.status;
  18751. });
  18752. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18753. res.set_content(accept, "text/plain");
  18754. });
  18755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18756. auto se = detail::scope_exit([&] {
  18757. svr.stop();
  18758. thread.join();
  18759. ASSERT_FALSE(svr.is_running());
  18760. });
  18761. svr.wait_until_ready();
  18762. {
  18763. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18764. curl_easy_init(), &curl_easy_cleanup};
  18765. ASSERT_NE(curl, nullptr);
  18766. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18767. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18768. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18769. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18770. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18771. &curl_slist_free_all};
  18772. ASSERT_NE(list, nullptr);
  18773. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18774. struct read_data {
  18775. uint64_t read_size;
  18776. uint64_t total_size;
  18777. } data = {0, total_size};
  18778. using read_callback_t =
  18779. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18780. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18781. void *userdata) -> size_t {
  18782. read_data *d = (read_data *)userdata;
  18783. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18784. std::fill_n(ptr, size * nmemb, 'A');
  18785. d->read_size += size * nmemb;
  18786. return size * nmemb;
  18787. };
  18788. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18789. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18790. std::vector<char> buffer;
  18791. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18792. using write_callback_t =
  18793. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18794. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18795. void *userdata) -> size_t {
  18796. std::vector<char> *buf = (std::vector<char> *)userdata;
  18797. buf->reserve(buf->size() + size * nmemb + 1);
  18798. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18799. return size * nmemb;
  18800. };
  18801. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18802. {
  18803. const auto res = curl_easy_perform(curl.get());
  18804. ASSERT_EQ(res, CURLE_OK);
  18805. }
  18806. {
  18807. auto response_code = long{};
  18808. const auto res =
  18809. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18810. ASSERT_EQ(res, CURLE_OK);
  18811. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18812. }
  18813. {
  18814. auto dl = curl_off_t{};
  18815. const auto res =
  18816. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18817. ASSERT_EQ(res, CURLE_OK);
  18818. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18819. }
  18820. {
  18821. buffer.push_back('\0');
  18822. ASSERT_STRCASEEQ(buffer.data(), reject);
  18823. }
  18824. }
  18825. }
  18826. #endif
  18827. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18828. // Regression test for #2458.
  18829. //
  18830. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18831. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18832. // ticket can make the client socket spuriously readable during the
  18833. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18834. // the client withholds the body and then blocks reading a response that never
  18835. // comes, failing with `Failed to read connection`.
  18836. //
  18837. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18838. // within the timeout. This raw OpenSSL server deliberately never sends
  18839. // `100 Continue`; the client must still deliver the body and receive 200.
  18840. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18841. signal(SIGPIPE, SIG_IGN);
  18842. const auto port = PORT + 4;
  18843. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18844. ASSERT_NE(srv, INVALID_SOCKET);
  18845. int opt = 1;
  18846. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18847. sockaddr_in addr{};
  18848. addr.sin_family = AF_INET;
  18849. addr.sin_port = htons(static_cast<uint16_t>(port));
  18850. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18851. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18852. ASSERT_EQ(0, ::listen(srv, 1));
  18853. std::atomic<size_t> server_body_bytes{0};
  18854. auto server_thread = std::thread([&] {
  18855. sockaddr_in cli_addr{};
  18856. socklen_t cli_len = sizeof(cli_addr);
  18857. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18858. if (cli == INVALID_SOCKET) { return; }
  18859. // Bound the lifetime of the server side so a buggy client (which never
  18860. // sends the body) cannot make this thread block forever on join.
  18861. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18862. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18863. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18864. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18865. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18866. SSL *ssl = SSL_new(ctx);
  18867. SSL_set_fd(ssl, static_cast<int>(cli));
  18868. if (SSL_accept(ssl) > 0) {
  18869. // Read the request headers. Reading here also flushes the TLS 1.3
  18870. // session tickets to the client. Deliberately do NOT send
  18871. // `100 Continue`.
  18872. std::string buf;
  18873. char tmp[1024];
  18874. while (buf.find("\r\n\r\n") == std::string::npos) {
  18875. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18876. if (n <= 0) { break; }
  18877. buf.append(tmp, static_cast<size_t>(n));
  18878. }
  18879. // A correct client sends the body now; count what arrives.
  18880. auto pos = buf.find("\r\n\r\n");
  18881. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18882. while (body < 4096) {
  18883. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18884. if (n <= 0) { break; }
  18885. body += static_cast<size_t>(n);
  18886. }
  18887. server_body_bytes = body;
  18888. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18889. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18890. SSL_shutdown(ssl);
  18891. }
  18892. SSL_free(ssl);
  18893. detail::close_socket(cli);
  18894. SSL_CTX_free(ctx);
  18895. });
  18896. auto se = detail::scope_exit([&] {
  18897. server_thread.join();
  18898. detail::close_socket(srv);
  18899. });
  18900. SSLClient cli("127.0.0.1", port);
  18901. cli.enable_server_certificate_verification(false);
  18902. cli.set_connection_timeout(5, 0);
  18903. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18904. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18905. std::string body(4096, 'A');
  18906. auto res = cli.Put("/api/test", body, "application/json");
  18907. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18908. EXPECT_EQ(StatusCode::OK_200, res->status);
  18909. EXPECT_EQ(body.size(), server_body_bytes.load());
  18910. }
  18911. #endif
  18912. template <typename S, typename C>
  18913. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18914. svr.Get("/stream", [&](const Request &, Response &res) {
  18915. auto data = new std::string("01234567890123456789");
  18916. res.set_content_provider(
  18917. data->size(), "text/plain",
  18918. [&, data](size_t offset, size_t length, DataSink &sink) {
  18919. const size_t DATA_CHUNK_SIZE = 4;
  18920. const auto &d = *data;
  18921. std::this_thread::sleep_for(std::chrono::seconds(1));
  18922. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18923. return true;
  18924. },
  18925. [data](bool success) {
  18926. EXPECT_FALSE(success);
  18927. delete data;
  18928. });
  18929. });
  18930. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18931. auto i = new size_t(0);
  18932. res.set_content_provider(
  18933. "text/plain",
  18934. [i](size_t, DataSink &sink) {
  18935. if (*i < 5) {
  18936. std::this_thread::sleep_for(std::chrono::seconds(1));
  18937. sink.write("abcd", 4);
  18938. (*i)++;
  18939. } else {
  18940. sink.done();
  18941. }
  18942. return true;
  18943. },
  18944. [i](bool success) {
  18945. EXPECT_FALSE(success);
  18946. delete i;
  18947. });
  18948. });
  18949. svr.Get("/chunked", [&](const Request &, Response &res) {
  18950. auto i = new size_t(0);
  18951. res.set_chunked_content_provider(
  18952. "text/plain",
  18953. [i](size_t, DataSink &sink) {
  18954. if (*i < 5) {
  18955. std::this_thread::sleep_for(std::chrono::seconds(1));
  18956. sink.os << "abcd";
  18957. (*i)++;
  18958. } else {
  18959. sink.done();
  18960. }
  18961. return true;
  18962. },
  18963. [i](bool success) {
  18964. EXPECT_FALSE(success);
  18965. delete i;
  18966. });
  18967. });
  18968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18969. auto se = detail::scope_exit([&] {
  18970. svr.stop();
  18971. listen_thread.join();
  18972. ASSERT_FALSE(svr.is_running());
  18973. });
  18974. svr.wait_until_ready();
  18975. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18976. {
  18977. auto start = std::chrono::steady_clock::now();
  18978. auto res = cli.Get("/stream");
  18979. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18980. std::chrono::steady_clock::now() - start)
  18981. .count();
  18982. ASSERT_FALSE(res);
  18983. EXPECT_EQ(Error::Read, res.error());
  18984. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18985. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18986. }
  18987. {
  18988. auto start = std::chrono::steady_clock::now();
  18989. auto res = cli.Get("/stream_without_length");
  18990. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18991. std::chrono::steady_clock::now() - start)
  18992. .count();
  18993. ASSERT_FALSE(res);
  18994. EXPECT_EQ(Error::Read, res.error());
  18995. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18996. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18997. }
  18998. {
  18999. auto start = std::chrono::steady_clock::now();
  19000. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19001. EXPECT_EQ("abcd", string(data, data_length));
  19002. return true;
  19003. });
  19004. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19005. std::chrono::steady_clock::now() - start)
  19006. .count();
  19007. ASSERT_FALSE(res);
  19008. EXPECT_EQ(Error::Read, res.error());
  19009. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19010. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19011. }
  19012. }
  19013. TEST(MaxTimeoutTest, ContentStream) {
  19014. time_t timeout = 2000;
  19015. time_t threshold = 200;
  19016. Server svr;
  19017. Client cli("localhost", PORT);
  19018. max_timeout_test(svr, cli, timeout, threshold);
  19019. }
  19020. #ifdef CPPHTTPLIB_SSL_ENABLED
  19021. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19022. time_t timeout = 2000;
  19023. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19025. SSLClient cli("localhost", PORT);
  19026. cli.enable_server_certificate_verification(false);
  19027. max_timeout_test(svr, cli, timeout, threshold);
  19028. }
  19029. #endif
  19030. class EventDispatcher {
  19031. public:
  19032. EventDispatcher() {}
  19033. bool wait_event(DataSink *sink) {
  19034. unique_lock<mutex> lk(m_);
  19035. int id = id_;
  19036. // Wait with timeout to prevent hanging if client disconnects
  19037. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19038. [&] { return cid_ == id; })) {
  19039. return false; // Timeout occurred
  19040. }
  19041. sink->write(message_.data(), message_.size());
  19042. return true;
  19043. }
  19044. void send_event(const string &message) {
  19045. lock_guard<mutex> lk(m_);
  19046. cid_ = id_++;
  19047. message_ = message;
  19048. cv_.notify_all();
  19049. }
  19050. private:
  19051. mutex m_;
  19052. condition_variable cv_;
  19053. atomic_int id_{0};
  19054. atomic_int cid_{-1};
  19055. string message_;
  19056. };
  19057. TEST(ClientInThreadTest, Issue2068) {
  19058. EventDispatcher ed;
  19059. Server svr;
  19060. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19061. res.set_chunked_content_provider("text/event-stream",
  19062. [&](size_t /*offset*/, DataSink &sink) {
  19063. return ed.wait_event(&sink);
  19064. });
  19065. });
  19066. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19067. svr.wait_until_ready();
  19068. thread event_thread([&] {
  19069. int id = 0;
  19070. while (svr.is_running()) {
  19071. this_thread::sleep_for(chrono::milliseconds(500));
  19072. std::stringstream ss;
  19073. ss << "data: " << id << "\n\n";
  19074. ed.send_event(ss.str());
  19075. id++;
  19076. }
  19077. });
  19078. auto se = detail::scope_exit([&] {
  19079. svr.stop();
  19080. listen_thread.join();
  19081. event_thread.join();
  19082. ASSERT_FALSE(svr.is_running());
  19083. });
  19084. {
  19085. auto client = detail::make_unique<Client>(HOST, PORT);
  19086. client->set_read_timeout(std::chrono::minutes(10));
  19087. std::atomic<bool> stop{false};
  19088. std::thread t([&] {
  19089. client->Get("/event1",
  19090. [&](const char *, size_t) -> bool { return !stop; });
  19091. });
  19092. std::this_thread::sleep_for(std::chrono::seconds(2));
  19093. stop = true;
  19094. client->stop();
  19095. t.join();
  19096. // Reset client after thread has finished
  19097. client.reset();
  19098. }
  19099. }
  19100. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19101. auto handled = false;
  19102. Server svr;
  19103. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19104. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19105. auto se = detail::scope_exit([&] {
  19106. svr.stop();
  19107. t.join();
  19108. ASSERT_FALSE(svr.is_running());
  19109. ASSERT_FALSE(handled);
  19110. });
  19111. svr.wait_until_ready();
  19112. // Two Content-Length headers with different values — must be rejected
  19113. auto req = "POST /test HTTP/1.1\r\n"
  19114. "Content-Length: 5\r\n"
  19115. "Content-Length: 10\r\n"
  19116. "\r\n"
  19117. "hello";
  19118. std::string response;
  19119. ASSERT_TRUE(send_request(1, req, &response));
  19120. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19121. response.substr(0, response.find("\r\n")));
  19122. }
  19123. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19124. auto handled = false;
  19125. Server svr;
  19126. svr.Post("/test", [&](const Request &, Response &res) {
  19127. handled = true;
  19128. res.set_content("ok", "text/plain");
  19129. });
  19130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19131. auto se = detail::scope_exit([&] {
  19132. svr.stop();
  19133. t.join();
  19134. ASSERT_FALSE(svr.is_running());
  19135. ASSERT_TRUE(handled);
  19136. });
  19137. svr.wait_until_ready();
  19138. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19139. auto req = "POST /test HTTP/1.1\r\n"
  19140. "Host: localhost\r\n"
  19141. "Content-Length: 5\r\n"
  19142. "Content-Length: 5\r\n"
  19143. "\r\n"
  19144. "hello";
  19145. std::string response;
  19146. ASSERT_TRUE(send_request(1, req, &response));
  19147. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19148. }
  19149. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19150. Server svr;
  19151. svr.Get("/test", [](const Request &, Response &res) {
  19152. res.set_content("ok", "text/plain");
  19153. });
  19154. auto port = svr.bind_to_any_port(HOST);
  19155. thread t = thread([&] { svr.listen_after_bind(); });
  19156. auto se = detail::scope_exit([&] {
  19157. svr.stop();
  19158. t.join();
  19159. ASSERT_FALSE(svr.is_running());
  19160. });
  19161. svr.wait_until_ready();
  19162. auto status_line = [&](const std::string &host_lines) {
  19163. std::string res;
  19164. send_request(
  19165. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19166. &res, port);
  19167. return res.substr(0, res.find("\r\n"));
  19168. };
  19169. const char *accepted[] = {
  19170. "Host: localhost\r\n",
  19171. "Host: a.example:8080\r\n",
  19172. "Host: my_service\r\n",
  19173. "Host: [::1]:8080\r\n",
  19174. "Host: [fe80::1%25eth0]\r\n",
  19175. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19176. };
  19177. for (auto host_lines : accepted) {
  19178. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19179. }
  19180. const char *rejected[] = {
  19181. "Host: a.example\r\nHost: b.example\r\n",
  19182. "Host: a.example\r\nHost: a.example\r\n",
  19183. "Host: a@b.example\r\n",
  19184. "Host: a.example/b\r\n",
  19185. "Host: a.example\\b\r\n",
  19186. "Host: a.example?b\r\n",
  19187. "Host: a.example#b\r\n",
  19188. "Host: a.example b.example\r\n",
  19189. };
  19190. for (auto host_lines : rejected) {
  19191. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19192. << host_lines;
  19193. }
  19194. }
  19195. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19196. Server svr;
  19197. svr.Get("/", [](const Request &req, Response &res) {
  19198. EXPECT_EQ(2U, req.trailers.size());
  19199. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19200. // Denied
  19201. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19202. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19203. // Accepted
  19204. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19205. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19206. EXPECT_TRUE(req.has_trailer("X-World"));
  19207. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19208. res.set_content("ok", "text/plain");
  19209. });
  19210. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19211. auto se = detail::scope_exit([&] {
  19212. svr.stop();
  19213. t.join();
  19214. ASSERT_FALSE(svr.is_running());
  19215. });
  19216. svr.wait_until_ready();
  19217. const std::string req = "GET / HTTP/1.1\r\n"
  19218. "Transfer-Encoding: chunked\r\n"
  19219. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19220. "\r\n"
  19221. "0\r\n"
  19222. "Content-Length: 10\r\n"
  19223. "Host: internal.local\r\n"
  19224. "Content-Type: malicious/content\r\n"
  19225. "Cookie: any\r\n"
  19226. "Set-Cookie: any\r\n"
  19227. "X-Forwarded-For: attacker.com\r\n"
  19228. "X-Real-Ip: 1.1.1.1\r\n"
  19229. "X-Hello: hello\r\n"
  19230. "X-World: world\r\n"
  19231. "\r\n";
  19232. std::string res;
  19233. ASSERT_TRUE(send_request(1, req, &res));
  19234. }
  19235. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19236. // several field lines, and the combined value is what has to be parsed. A
  19237. // Trailer field split across lines therefore declares every name it lists;
  19238. // reading only the first line silently drops the trailers the later lines
  19239. // declare. The prohibited-trailer filter still applies to every line.
  19240. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19241. Server svr;
  19242. size_t observed_trailer_count = 0;
  19243. std::string observed_hello;
  19244. std::string observed_world;
  19245. bool observed_content_length = true;
  19246. svr.Get("/", [&](const Request &req, Response &res) {
  19247. observed_trailer_count = req.trailers.size();
  19248. observed_hello = req.get_trailer_value("X-Hello");
  19249. observed_world = req.get_trailer_value("X-World");
  19250. observed_content_length = req.has_trailer("Content-Length");
  19251. res.set_content("ok", "text/plain");
  19252. });
  19253. auto port = svr.bind_to_any_port(HOST);
  19254. thread t = thread([&]() { svr.listen_after_bind(); });
  19255. auto se = detail::scope_exit([&] {
  19256. svr.stop();
  19257. t.join();
  19258. ASSERT_FALSE(svr.is_running());
  19259. });
  19260. svr.wait_until_ready();
  19261. const std::string req = "GET / HTTP/1.1\r\n"
  19262. "Host: localhost\r\n"
  19263. "Transfer-Encoding: chunked\r\n"
  19264. "Trailer: X-Hello\r\n"
  19265. "Trailer: X-World, Content-Length\r\n"
  19266. "\r\n"
  19267. "0\r\n"
  19268. "X-Hello: hello\r\n"
  19269. "X-World: world\r\n"
  19270. "Content-Length: 10\r\n"
  19271. "\r\n";
  19272. std::string res;
  19273. ASSERT_TRUE(send_request(1, req, &res, port));
  19274. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19275. // Accepted: both field lines contribute to the declared set
  19276. EXPECT_EQ(2U, observed_trailer_count);
  19277. EXPECT_EQ(observed_hello, "hello");
  19278. EXPECT_EQ(observed_world, "world");
  19279. // Denied: a prohibited name stays prohibited on a later field line
  19280. EXPECT_FALSE(observed_content_length);
  19281. }
  19282. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19283. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19284. // unbounded run of fields that are never declared, because the counter would
  19285. // only advance for declared fields.
  19286. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19287. Server svr;
  19288. bool handler_called = false;
  19289. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19290. handler_called = true;
  19291. res.set_content("ok", "text/plain");
  19292. });
  19293. auto port = svr.bind_to_any_port(HOST);
  19294. thread t = thread([&]() { svr.listen_after_bind(); });
  19295. auto se = detail::scope_exit([&] {
  19296. svr.stop();
  19297. t.join();
  19298. ASSERT_FALSE(svr.is_running());
  19299. });
  19300. svr.wait_until_ready();
  19301. // Declare nothing, then send far more undeclared trailer fields than the
  19302. // header-count limit. Parsing must stop and reject the request rather than
  19303. // read every line.
  19304. std::string req = "GET / HTTP/1.1\r\n"
  19305. "Transfer-Encoding: chunked\r\n"
  19306. "\r\n"
  19307. "0\r\n";
  19308. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19309. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19310. }
  19311. req += "\r\n";
  19312. std::string res;
  19313. ASSERT_TRUE(send_request(1, req, &res, port));
  19314. // The request is rejected before the handler runs.
  19315. EXPECT_FALSE(handler_called);
  19316. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19317. }
  19318. // The set of declared trailer names is capped so a peer cannot grow it without
  19319. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19320. // declared past the cap is not honored, even if the field is actually sent.
  19321. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19322. Server svr;
  19323. // One name inside the cap and one past it, so the test tracks the cap rather
  19324. // than a fixed count.
  19325. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19326. const std::string within_cap_name = "X-T-0";
  19327. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19328. bool observed_within_cap = false;
  19329. bool observed_past_cap = false;
  19330. svr.Get("/", [&](const Request &req, Response &res) {
  19331. observed_within_cap = req.has_trailer(within_cap_name);
  19332. observed_past_cap = req.has_trailer(past_cap_name);
  19333. res.set_content("ok", "text/plain");
  19334. });
  19335. auto port = svr.bind_to_any_port(HOST);
  19336. thread t = thread([&]() { svr.listen_after_bind(); });
  19337. auto se = detail::scope_exit([&] {
  19338. svr.stop();
  19339. t.join();
  19340. ASSERT_FALSE(svr.is_running());
  19341. });
  19342. svr.wait_until_ready();
  19343. // Declare more trailer names than the cap in a single Trailer field, then
  19344. // actually send the first (within the cap) and the last (past it).
  19345. std::string trailer_decl = "Trailer: ";
  19346. for (int i = 0; i < declared_count; i++) {
  19347. if (i != 0) { trailer_decl += ", "; }
  19348. trailer_decl += "X-T-" + std::to_string(i);
  19349. }
  19350. trailer_decl += "\r\n";
  19351. const std::string req = "GET / HTTP/1.1\r\n"
  19352. "Host: localhost\r\n"
  19353. "Transfer-Encoding: chunked\r\n" +
  19354. trailer_decl +
  19355. "\r\n"
  19356. "0\r\n" +
  19357. within_cap_name + ": a\r\n" + past_cap_name +
  19358. ": b\r\n"
  19359. "\r\n";
  19360. std::string res;
  19361. ASSERT_TRUE(send_request(1, req, &res, port));
  19362. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19363. // A name within the cap is honored; one declared past the cap is dropped.
  19364. EXPECT_TRUE(observed_within_cap);
  19365. EXPECT_FALSE(observed_past_cap);
  19366. }
  19367. // A direct client that is not listed in trusted_proxies must not be able to
  19368. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19369. // the peer address on the actual TCP connection determines whether the
  19370. // header is honored.
  19371. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19372. Server svr;
  19373. // Deliberately does NOT include the loopback address the test client
  19374. // actually connects from, so the direct connection is not a trusted proxy.
  19375. svr.set_trusted_proxies({"203.0.113.66"});
  19376. std::string observed_remote_addr;
  19377. svr.Get("/ip", [&](const Request &req, Response &res) {
  19378. observed_remote_addr = req.remote_addr;
  19379. res.set_content("ok", "text/plain");
  19380. });
  19381. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19382. auto se = detail::scope_exit([&] {
  19383. svr.stop();
  19384. t.join();
  19385. ASSERT_FALSE(svr.is_running());
  19386. });
  19387. svr.wait_until_ready();
  19388. Client cli(HOST, PORT);
  19389. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19391. EXPECT_EQ(StatusCode::OK_200, res->status);
  19392. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19393. // ignored entirely and the real connection-level address retained.
  19394. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19395. observed_remote_addr == "127.0.0.1");
  19396. }
  19397. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19398. Server svr;
  19399. std::string observed_remote_addr;
  19400. std::string observed_xff;
  19401. svr.Get("/ip", [&](const Request &req, Response &res) {
  19402. observed_remote_addr = req.remote_addr;
  19403. observed_xff = req.get_header_value("X-Forwarded-For");
  19404. res.set_content("ok", "text/plain");
  19405. });
  19406. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19407. auto se = detail::scope_exit([&] {
  19408. svr.stop();
  19409. t.join();
  19410. ASSERT_FALSE(svr.is_running());
  19411. });
  19412. svr.wait_until_ready();
  19413. Client cli(HOST, PORT);
  19414. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19416. EXPECT_EQ(StatusCode::OK_200, res->status);
  19417. EXPECT_EQ(observed_xff, "203.0.113.66");
  19418. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19419. observed_remote_addr == "127.0.0.1");
  19420. }
  19421. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19422. Server svr;
  19423. svr.set_trusted_proxies({"203.0.113.66"});
  19424. std::string observed_remote_addr;
  19425. std::string observed_xff;
  19426. svr.Get("/ip", [&](const Request &req, Response &res) {
  19427. observed_remote_addr = req.remote_addr;
  19428. observed_xff = req.get_header_value("X-Forwarded-For");
  19429. res.set_content("ok", "text/plain");
  19430. });
  19431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19432. auto se = detail::scope_exit([&] {
  19433. svr.stop();
  19434. t.join();
  19435. ASSERT_FALSE(svr.is_running());
  19436. });
  19437. svr.wait_until_ready();
  19438. Client cli(HOST, PORT);
  19439. auto res = cli.Get("/ip");
  19440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19441. EXPECT_EQ(StatusCode::OK_200, res->status);
  19442. EXPECT_EQ(observed_xff, "");
  19443. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19444. observed_remote_addr == "127.0.0.1");
  19445. }
  19446. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19447. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19448. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19449. Server svr;
  19450. svr.set_trusted_proxies({"127.0.0.1"});
  19451. svr.Get("/ip", [](const Request &req, Response &res) {
  19452. res.set_content(req.remote_addr, "text/plain");
  19453. });
  19454. auto port = svr.bind_to_any_port("::");
  19455. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19456. thread t = thread([&] { svr.listen_after_bind(); });
  19457. auto se = detail::scope_exit([&] {
  19458. svr.stop();
  19459. t.join();
  19460. ASSERT_FALSE(svr.is_running());
  19461. });
  19462. svr.wait_until_ready();
  19463. Client cli("127.0.0.1", port);
  19464. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19466. EXPECT_EQ("198.51.100.23", res->body);
  19467. }
  19468. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19469. Server svr;
  19470. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19471. svr.Get("/ip", [](const Request &req, Response &res) {
  19472. res.set_content(req.remote_addr, "text/plain");
  19473. });
  19474. auto port = svr.bind_to_any_port(HOST);
  19475. ASSERT_GT(port, 0);
  19476. thread t = thread([&] { svr.listen_after_bind(); });
  19477. auto se = detail::scope_exit([&] {
  19478. svr.stop();
  19479. t.join();
  19480. ASSERT_FALSE(svr.is_running());
  19481. });
  19482. svr.wait_until_ready();
  19483. Client cli(HOST, port);
  19484. auto res = cli.Get(
  19485. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19487. EXPECT_EQ("198.51.100.23", res->body);
  19488. }
  19489. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19490. Server svr;
  19491. // Include the loopback address the test client actually connects from, so
  19492. // the direct connection itself is recognized as the trusted proxy hop.
  19493. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19494. std::string observed_remote_addr;
  19495. std::string observed_xff;
  19496. svr.Get("/ip", [&](const Request &req, Response &res) {
  19497. observed_remote_addr = req.remote_addr;
  19498. observed_xff = req.get_header_value("X-Forwarded-For");
  19499. res.set_content("ok", "text/plain");
  19500. });
  19501. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19502. auto se = detail::scope_exit([&] {
  19503. svr.stop();
  19504. t.join();
  19505. ASSERT_FALSE(svr.is_running());
  19506. });
  19507. svr.wait_until_ready();
  19508. Client cli(HOST, PORT);
  19509. auto res = cli.Get(
  19510. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19512. EXPECT_EQ(StatusCode::OK_200, res->status);
  19513. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19514. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19515. }
  19516. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19517. Server svr;
  19518. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19519. std::string observed_remote_addr;
  19520. std::string observed_xff;
  19521. svr.Get("/ip", [&](const Request &req, Response &res) {
  19522. observed_remote_addr = req.remote_addr;
  19523. observed_xff = req.get_header_value("X-Forwarded-For");
  19524. res.set_content("ok", "text/plain");
  19525. });
  19526. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19527. auto se = detail::scope_exit([&] {
  19528. svr.stop();
  19529. t.join();
  19530. ASSERT_FALSE(svr.is_running());
  19531. });
  19532. svr.wait_until_ready();
  19533. Client cli(HOST, PORT);
  19534. auto res = cli.Get(
  19535. "/ip",
  19536. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19538. EXPECT_EQ(StatusCode::OK_200, res->status);
  19539. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19540. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19541. }
  19542. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19543. Server svr;
  19544. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19545. std::string observed_remote_addr;
  19546. std::string observed_xff;
  19547. svr.Get("/ip", [&](const Request &req, Response &res) {
  19548. observed_remote_addr = req.remote_addr;
  19549. observed_xff = req.get_header_value("X-Forwarded-For");
  19550. res.set_content("ok", "text/plain");
  19551. });
  19552. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19553. auto se = detail::scope_exit([&] {
  19554. svr.stop();
  19555. t.join();
  19556. ASSERT_FALSE(svr.is_running());
  19557. });
  19558. svr.wait_until_ready();
  19559. Client cli(HOST, PORT);
  19560. auto res = cli.Get(
  19561. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19563. EXPECT_EQ(StatusCode::OK_200, res->status);
  19564. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19565. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19566. // and must not be selected.
  19567. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19568. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19569. }
  19570. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19571. Server svr;
  19572. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19573. std::string observed_remote_addr;
  19574. svr.Get("/ip", [&](const Request &req, Response &res) {
  19575. observed_remote_addr = req.remote_addr;
  19576. res.set_content("ok", "text/plain");
  19577. });
  19578. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19579. auto se = detail::scope_exit([&] {
  19580. svr.stop();
  19581. t.join();
  19582. ASSERT_FALSE(svr.is_running());
  19583. });
  19584. svr.wait_until_ready();
  19585. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19586. // a forged address and the trusted proxy's own address; the forged value must
  19587. // not win over the address the trusted proxy actually recorded.
  19588. Client cli(HOST, PORT);
  19589. auto res = cli.Get(
  19590. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19592. EXPECT_EQ(StatusCode::OK_200, res->status);
  19593. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19594. }
  19595. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19596. Server svr;
  19597. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19598. std::string observed_remote_addr;
  19599. std::string observed_xff;
  19600. svr.Get("/ip", [&](const Request &req, Response &res) {
  19601. observed_remote_addr = req.remote_addr;
  19602. observed_xff = req.get_header_value("X-Forwarded-For");
  19603. res.set_content("ok", "text/plain");
  19604. });
  19605. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19606. auto se = detail::scope_exit([&] {
  19607. svr.stop();
  19608. t.join();
  19609. ASSERT_FALSE(svr.is_running());
  19610. });
  19611. svr.wait_until_ready();
  19612. Client cli(HOST, PORT);
  19613. auto res = cli.Get(
  19614. "/ip",
  19615. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19617. EXPECT_EQ(StatusCode::OK_200, res->status);
  19618. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19619. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19620. }
  19621. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19622. Server svr;
  19623. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19624. std::string observed_remote_addr;
  19625. std::string observed_xff;
  19626. svr.Get("/ip", [&](const Request &req, Response &res) {
  19627. observed_remote_addr = req.remote_addr;
  19628. observed_xff = req.get_header_value("X-Forwarded-For");
  19629. res.set_content("ok", "text/plain");
  19630. });
  19631. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19632. auto se = detail::scope_exit([&] {
  19633. svr.stop();
  19634. t.join();
  19635. ASSERT_FALSE(svr.is_running());
  19636. });
  19637. svr.wait_until_ready();
  19638. std::string raw_req =
  19639. "GET /ip HTTP/1.1\r\n"
  19640. "Host: localhost\r\n"
  19641. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19642. "Connection: close\r\n"
  19643. "\r\n";
  19644. std::string out;
  19645. ASSERT_TRUE(send_request(5, raw_req, &out));
  19646. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19647. // Header parser trims surrounding whitespace of the header value
  19648. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19649. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19650. }
  19651. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19652. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19653. // their own X-Forwarded-For as a separate field line rather than extending the
  19654. // one the client sent, so every occurrence has to be taken into account.
  19655. // Reading only the first one hands back the address the client chose.
  19656. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19657. Server svr;
  19658. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19659. std::string observed_remote_addr;
  19660. size_t observed_xff_count = 0;
  19661. svr.Get("/ip", [&](const Request &req, Response &res) {
  19662. observed_remote_addr = req.remote_addr;
  19663. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19664. res.set_content("ok", "text/plain");
  19665. });
  19666. auto port = svr.bind_to_any_port(HOST);
  19667. thread t = thread([&]() { svr.listen_after_bind(); });
  19668. auto se = detail::scope_exit([&] {
  19669. svr.stop();
  19670. t.join();
  19671. ASSERT_FALSE(svr.is_running());
  19672. });
  19673. svr.wait_until_ready();
  19674. // The client supplies the first field line; the trusted proxy appends the
  19675. // address it observed as a second one.
  19676. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19677. "Host: localhost\r\n"
  19678. "X-Forwarded-For: 1.2.3.4\r\n"
  19679. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19680. "Connection: close\r\n"
  19681. "\r\n";
  19682. std::string out;
  19683. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19684. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19685. EXPECT_EQ(observed_xff_count, 2U);
  19686. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19687. // The same chain spread over one field line per hop derives the same client
  19688. // address, i.e. the split and the comma-joined representations agree.
  19689. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19690. "Host: localhost\r\n"
  19691. "X-Forwarded-For: 1.2.3.4\r\n"
  19692. "X-Forwarded-For: 198.51.100.23\r\n"
  19693. "X-Forwarded-For: 192.0.2.45\r\n"
  19694. "Connection: close\r\n"
  19695. "\r\n";
  19696. out.clear();
  19697. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19698. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19699. EXPECT_EQ(observed_xff_count, 3U);
  19700. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19701. }
  19702. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19703. // crash the server (it used to call front() on an empty vector inside
  19704. // get_client_ip). The connection-level remote address must be retained instead.
  19705. static void run_malformed_xff_test(const std::string &xff_value) {
  19706. Server svr;
  19707. svr.set_trusted_proxies({"192.0.2.45"});
  19708. std::string observed_remote_addr;
  19709. svr.Get("/ip", [&](const Request &req, Response &res) {
  19710. observed_remote_addr = req.remote_addr;
  19711. res.set_content("ok", "text/plain");
  19712. });
  19713. int port = 0;
  19714. thread t = thread([&]() {
  19715. port = svr.bind_to_any_port(HOST);
  19716. svr.listen_after_bind();
  19717. });
  19718. auto se = detail::scope_exit([&] {
  19719. svr.stop();
  19720. t.join();
  19721. ASSERT_FALSE(svr.is_running());
  19722. });
  19723. svr.wait_until_ready();
  19724. Client cli(HOST, port);
  19725. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19727. EXPECT_EQ(StatusCode::OK_200, res->status);
  19728. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19729. observed_remote_addr == "127.0.0.1");
  19730. }
  19731. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19732. run_malformed_xff_test("");
  19733. }
  19734. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19735. run_malformed_xff_test(",");
  19736. }
  19737. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19738. run_malformed_xff_test(", , ,");
  19739. }
  19740. // The same rule applies to Accept: a request whose acceptable types are spread
  19741. // over several field lines must be negotiated against all of them.
  19742. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19743. // case-insensitive connection options. Comparing the whole field value against
  19744. // one option misses a client that sends several of them, and misses every
  19745. // casing but the one written in the comparison.
  19746. //
  19747. // Sends req, reads the response, then reuses the same socket for a second
  19748. // request to find out whether the server kept the connection.
  19749. static void probe_connection_reuse(int port, const std::string &req,
  19750. bool *announced_close, bool *reusable) {
  19751. auto error = Error::Success;
  19752. auto sock = detail::create_client_socket(
  19753. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19754. /*connection_timeout_sec=*/5, 0,
  19755. /*read_timeout_sec=*/1, 0,
  19756. /*write_timeout_sec=*/5, 0, std::string(), error);
  19757. ASSERT_NE(sock, INVALID_SOCKET);
  19758. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19759. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19760. "Host: localhost\r\n"
  19761. "Connection: close\r\n"
  19762. "\r\n";
  19763. std::string first_response;
  19764. std::string second_response;
  19765. detail::process_client_socket(
  19766. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19767. [&](Stream &strm) {
  19768. if (strm.write(req.data(), req.size()) !=
  19769. static_cast<ssize_t>(req.size())) {
  19770. return false;
  19771. }
  19772. char buf[512];
  19773. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19774. // Headers plus the two-byte body of the handler below
  19775. while (reader.getline()) {
  19776. first_response += reader.ptr();
  19777. if (first_response.find("ok") != std::string::npos) { break; }
  19778. }
  19779. if (strm.write(second.data(), second.size()) !=
  19780. static_cast<ssize_t>(second.size())) {
  19781. return true;
  19782. }
  19783. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19784. while (reader2.getline()) {
  19785. second_response += reader2.ptr();
  19786. if (second_response.find("ok") != std::string::npos) { break; }
  19787. }
  19788. return true;
  19789. });
  19790. *announced_close =
  19791. first_response.find("Connection: close") != std::string::npos;
  19792. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19793. }
  19794. class ConnectionTokenTest : public ::testing::Test {
  19795. protected:
  19796. void SetUp() override {
  19797. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19798. res.set_content("ok", "text/plain");
  19799. });
  19800. port_ = svr_.bind_to_any_port(HOST);
  19801. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19802. svr_.wait_until_ready();
  19803. }
  19804. void TearDown() override {
  19805. svr_.stop();
  19806. if (thread_.joinable()) { thread_.join(); }
  19807. }
  19808. Server svr_;
  19809. int port_ = 0;
  19810. thread thread_;
  19811. };
  19812. // "close" alongside another option still closes the connection, and the
  19813. // response says so rather than leaving the peer to discover it.
  19814. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19815. bool announced_close = false;
  19816. bool reusable = true;
  19817. probe_connection_reuse(port_,
  19818. "GET /keepalive HTTP/1.1\r\n"
  19819. "Host: localhost\r\n"
  19820. "Connection: keep-alive, close\r\n"
  19821. "\r\n",
  19822. &announced_close, &reusable);
  19823. EXPECT_TRUE(announced_close);
  19824. EXPECT_FALSE(reusable);
  19825. }
  19826. // "close" split over two field lines is the same list, so it is honored too.
  19827. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19828. bool announced_close = false;
  19829. bool reusable = true;
  19830. probe_connection_reuse(port_,
  19831. "GET /keepalive HTTP/1.1\r\n"
  19832. "Host: localhost\r\n"
  19833. "Connection: keep-alive\r\n"
  19834. "Connection: close\r\n"
  19835. "\r\n",
  19836. &announced_close, &reusable);
  19837. EXPECT_TRUE(announced_close);
  19838. EXPECT_FALSE(reusable);
  19839. }
  19840. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19841. // keep-alive in the spelling everyone actually sends keeps its connection.
  19842. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19843. bool announced_close = false;
  19844. bool reusable = false;
  19845. probe_connection_reuse(port_,
  19846. "GET /keepalive HTTP/1.0\r\n"
  19847. "Host: localhost\r\n"
  19848. "Connection: keep-alive\r\n"
  19849. "\r\n",
  19850. &announced_close, &reusable);
  19851. EXPECT_FALSE(announced_close);
  19852. EXPECT_TRUE(reusable);
  19853. }
  19854. // A token the value merely contains is not the token itself.
  19855. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19856. bool announced_close = false;
  19857. bool reusable = false;
  19858. probe_connection_reuse(port_,
  19859. "GET /keepalive HTTP/1.1\r\n"
  19860. "Host: localhost\r\n"
  19861. "Connection: notclose\r\n"
  19862. "\r\n",
  19863. &announced_close, &reusable);
  19864. EXPECT_FALSE(announced_close);
  19865. EXPECT_TRUE(reusable);
  19866. }
  19867. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19868. Server svr;
  19869. std::vector<std::string> observed_types;
  19870. svr.Get("/", [&](const Request &req, Response &res) {
  19871. observed_types = req.accept_content_types;
  19872. res.set_content("ok", "text/plain");
  19873. });
  19874. auto port = svr.bind_to_any_port(HOST);
  19875. thread t = thread([&]() { svr.listen_after_bind(); });
  19876. auto se = detail::scope_exit([&] {
  19877. svr.stop();
  19878. t.join();
  19879. ASSERT_FALSE(svr.is_running());
  19880. });
  19881. svr.wait_until_ready();
  19882. Client cli(HOST, port);
  19883. Headers headers;
  19884. headers.emplace("Accept", "text/plain;q=0.5");
  19885. headers.emplace("Accept", "application/json");
  19886. auto res = cli.Get("/", headers);
  19887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19888. EXPECT_EQ(StatusCode::OK_200, res->status);
  19889. // Sorted by q-value, so the second field line's type comes first
  19890. ASSERT_EQ(2U, observed_types.size());
  19891. EXPECT_EQ("application/json", observed_types[0]);
  19892. EXPECT_EQ("text/plain", observed_types[1]);
  19893. }
  19894. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19895. // empty field line must not contribute a bare comma to the combined value.
  19896. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19897. Server svr;
  19898. std::vector<std::string> observed_types;
  19899. svr.Get("/", [&](const Request &req, Response &res) {
  19900. observed_types = req.accept_content_types;
  19901. res.set_content("ok", "text/plain");
  19902. });
  19903. auto port = svr.bind_to_any_port(HOST);
  19904. thread t = thread([&]() { svr.listen_after_bind(); });
  19905. auto se = detail::scope_exit([&] {
  19906. svr.stop();
  19907. t.join();
  19908. ASSERT_FALSE(svr.is_running());
  19909. });
  19910. svr.wait_until_ready();
  19911. // Empty first field line, then a real one
  19912. std::string raw_req = "GET / HTTP/1.1\r\n"
  19913. "Host: localhost\r\n"
  19914. "Accept:\r\n"
  19915. "Accept: application/json\r\n"
  19916. "Connection: close\r\n"
  19917. "\r\n";
  19918. std::string out;
  19919. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19920. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19921. ASSERT_EQ(1U, observed_types.size());
  19922. EXPECT_EQ("application/json", observed_types[0]);
  19923. }
  19924. // The skip in get_combined_header_value() is what keeps an empty field line
  19925. // from contributing a bare comma. Only a trailing empty field line exercises
  19926. // it: a leading one is already covered by the "combined is still empty" check,
  19927. // and parse_accept_header() now ignores the empty element either way, so the
  19928. // request-level test above can no longer tell the two apart.
  19929. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19930. Headers headers;
  19931. headers.emplace("Accept", "text/html");
  19932. headers.emplace("Accept", "");
  19933. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19934. headers.clear();
  19935. headers.emplace("Accept", "");
  19936. headers.emplace("Accept", "application/json");
  19937. EXPECT_EQ("application/json",
  19938. detail::get_combined_header_value(headers, "Accept"));
  19939. }
  19940. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19941. // An encoding offered on a later Accept-Encoding field line is still offered.
  19942. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19943. Server svr;
  19944. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19945. res.set_content(std::string(1024, 'x'), "text/plain");
  19946. });
  19947. auto port = svr.bind_to_any_port(HOST);
  19948. thread t = thread([&]() { svr.listen_after_bind(); });
  19949. auto se = detail::scope_exit([&] {
  19950. svr.stop();
  19951. t.join();
  19952. ASSERT_FALSE(svr.is_running());
  19953. });
  19954. svr.wait_until_ready();
  19955. Client cli(HOST, port);
  19956. cli.set_decompress(false);
  19957. Headers headers;
  19958. headers.emplace("Accept-Encoding", "identity");
  19959. headers.emplace("Accept-Encoding", "gzip");
  19960. auto res = cli.Get("/", headers);
  19961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19962. EXPECT_EQ(StatusCode::OK_200, res->status);
  19963. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19964. }
  19965. #endif
  19966. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19967. // Transfer-Encoding is not its body.
  19968. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19969. Server svr;
  19970. svr.set_payload_max_length(8);
  19971. svr.Post("/test", [](const Request &, Response &res) {
  19972. res.set_content("ok", "text/plain");
  19973. });
  19974. auto port = svr.bind_to_any_port(HOST);
  19975. ASSERT_GT(port, 0);
  19976. thread t = thread([&] { svr.listen_after_bind(); });
  19977. auto se = detail::scope_exit([&] {
  19978. svr.stop();
  19979. t.join();
  19980. ASSERT_FALSE(svr.is_running());
  19981. });
  19982. svr.wait_until_ready();
  19983. std::string resp;
  19984. ASSERT_TRUE(send_request(1,
  19985. "POST /test HTTP/1.1\r\n"
  19986. "Host: localhost\r\n"
  19987. "Connection: close\r\n"
  19988. "\r\n" +
  19989. std::string(16, 'X'),
  19990. &resp, port));
  19991. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19992. }
  19993. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19994. Server svr;
  19995. svr.Post("/post", [&](const Request &req, Response &res) {
  19996. res.set_content(req.body, "text/plain");
  19997. });
  19998. svr.Put("/put", [&](const Request &req, Response &res) {
  19999. res.set_content(req.body, "text/plain");
  20000. });
  20001. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20002. res.set_content(req.body, "text/plain");
  20003. });
  20004. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20005. res.set_content(req.body, "text/plain");
  20006. });
  20007. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20008. auto se = detail::scope_exit([&] {
  20009. svr.stop();
  20010. t.join();
  20011. ASSERT_FALSE(svr.is_running());
  20012. });
  20013. svr.wait_until_ready();
  20014. std::string resp;
  20015. // POST without Content-Length
  20016. ASSERT_TRUE(send_request(5,
  20017. "POST /post HTTP/1.1\r\n"
  20018. "Host: localhost\r\n"
  20019. "Connection: close\r\n"
  20020. "\r\n",
  20021. &resp));
  20022. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20023. // PUT without Content-Length
  20024. resp.clear();
  20025. ASSERT_TRUE(send_request(5,
  20026. "PUT /put HTTP/1.1\r\n"
  20027. "Host: localhost\r\n"
  20028. "Connection: close\r\n"
  20029. "\r\n",
  20030. &resp));
  20031. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20032. // PATCH without Content-Length
  20033. resp.clear();
  20034. ASSERT_TRUE(send_request(5,
  20035. "PATCH /patch HTTP/1.1\r\n"
  20036. "Host: localhost\r\n"
  20037. "Connection: close\r\n"
  20038. "\r\n",
  20039. &resp));
  20040. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20041. // DELETE without Content-Length
  20042. resp.clear();
  20043. ASSERT_TRUE(send_request(5,
  20044. "DELETE /delete HTTP/1.1\r\n"
  20045. "Host: localhost\r\n"
  20046. "Connection: close\r\n"
  20047. "\r\n",
  20048. &resp));
  20049. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20050. }
  20051. //==============================================================================
  20052. // open_stream() Tests
  20053. //==============================================================================
  20054. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20055. std::string result;
  20056. char buf[8192];
  20057. ssize_t n;
  20058. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20059. result.append(buf, static_cast<size_t>(n));
  20060. }
  20061. return result;
  20062. }
  20063. // Mock stream for unit tests
  20064. class MockStream : public Stream {
  20065. public:
  20066. std::string data;
  20067. size_t pos = 0;
  20068. ssize_t error_after = -1; // -1 = no error
  20069. explicit MockStream(const std::string &d, ssize_t err = -1)
  20070. : data(d), error_after(err) {}
  20071. bool is_readable() const override { return true; }
  20072. bool wait_readable() const override { return true; }
  20073. bool wait_writable() const override { return true; }
  20074. ssize_t read(char *ptr, size_t size) override {
  20075. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20076. if (pos >= data.size()) return 0;
  20077. size_t limit =
  20078. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20079. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20080. std::memcpy(ptr, data.data() + pos, to_read);
  20081. pos += to_read;
  20082. return static_cast<ssize_t>(to_read);
  20083. }
  20084. ssize_t write(const char *, size_t) override { return -1; }
  20085. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20086. ip = "127.0.0.1";
  20087. port = 0;
  20088. }
  20089. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20090. ip = "127.0.0.1";
  20091. port = 0;
  20092. }
  20093. socket_t socket() const override { return INVALID_SOCKET; }
  20094. time_t duration() const override { return 0; }
  20095. };
  20096. TEST(StreamHandleTest, Basic) {
  20097. ClientImpl::StreamHandle handle;
  20098. EXPECT_FALSE(handle.is_valid());
  20099. handle.response = detail::make_unique<Response>();
  20100. handle.error = Error::Connection;
  20101. EXPECT_FALSE(handle.is_valid());
  20102. handle.error = Error::Success;
  20103. EXPECT_TRUE(handle.is_valid());
  20104. }
  20105. TEST(BodyReaderTest, Basic) {
  20106. MockStream stream("Hello, World!");
  20107. detail::BodyReader reader;
  20108. reader.stream = &stream;
  20109. reader.content_length = 13;
  20110. char buf[32];
  20111. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20112. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20113. EXPECT_TRUE(reader.eof);
  20114. }
  20115. TEST(BodyReaderTest, NoStream) {
  20116. detail::BodyReader reader;
  20117. char buf[32];
  20118. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20119. EXPECT_EQ(Error::Connection, reader.last_error);
  20120. }
  20121. TEST(BodyReaderTest, Error) {
  20122. MockStream stream("Hello, World!", 5);
  20123. detail::BodyReader reader;
  20124. reader.stream = &stream;
  20125. reader.content_length = 13;
  20126. char buf[32];
  20127. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20128. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20129. EXPECT_EQ(Error::Read, reader.last_error);
  20130. }
  20131. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20132. // Mock-based StreamHandle tests relying on private internals are removed.
  20133. class OpenStreamTest : public ::testing::Test {
  20134. protected:
  20135. void SetUp() override {
  20136. svr_.Get("/hello", [](const Request &, Response &res) {
  20137. res.set_content("Hello World!", "text/plain");
  20138. });
  20139. svr_.Get("/large", [](const Request &, Response &res) {
  20140. res.set_content(std::string(10000, 'X'), "text/plain");
  20141. });
  20142. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20143. res.set_content("Hello World!", "image/jpeg");
  20144. res.set_header("Content-Encoding", "UTF-8");
  20145. });
  20146. svr_.Get("/chunked", [](const Request &, Response &res) {
  20147. res.set_chunked_content_provider("text/plain",
  20148. [](size_t offset, DataSink &sink) {
  20149. if (offset < 15) {
  20150. sink.write("chunk", 5);
  20151. return true;
  20152. }
  20153. sink.done();
  20154. return true;
  20155. });
  20156. });
  20157. svr_.Get("/compressible", [](const Request &, Response &res) {
  20158. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20159. DataSink &sink) {
  20160. if (offset < 100 * 1024) {
  20161. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20162. sink.write(chunk.data(), chunk.size());
  20163. return true;
  20164. }
  20165. sink.done();
  20166. return true;
  20167. });
  20168. });
  20169. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20170. [](const Request & /*req*/, Response &res) {
  20171. auto i = new int(0);
  20172. res.set_header("Trailer", "Content-Length, X-Allowed");
  20173. res.set_chunked_content_provider(
  20174. "text/plain",
  20175. [i](size_t /*offset*/, DataSink &sink) {
  20176. switch (*i) {
  20177. case 0: sink.os << "123"; break;
  20178. case 1: sink.os << "456"; break;
  20179. case 2: sink.os << "789"; break;
  20180. case 3: {
  20181. sink.done_with_trailer(
  20182. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20183. } break;
  20184. }
  20185. (*i)++;
  20186. return true;
  20187. },
  20188. [i](bool success) {
  20189. EXPECT_TRUE(success);
  20190. delete i;
  20191. });
  20192. });
  20193. // Echo headers endpoint for header-related tests
  20194. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20195. std::string body;
  20196. for (const auto &h : req.headers) {
  20197. body.append(h.first);
  20198. body.push_back(':');
  20199. body.append(h.second);
  20200. body.push_back('\n');
  20201. }
  20202. res.set_content(body, "text/plain");
  20203. });
  20204. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20205. std::string body;
  20206. for (const auto &h : req.headers) {
  20207. body.append(h.first);
  20208. body.push_back(':');
  20209. body.append(h.second);
  20210. body.push_back('\n');
  20211. }
  20212. res.set_content(body, "text/plain");
  20213. });
  20214. port_ = svr_.bind_to_any_port("127.0.0.1");
  20215. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20216. svr_.wait_until_ready();
  20217. }
  20218. void TearDown() override {
  20219. svr_.stop();
  20220. if (thread_.joinable()) thread_.join();
  20221. }
  20222. Server svr_;
  20223. std::thread thread_;
  20224. int port_ = 0;
  20225. };
  20226. TEST_F(OpenStreamTest, Basic) {
  20227. Client cli("127.0.0.1", port_);
  20228. auto handle = cli.open_stream("GET", "/hello");
  20229. EXPECT_TRUE(handle.is_valid());
  20230. EXPECT_EQ("Hello World!", read_all(handle));
  20231. }
  20232. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20233. Client cli("127.0.0.1", port_);
  20234. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20235. ASSERT_TRUE(handle.is_valid());
  20236. EXPECT_EQ("Hello World!", read_all(handle));
  20237. }
  20238. TEST_F(OpenStreamTest, SmallBuffer) {
  20239. Client cli("127.0.0.1", port_);
  20240. auto handle = cli.open_stream("GET", "/hello");
  20241. std::string result;
  20242. char buf[4];
  20243. ssize_t n;
  20244. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20245. result.append(buf, static_cast<size_t>(n));
  20246. EXPECT_EQ("Hello World!", result);
  20247. }
  20248. TEST_F(OpenStreamTest, DefaultHeaders) {
  20249. Client cli("127.0.0.1", port_);
  20250. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20251. {
  20252. auto handle = cli.open_stream("GET", "/echo-headers");
  20253. ASSERT_TRUE(handle.is_valid());
  20254. auto body = read_all(handle);
  20255. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20256. std::string::npos);
  20257. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20258. std::string::npos);
  20259. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20260. }
  20261. // open_stream POST with body and no explicit content_type should NOT add
  20262. // text/plain Content-Type (behavior differs from non-streaming path), but
  20263. // should include Content-Length
  20264. {
  20265. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20266. ASSERT_TRUE(handle.is_valid());
  20267. auto body = read_all(handle);
  20268. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20269. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20270. }
  20271. // open_stream POST with explicit Content-Type should preserve it
  20272. {
  20273. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20274. {{"Content-Type", "application/custom"}},
  20275. "{}", "application/custom");
  20276. ASSERT_TRUE(handle.is_valid());
  20277. auto body = read_all(handle);
  20278. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20279. }
  20280. // User-specified User-Agent must not be overwritten for stream API
  20281. {
  20282. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20283. {{"User-Agent", "MyAgent/1.2"}});
  20284. ASSERT_TRUE(handle.is_valid());
  20285. auto body = read_all(handle);
  20286. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20287. }
  20288. }
  20289. TEST_F(OpenStreamTest, Large) {
  20290. Client cli("127.0.0.1", port_);
  20291. auto handle = cli.open_stream("GET", "/large");
  20292. EXPECT_EQ(10000u, read_all(handle).size());
  20293. }
  20294. TEST_F(OpenStreamTest, ConnectionError) {
  20295. Client cli("127.0.0.1", 9999);
  20296. auto handle = cli.open_stream("GET", "/hello");
  20297. EXPECT_FALSE(handle.is_valid());
  20298. }
  20299. TEST_F(OpenStreamTest, Chunked) {
  20300. Client cli("127.0.0.1", port_);
  20301. auto handle = cli.open_stream("GET", "/chunked");
  20302. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20303. "Transfer-Encoding") == "chunked");
  20304. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20305. }
  20306. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20307. Client cli("127.0.0.1", port_);
  20308. auto handle =
  20309. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20310. ASSERT_TRUE(handle.is_valid());
  20311. // Consume body to allow trailers to be received/parsed
  20312. auto body = read_all(handle);
  20313. // Explicitly parse trailers (ensure trailers are available for assertion)
  20314. handle.parse_trailers_if_needed();
  20315. EXPECT_EQ(std::string("123456789"), body);
  20316. // The response should include a Trailer header declaring both names
  20317. ASSERT_TRUE(handle.response);
  20318. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20319. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20320. handle.response->get_header_value("Trailer"));
  20321. // Prohibited trailer must not be present
  20322. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20323. // Allowed trailer should be present
  20324. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20325. EXPECT_EQ(std::string("yes"),
  20326. handle.response->get_trailer_value("X-Allowed"));
  20327. // Verify trailers are NOT present as regular headers
  20328. EXPECT_EQ(std::string(""),
  20329. handle.response->get_header_value("Content-Length"));
  20330. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20331. }
  20332. // Accepts one connection on an OS-assigned port, which it hands over through
  20333. // port_promise, reads the request head and sends back response. after_send,
  20334. // if given, runs on the connection before it is closed.
  20335. static std::thread
  20336. serve_single_response(std::promise<int> &port_promise,
  20337. const std::string &response,
  20338. std::function<void(socket_t)> after_send = nullptr) {
  20339. return std::thread([&port_promise, response, after_send] {
  20340. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20341. default_socket_options(srv);
  20342. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20343. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20344. sockaddr_in addr{};
  20345. addr.sin_family = AF_INET;
  20346. addr.sin_port = htons(0); // Let OS assign a free port
  20347. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20348. int opt = 1;
  20349. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20350. #ifdef _WIN32
  20351. reinterpret_cast<const char *>(&opt),
  20352. #else
  20353. &opt,
  20354. #endif
  20355. sizeof(opt));
  20356. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20357. ::listen(srv, 1) != 0) {
  20358. port_promise.set_value(-1);
  20359. detail::close_socket(srv);
  20360. return;
  20361. }
  20362. socklen_t addr_len = sizeof(addr);
  20363. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20364. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20365. sockaddr_in cli_addr{};
  20366. socklen_t cli_len = sizeof(cli_addr);
  20367. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20368. if (cli != INVALID_SOCKET) {
  20369. // Read the complete HTTP request (until the blank line that terminates
  20370. // headers) before sending the response. If the server closes the socket
  20371. // while the client's request data is still unread in the kernel receive
  20372. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20373. // connection on both sides: it discards the client's receive buffer
  20374. // (which already holds our response) and causes any in-progress write on
  20375. // the client to fail with ECONNRESET. Reading all request data first
  20376. // ensures close() emits a graceful FIN.
  20377. {
  20378. char rbuf[256];
  20379. std::string req;
  20380. while (req.find("\r\n\r\n") == std::string::npos) {
  20381. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20382. if (n <= 0) { break; }
  20383. req.append(rbuf, static_cast<size_t>(n));
  20384. }
  20385. }
  20386. ::send(cli,
  20387. #ifdef _WIN32
  20388. static_cast<const char *>(response.c_str()),
  20389. static_cast<int>(response.size()),
  20390. #else
  20391. response.c_str(), response.size(),
  20392. #endif
  20393. 0);
  20394. if (after_send) { after_send(cli); }
  20395. detail::close_socket(cli);
  20396. }
  20397. detail::close_socket(srv);
  20398. });
  20399. }
  20400. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20401. #ifndef _WIN32
  20402. signal(SIGPIPE, SIG_IGN);
  20403. #endif
  20404. std::promise<int> port_promise;
  20405. auto port_future = port_promise.get_future();
  20406. auto server_thread =
  20407. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20408. "Content-Type: text/plain\r\n"
  20409. "Content-Length: not-a-number\r\n"
  20410. "Connection: close\r\n"
  20411. "\r\n"
  20412. "hello");
  20413. auto port = port_future.get();
  20414. ASSERT_GT(port, 0);
  20415. Client cli("127.0.0.1", port);
  20416. auto handle = cli.open_stream("GET", "/");
  20417. EXPECT_FALSE(handle.is_valid());
  20418. server_thread.join();
  20419. }
  20420. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20421. #ifndef _WIN32
  20422. signal(SIGPIPE, SIG_IGN);
  20423. #endif
  20424. std::promise<int> port_promise;
  20425. auto port_future = port_promise.get_future();
  20426. auto server_thread = serve_single_response(
  20427. port_promise, "HTTP/1.1 200 OK\r\n"
  20428. "Content-Type: text/plain\r\n"
  20429. "Content-Length: 99999999999999999999999999\r\n"
  20430. "Connection: close\r\n"
  20431. "\r\n"
  20432. "hello");
  20433. auto port = port_future.get();
  20434. ASSERT_GT(port, 0);
  20435. // Historically std::stoull would throw std::out_of_range here and crash
  20436. // the process, then parsing silently clamped to a bogus framing length and
  20437. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20438. // so the stream fails to open, matching the not-a-number case above. The
  20439. // process still must NOT terminate.
  20440. Client cli("127.0.0.1", port);
  20441. auto handle = cli.open_stream("GET", "/");
  20442. EXPECT_FALSE(handle.is_valid());
  20443. server_thread.join();
  20444. }
  20445. #ifndef _WIN32
  20446. // As above for the body of a streamed request: a send() cut short by the write
  20447. // timeout must not leave the rest of the body unsent.
  20448. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20449. signal(SIGPIPE, SIG_IGN);
  20450. Server svr;
  20451. svr.set_socket_options([](socket_t sock) {
  20452. int size = 8192;
  20453. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20454. reinterpret_cast<const char *>(&size), sizeof(size));
  20455. });
  20456. svr.Post("/size", [](const Request &, Response &res,
  20457. const ContentReader &content_reader) {
  20458. // Outlast the client's write timeout before reading the body.
  20459. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20460. size_t received = 0;
  20461. content_reader([&](const char *, size_t len) {
  20462. received += len;
  20463. return true;
  20464. });
  20465. res.set_content(std::to_string(received), "text/plain");
  20466. });
  20467. auto port = svr.bind_to_any_port(HOST);
  20468. std::thread t([&]() { svr.listen_after_bind(); });
  20469. auto se = detail::scope_exit([&] {
  20470. svr.stop();
  20471. t.join();
  20472. });
  20473. svr.wait_until_ready();
  20474. Client cli(HOST, port);
  20475. cli.set_write_timeout(0, 500000);
  20476. cli.set_socket_options([](socket_t sock) {
  20477. int size = 8192;
  20478. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20479. reinterpret_cast<const char *>(&size), sizeof(size));
  20480. });
  20481. const std::string body(4 * 1024 * 1024, 'A');
  20482. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20483. "application/octet-stream");
  20484. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20485. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20486. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20487. }
  20488. #endif
  20489. // Serves `response` to the single request `fn` makes with a fresh client.
  20490. template <typename Fn>
  20491. static void with_single_response(const std::string &response, Fn fn) {
  20492. #ifndef _WIN32
  20493. signal(SIGPIPE, SIG_IGN);
  20494. #endif
  20495. std::promise<int> port_promise;
  20496. auto port_future = port_promise.get_future();
  20497. auto server_thread = serve_single_response(port_promise, response);
  20498. auto se = detail::scope_exit([&] { server_thread.join(); });
  20499. auto port = port_future.get();
  20500. ASSERT_GT(port, 0);
  20501. Client cli("127.0.0.1", port);
  20502. fn(cli);
  20503. }
  20504. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20505. // too, also in a build without the decoder for the advertised coding.
  20506. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20507. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20508. const auto response = "HTTP/1.1 200 OK\r\n"
  20509. "Content-Encoding: gzip\r\n"
  20510. "Content-Length: " +
  20511. std::to_string(gzipped.size()) +
  20512. "\r\n"
  20513. "Connection: close\r\n\r\n" +
  20514. gzipped;
  20515. with_single_response(response, [&](Client &cli) {
  20516. cli.set_decompress(false);
  20517. auto handle = cli.open_stream("GET", "/");
  20518. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20519. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20520. EXPECT_EQ(gzipped, read_all(handle));
  20521. EXPECT_FALSE(handle.has_read_error());
  20522. });
  20523. with_single_response(response, [&](Client &cli) {
  20524. cli.set_decompress(false);
  20525. auto res = stream::Get(cli, "/", 7);
  20526. ASSERT_TRUE(res) << to_string(res.error());
  20527. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20528. EXPECT_EQ(gzipped, res.read_all());
  20529. EXPECT_FALSE(res.has_read_error());
  20530. });
  20531. }
  20532. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20533. // Neither Content-Length nor chunked: the body ends at the close
  20534. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20535. "Connection: close\r\n"
  20536. "\r\n"
  20537. "hello";
  20538. with_single_response(close_delimited, [](Client &cli) {
  20539. auto handle = cli.open_stream("GET", "/");
  20540. ASSERT_TRUE(handle.is_valid());
  20541. EXPECT_EQ("hello", read_all(handle));
  20542. EXPECT_FALSE(handle.has_read_error());
  20543. });
  20544. // A close before the end of the Content-Length is still an error
  20545. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20546. "Content-Length: 10\r\n"
  20547. "\r\n"
  20548. "hello";
  20549. with_single_response(short_content_length, [](Client &cli) {
  20550. auto handle = cli.open_stream("GET", "/");
  20551. ASSERT_TRUE(handle.is_valid());
  20552. read_all(handle);
  20553. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20554. });
  20555. // So is a close before the last chunk
  20556. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20557. "Transfer-Encoding: chunked\r\n"
  20558. "\r\n"
  20559. "5\r\nhello\r\n";
  20560. with_single_response(short_chunked, [](Client &cli) {
  20561. auto handle = cli.open_stream("GET", "/");
  20562. ASSERT_TRUE(handle.is_valid());
  20563. read_all(handle);
  20564. EXPECT_TRUE(handle.has_read_error());
  20565. });
  20566. }
  20567. #ifdef CPPHTTPLIB_SSL_ENABLED
  20568. // Serves `response` to one request, then closes with or without a close_notify
  20569. template <typename Fn>
  20570. static void with_single_tls_response(const std::string &response,
  20571. bool close_notify, Fn fn) {
  20572. #ifndef _WIN32
  20573. signal(SIGPIPE, SIG_IGN);
  20574. #endif
  20575. std::promise<int> port_promise;
  20576. auto port_future = port_promise.get_future();
  20577. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20578. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20579. default_socket_options(srv);
  20580. sockaddr_in addr{};
  20581. addr.sin_family = AF_INET;
  20582. addr.sin_port = htons(0);
  20583. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20584. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20585. ::listen(srv, 1) != 0) {
  20586. port_promise.set_value(-1);
  20587. detail::close_socket(srv);
  20588. return;
  20589. }
  20590. socklen_t addr_len = sizeof(addr);
  20591. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20592. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20593. auto cli = ::accept(srv, nullptr, nullptr);
  20594. if (cli != INVALID_SOCKET) {
  20595. auto ctx = tls::create_server_context();
  20596. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20597. nullptr);
  20598. auto session = tls::create_session(ctx, cli);
  20599. tls::TlsError err;
  20600. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20601. // The request head first, so that closing the socket sends a FIN
  20602. // rather than an RST for the unread bytes.
  20603. std::string req;
  20604. char buf[256];
  20605. while (req.find("\r\n\r\n") == std::string::npos) {
  20606. auto n = tls::read(session, buf, sizeof(buf), err);
  20607. if (n <= 0) { break; }
  20608. req.append(buf, static_cast<size_t>(n));
  20609. }
  20610. size_t sent = 0;
  20611. while (sent < response.size()) {
  20612. auto n = tls::write(session, response.data() + sent,
  20613. response.size() - sent, err);
  20614. if (n <= 0) { break; }
  20615. sent += static_cast<size_t>(n);
  20616. }
  20617. if (close_notify) { tls::shutdown(session, true); }
  20618. }
  20619. tls::free_session(session);
  20620. detail::close_socket(cli);
  20621. tls::free_context(ctx);
  20622. }
  20623. detail::close_socket(srv);
  20624. });
  20625. auto se = detail::scope_exit([&] { server_thread.join(); });
  20626. auto port = port_future.get();
  20627. ASSERT_GT(port, 0);
  20628. SSLClient cli("127.0.0.1", port);
  20629. cli.enable_server_certificate_verification(false);
  20630. fn(cli);
  20631. }
  20632. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20633. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20634. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20635. "Connection: close\r\n"
  20636. "\r\n"
  20637. "hello";
  20638. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20639. auto res = cli.Get("/");
  20640. ASSERT_TRUE(res) << to_string(res.error());
  20641. EXPECT_EQ("hello", res->body);
  20642. });
  20643. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20644. auto res = cli.Get("/");
  20645. ASSERT_FALSE(res);
  20646. EXPECT_EQ(Error::Read, res.error());
  20647. });
  20648. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20649. auto handle = cli.open_stream("GET", "/");
  20650. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20651. read_all(handle);
  20652. EXPECT_TRUE(handle.has_read_error());
  20653. });
  20654. // A framed body ends where its framing says, with or without the alert
  20655. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20656. "Content-Length: 5\r\n"
  20657. "Connection: close\r\n"
  20658. "\r\n"
  20659. "hello";
  20660. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20661. auto res = cli.Get("/");
  20662. ASSERT_TRUE(res) << to_string(res.error());
  20663. EXPECT_EQ("hello", res->body);
  20664. });
  20665. }
  20666. #endif
  20667. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20668. const char *responses[] = {
  20669. "HTTP/1.1 103 Early Hints\r\n"
  20670. "Link: </style.css>; rel=preload\r\n"
  20671. "\r\n"
  20672. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20673. "HTTP/1.1 100 Continue\r\n"
  20674. "X-Note: interim\r\n"
  20675. "\r\n"
  20676. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20677. };
  20678. for (auto response : responses) {
  20679. with_single_response(response, [](Client &cli) {
  20680. auto res = cli.Get("/");
  20681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20682. EXPECT_EQ(StatusCode::OK_200, res->status);
  20683. EXPECT_EQ("ok", res->body);
  20684. });
  20685. }
  20686. }
  20687. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20688. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20689. const std::string final_response =
  20690. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20691. std::string interims;
  20692. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20693. interims += interim;
  20694. }
  20695. with_single_response(interims + final_response, [](Client &cli) {
  20696. auto res = cli.Get("/");
  20697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20698. EXPECT_EQ("ok", res->body);
  20699. });
  20700. with_single_response(interims + interim + final_response, [](Client &cli) {
  20701. auto res = cli.Get("/");
  20702. ASSERT_FALSE(res);
  20703. EXPECT_EQ(Error::Read, res.error());
  20704. });
  20705. }
  20706. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20707. #ifndef _WIN32
  20708. signal(SIGPIPE, SIG_IGN);
  20709. #endif
  20710. // The server answers the head without asking for the body. Bytes it then
  20711. // reads on the connection would be taken for the body the request declared.
  20712. auto closed_by_client = false;
  20713. std::promise<int> port_promise;
  20714. auto server_thread = serve_single_response(
  20715. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20716. [&](socket_t sock) {
  20717. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20718. char buf[256];
  20719. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20720. });
  20721. Client cli("127.0.0.1", port_promise.get_future().get());
  20722. cli.set_keep_alive(true);
  20723. cli.set_read_timeout(1, 0);
  20724. // Long enough for the client to send Expect: 100-continue.
  20725. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20727. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20728. cli.Get("/second");
  20729. server_thread.join();
  20730. EXPECT_TRUE(closed_by_client);
  20731. }
  20732. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20733. // Long enough for the client to send Expect: 100-continue
  20734. with_single_response(
  20735. "HTTP/1.1 103 Early Hints\r\n"
  20736. "Link: </style.css>; rel=preload\r\n"
  20737. "\r\n"
  20738. "HTTP/1.1 401 Unauthorized\r\n"
  20739. "Content-Length: 0\r\n\r\n",
  20740. [](Client &cli) {
  20741. cli.set_read_timeout(2, 0);
  20742. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20744. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20745. });
  20746. }
  20747. #ifdef CPPHTTPLIB_SSL_ENABLED
  20748. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20749. #ifndef _WIN32
  20750. signal(SIGPIPE, SIG_IGN);
  20751. #endif
  20752. auto reused = false;
  20753. std::promise<int> port_promise;
  20754. auto server_thread = serve_single_response(
  20755. port_promise,
  20756. "HTTP/1.1 401 Unauthorized\r\n"
  20757. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20758. "Content-Length: 0\r\n\r\n",
  20759. [&](socket_t sock) {
  20760. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20761. char buf[256];
  20762. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20763. });
  20764. Client cli("127.0.0.1", port_promise.get_future().get());
  20765. cli.set_keep_alive(true);
  20766. cli.set_digest_auth("user", "pass");
  20767. cli.set_read_timeout(1, 0);
  20768. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20769. server_thread.join();
  20770. EXPECT_FALSE(reused);
  20771. }
  20772. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20773. // Any other answer to CONNECT would read as the origin's response.
  20774. struct {
  20775. const char *response;
  20776. bool passed_on;
  20777. } cases[] = {
  20778. {"HTTP/1.1 201 Created\r\n"
  20779. "Set-Cookie: session=from-proxy\r\n"
  20780. "Content-Length: 0\r\n\r\n",
  20781. false},
  20782. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20783. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20784. "Content-Length: 0\r\n\r\n",
  20785. true},
  20786. };
  20787. for (const auto &c : cases) {
  20788. std::promise<int> port_promise;
  20789. auto server_thread = serve_single_response(port_promise, c.response);
  20790. SSLClient cli("example.com", 443);
  20791. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20792. auto res = cli.Get("/");
  20793. server_thread.join();
  20794. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20795. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20796. if (res) {
  20797. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20798. }
  20799. }
  20800. }
  20801. #endif
  20802. // Records the client's error logger calls as "error METHOD path", or
  20803. // "error null" for a call without a request
  20804. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20805. return [&log](const Error &err, const Request *req) {
  20806. log.push_back(to_string(err) + " " +
  20807. (req ? req->method + " " + req->path : "null"));
  20808. };
  20809. }
  20810. // A failed request is reported once, with the request the caller made
  20811. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20812. Server svr;
  20813. svr.Get("/big", [](const Request &, Response &res) {
  20814. res.set_content(std::string(100000, 'b'), "text/plain");
  20815. });
  20816. auto port = svr.bind_to_any_port(HOST);
  20817. std::thread t([&]() { svr.listen_after_bind(); });
  20818. auto se = detail::scope_exit([&] {
  20819. svr.stop();
  20820. t.join();
  20821. });
  20822. svr.wait_until_ready();
  20823. Client cli(HOST, port);
  20824. std::vector<std::string> log;
  20825. cli.set_error_logger(record_errors(log));
  20826. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20827. cli.Get("/big", [](const char *, size_t) { return false; });
  20828. EXPECT_EQ(expected, log);
  20829. log.clear();
  20830. cli.Get("/big", [](size_t, size_t) { return false; });
  20831. EXPECT_EQ(expected, log);
  20832. }
  20833. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20834. // Fails while the body is read
  20835. auto broken = [](const Request &, Response &res) {
  20836. res.set_content_provider(10, "text/plain",
  20837. [](size_t, size_t, DataSink &) { return false; });
  20838. };
  20839. Server other;
  20840. other.Get("/broken", broken);
  20841. auto other_port = other.bind_to_any_port(HOST);
  20842. std::thread other_t([&]() { other.listen_after_bind(); });
  20843. auto other_se = detail::scope_exit([&] {
  20844. other.stop();
  20845. other_t.join();
  20846. });
  20847. other.wait_until_ready();
  20848. Server svr;
  20849. svr.Get("/broken", broken);
  20850. svr.Get("/same-origin",
  20851. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20852. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20853. res.set_redirect("http://" + std::string(HOST) + ":" +
  20854. std::to_string(other_port) + "/broken");
  20855. });
  20856. auto port = svr.bind_to_any_port(HOST);
  20857. std::thread t([&]() { svr.listen_after_bind(); });
  20858. auto se = detail::scope_exit([&] {
  20859. svr.stop();
  20860. t.join();
  20861. });
  20862. svr.wait_until_ready();
  20863. Client cli(HOST, port);
  20864. cli.set_follow_location(true);
  20865. std::vector<std::string> log;
  20866. cli.set_error_logger(record_errors(log));
  20867. for (auto path : {"/same-origin", "/cross-origin"}) {
  20868. log.clear();
  20869. auto res = cli.Get(path);
  20870. ASSERT_FALSE(res);
  20871. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20872. log);
  20873. }
  20874. }
  20875. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20876. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20877. std::vector<std::string> log;
  20878. cli.set_error_logger(record_errors(log));
  20879. auto handle = cli.open_stream("GET", "/x");
  20880. EXPECT_FALSE(handle.is_valid());
  20881. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20882. log);
  20883. });
  20884. }
  20885. #ifdef CPPHTTPLIB_SSL_ENABLED
  20886. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20887. // Not a TLS server, so the handshake fails. It waits for a request line in
  20888. // the handshake bytes, so a short read timeout lets it close quickly.
  20889. Server svr;
  20890. svr.set_read_timeout(0, 100000);
  20891. svr.Get("/x", [](const Request &, Response &res) {
  20892. res.set_content("x", "text/plain");
  20893. });
  20894. auto port = svr.bind_to_any_port(HOST);
  20895. std::thread t([&]() { svr.listen_after_bind(); });
  20896. auto se = detail::scope_exit([&] {
  20897. svr.stop();
  20898. t.join();
  20899. });
  20900. svr.wait_until_ready();
  20901. std::vector<std::string> log;
  20902. SSLClient cli(HOST, port);
  20903. cli.enable_server_certificate_verification(false);
  20904. cli.set_error_logger(record_errors(log));
  20905. auto res = cli.Get("/x");
  20906. ASSERT_FALSE(res);
  20907. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20908. log.clear();
  20909. auto handle = cli.open_stream("GET", "/x");
  20910. EXPECT_FALSE(handle.is_valid());
  20911. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20912. log.clear();
  20913. SSLClient no_ca(HOST, port);
  20914. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20915. no_ca.set_error_logger(record_errors(log));
  20916. res = no_ca.Get("/x");
  20917. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20918. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20919. }
  20920. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20921. #ifndef _WIN32
  20922. signal(SIGPIPE, SIG_IGN);
  20923. #endif
  20924. // Refused, answered with a challenge, or closed without an answer
  20925. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20926. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20927. "Content-Length: 0\r\n\r\n",
  20928. ""}) {
  20929. std::promise<int> port_promise;
  20930. auto server_thread = serve_single_response(port_promise, response);
  20931. SSLClient cli("example.com", 443);
  20932. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20933. std::vector<std::string> log;
  20934. cli.set_error_logger(record_errors(log));
  20935. auto res = cli.Get("/");
  20936. server_thread.join();
  20937. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20938. << response;
  20939. }
  20940. }
  20941. #endif
  20942. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20943. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20944. // the chunked coding and drop Content-Length, so a front-end that trusts
  20945. // Content-Length would disagree about where the body ends (response
  20946. // smuggling). The client must reject such a response.
  20947. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20948. for (const char *te : {"chunked", "gzip, chunked"}) {
  20949. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20950. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20951. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20952. "5\r\nhello\r\n0\r\n\r\n";
  20953. with_single_response(response, [&](Client &cli) {
  20954. auto res = cli.Get("/");
  20955. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20956. EXPECT_EQ(Error::Read, res.error()) << te;
  20957. });
  20958. with_single_response(response, [&](Client &cli) {
  20959. auto handle = cli.open_stream("GET", "/");
  20960. EXPECT_FALSE(handle.is_valid()) << te;
  20961. EXPECT_EQ(Error::Read, handle.error) << te;
  20962. });
  20963. }
  20964. }
  20965. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20966. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20967. // closing the connection (unlike a request, which must be rejected).
  20968. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20969. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20970. "Transfer-Encoding: chunked\r\n"
  20971. "Connection: close\r\n"
  20972. "\r\n"
  20973. "5\r\nhello\r\n0\r\n\r\n",
  20974. "HTTP/1.1 200 OK\r\n"
  20975. "Transfer-Encoding: gzip\r\n"
  20976. "Connection: close\r\n"
  20977. "\r\n"
  20978. "hello"}) {
  20979. with_single_response(response, [&](Client &cli) {
  20980. auto res = cli.Get("/");
  20981. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20982. EXPECT_EQ("hello", res->body);
  20983. });
  20984. with_single_response(response, [&](Client &cli) {
  20985. auto handle = cli.open_stream("GET", "/");
  20986. ASSERT_TRUE(handle.is_valid()) << response;
  20987. EXPECT_EQ("hello", read_all(handle));
  20988. });
  20989. }
  20990. }
  20991. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20992. // framing headers describe nothing to read and must not be rejected.
  20993. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20994. const std::string framing = "Content-Length: 5\r\n"
  20995. "Transfer-Encoding: chunked\r\n"
  20996. "Connection: close\r\n"
  20997. "\r\n";
  20998. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20999. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21000. });
  21001. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21002. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21003. });
  21004. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21005. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21006. with_single_response(response, [&](Client &cli) {
  21007. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21008. });
  21009. with_single_response(response, [&](Client &cli) {
  21010. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21011. });
  21012. }
  21013. }
  21014. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21015. // header section, so a stream opened on one has nothing to read, whatever
  21016. // framing or coding headers it carries.
  21017. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21018. struct Case {
  21019. const char *method;
  21020. const char *status;
  21021. };
  21022. // A reader of the declared body reports an early close when nothing
  21023. // follows, and hands back what does.
  21024. struct Framing {
  21025. const char *headers;
  21026. const char *after;
  21027. };
  21028. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21029. Case{"GET", "304 Not Modified"}}) {
  21030. for (const auto &f :
  21031. {Framing{"Content-Length: 5\r\n", ""},
  21032. Framing{"Content-Length: 5\r\n", "hello"},
  21033. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21034. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21035. // Not decoded, so a build without Brotli opens it too
  21036. Framing{"Content-Encoding: br\r\n", ""}}) {
  21037. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21038. "Connection: close\r\n"
  21039. "\r\n" +
  21040. f.after;
  21041. with_single_response(response, [&](Client &cli) {
  21042. auto handle = cli.open_stream(c.method, "/");
  21043. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21044. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21045. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21046. });
  21047. }
  21048. }
  21049. }
  21050. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21051. // response, is faulty framing, so the connection is not reused after it.
  21052. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21053. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21054. "Content-Length: 0\r\n"
  21055. "Transfer-Encoding: chunked\r\n"
  21056. "\r\n"
  21057. "5\r\nhello\r\n0\r\n\r\n",
  21058. "HTTP/1.0 200 Connection established\r\n"
  21059. "Connection: keep-alive\r\n"
  21060. "Transfer-Encoding: chunked\r\n"
  21061. "\r\n"
  21062. "5\r\nhello\r\n0\r\n\r\n"}) {
  21063. with_single_response(response, [&](Client &cli) {
  21064. cli.set_keep_alive(true);
  21065. auto res = cli.Get("/");
  21066. ASSERT_TRUE(res) << response;
  21067. EXPECT_EQ("hello", res->body);
  21068. EXPECT_FALSE(cli.is_socket_open()) << response;
  21069. });
  21070. }
  21071. }
  21072. // A payload max length of 0 means no limit, however the body is framed.
  21073. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21074. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21075. "Transfer-Encoding: chunked\r\n"
  21076. "\r\n"
  21077. "5\r\nhello\r\n0\r\n\r\n",
  21078. "HTTP/1.1 200 OK\r\n"
  21079. "Connection: close\r\n"
  21080. "\r\n"
  21081. "hello"}) {
  21082. with_single_response(response, [&](Client &cli) {
  21083. cli.set_payload_max_length(0);
  21084. auto res = cli.Get("/");
  21085. ASSERT_TRUE(res) << response;
  21086. EXPECT_EQ("hello", res->body) << response;
  21087. });
  21088. }
  21089. }
  21090. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21091. Server svr;
  21092. svr.set_payload_max_length(0);
  21093. svr.Post("/echo", [](const Request &req, Response &res) {
  21094. res.set_content(req.body, "text/plain");
  21095. });
  21096. auto port = svr.bind_to_any_port(HOST);
  21097. thread t = thread([&] { svr.listen_after_bind(); });
  21098. auto se = detail::scope_exit([&] {
  21099. svr.stop();
  21100. t.join();
  21101. ASSERT_FALSE(svr.is_running());
  21102. });
  21103. svr.wait_until_ready();
  21104. Client cli(HOST, port);
  21105. auto res = cli.Post(
  21106. "/echo",
  21107. [](size_t /*offset*/, DataSink &sink) {
  21108. sink.write("hello", 5);
  21109. sink.done();
  21110. return true;
  21111. },
  21112. "text/plain");
  21113. ASSERT_TRUE(res);
  21114. EXPECT_EQ(StatusCode::OK_200, res->status);
  21115. EXPECT_EQ("hello", res->body);
  21116. }
  21117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21118. TEST_F(OpenStreamTest, Gzip) {
  21119. Client cli("127.0.0.1", port_);
  21120. auto handle = cli.open_stream("GET", "/compressible", {},
  21121. {{"Accept-Encoding", "gzip"}});
  21122. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21123. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21124. }
  21125. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21126. Client cli("127.0.0.1", port_);
  21127. auto handle =
  21128. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21129. {{"Accept-Encoding", "gzip"}});
  21130. ASSERT_TRUE(handle.is_valid());
  21131. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21132. EXPECT_EQ("123456789", read_all(handle));
  21133. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21134. }
  21135. #endif
  21136. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21137. TEST_F(OpenStreamTest, Brotli) {
  21138. Client cli("127.0.0.1", port_);
  21139. auto handle =
  21140. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21141. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21142. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21143. }
  21144. #endif
  21145. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21146. TEST_F(OpenStreamTest, Zstd) {
  21147. Client cli("127.0.0.1", port_);
  21148. auto handle = cli.open_stream("GET", "/compressible", {},
  21149. {{"Accept-Encoding", "zstd"}});
  21150. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21151. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21152. }
  21153. #endif
  21154. #ifdef CPPHTTPLIB_SSL_ENABLED
  21155. class SSLOpenStreamTest : public ::testing::Test {
  21156. protected:
  21157. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21158. void SetUp() override {
  21159. svr_.Get("/hello", [](const Request &, Response &res) {
  21160. res.set_content("Hello SSL World!", "text/plain");
  21161. });
  21162. svr_.Get("/chunked", [](const Request &, Response &res) {
  21163. res.set_chunked_content_provider("text/plain",
  21164. [](size_t offset, DataSink &sink) {
  21165. if (offset < 15) {
  21166. sink.write("chunk", 5);
  21167. return true;
  21168. }
  21169. sink.done();
  21170. return true;
  21171. });
  21172. });
  21173. svr_.Post("/echo", [](const Request &req, Response &res) {
  21174. res.set_content(req.body, req.get_header_value("Content-Type"));
  21175. });
  21176. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21177. std::string body = req.body;
  21178. res.set_chunked_content_provider(
  21179. "text/plain", [body](size_t offset, DataSink &sink) {
  21180. if (offset < body.size()) {
  21181. sink.write(body.data() + offset, body.size() - offset);
  21182. }
  21183. sink.done();
  21184. return true;
  21185. });
  21186. });
  21187. port_ = svr_.bind_to_any_port("127.0.0.1");
  21188. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21189. svr_.wait_until_ready();
  21190. }
  21191. void TearDown() override {
  21192. svr_.stop();
  21193. if (thread_.joinable()) thread_.join();
  21194. }
  21195. SSLServer svr_;
  21196. std::thread thread_;
  21197. int port_ = 0;
  21198. };
  21199. TEST_F(SSLOpenStreamTest, Basic) {
  21200. SSLClient cli("127.0.0.1", port_);
  21201. cli.enable_server_certificate_verification(false);
  21202. auto handle = cli.open_stream("GET", "/hello");
  21203. ASSERT_TRUE(handle.is_valid());
  21204. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21205. }
  21206. TEST_F(SSLOpenStreamTest, Chunked) {
  21207. SSLClient cli("127.0.0.1", port_);
  21208. cli.enable_server_certificate_verification(false);
  21209. auto handle = cli.open_stream("GET", "/chunked");
  21210. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21211. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21212. "Transfer-Encoding") == "chunked");
  21213. auto body = read_all(handle);
  21214. EXPECT_EQ("chunkchunkchunk", body);
  21215. }
  21216. TEST_F(SSLOpenStreamTest, Post) {
  21217. SSLClient cli("127.0.0.1", port_);
  21218. cli.enable_server_certificate_verification(false);
  21219. auto handle =
  21220. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21221. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21222. EXPECT_EQ(200, handle.response->status);
  21223. auto body = read_all(handle);
  21224. EXPECT_EQ("Hello SSL POST", body);
  21225. }
  21226. TEST_F(SSLOpenStreamTest, PostChunked) {
  21227. SSLClient cli("127.0.0.1", port_);
  21228. cli.enable_server_certificate_verification(false);
  21229. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21230. "Chunked SSL Data", "text/plain");
  21231. ASSERT_TRUE(handle.is_valid());
  21232. EXPECT_EQ(200, handle.response->status);
  21233. auto body = read_all(handle);
  21234. EXPECT_EQ("Chunked SSL Data", body);
  21235. }
  21236. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21237. // Content-Length is terminated by the server closing the connection. When the
  21238. // SSL peer sends a close_notify after the body, the client must treat it as a
  21239. // clean EOF and return a successful response rather than an error.
  21240. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21242. ASSERT_TRUE(svr.is_valid());
  21243. svr.set_keep_alive_max_count(1);
  21244. const std::string expected_body = "Hello from connection-close response!";
  21245. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21246. res.set_content_provider("text/plain",
  21247. [&](size_t offset, DataSink &sink) -> bool {
  21248. if (offset < expected_body.size()) {
  21249. sink.write(expected_body.data() + offset,
  21250. expected_body.size() - offset);
  21251. }
  21252. sink.done();
  21253. return true;
  21254. });
  21255. });
  21256. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21257. auto se = detail::scope_exit([&] {
  21258. svr.stop();
  21259. listen_thread.join();
  21260. ASSERT_FALSE(svr.is_running());
  21261. });
  21262. svr.wait_until_ready();
  21263. SSLClient cli(HOST, PORT);
  21264. cli.enable_server_certificate_verification(false);
  21265. auto res = cli.Get("/no-content-length");
  21266. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21267. EXPECT_EQ(StatusCode::OK_200, res->status);
  21268. EXPECT_EQ(expected_body, res->body);
  21269. }
  21270. // Without Content-Length, the full buffer size reaches tls::read().
  21271. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21272. if (sizeof(size_t) <= sizeof(int)) {
  21273. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21274. }
  21275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21276. ASSERT_TRUE(svr.is_valid());
  21277. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21278. res.set_content_provider("text/plain",
  21279. [&](size_t offset, DataSink &sink) -> bool {
  21280. if (offset == 0) { sink.write("Hello", 5); }
  21281. sink.done();
  21282. return true;
  21283. });
  21284. });
  21285. auto port = svr.bind_to_any_port(HOST);
  21286. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21287. auto se = detail::scope_exit([&] {
  21288. svr.stop();
  21289. listen_thread.join();
  21290. });
  21291. svr.wait_until_ready();
  21292. SSLClient cli(HOST, port);
  21293. cli.enable_server_certificate_verification(false);
  21294. auto handle = cli.open_stream("GET", "/no-content-length");
  21295. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21296. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21297. std::unique_ptr<char[]> buf(new char[len]);
  21298. std::string body;
  21299. ssize_t n;
  21300. while ((n = handle.read(buf.get(), len)) > 0) {
  21301. body.append(buf.get(), static_cast<size_t>(n));
  21302. }
  21303. EXPECT_EQ(0, n);
  21304. EXPECT_EQ("Hello", body);
  21305. }
  21306. #endif // CPPHTTPLIB_SSL_ENABLED
  21307. //==============================================================================
  21308. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21309. // results for various scenarios.
  21310. //==============================================================================
  21311. TEST(ParityTest, GetVsOpenStream) {
  21312. Server svr;
  21313. const std::string path = "/parity";
  21314. const std::string content = "Parity test content: hello world";
  21315. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21316. res.set_content(content, "text/plain");
  21317. });
  21318. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21319. auto se = detail::scope_exit([&] {
  21320. svr.stop();
  21321. t.join();
  21322. ASSERT_FALSE(svr.is_running());
  21323. });
  21324. svr.wait_until_ready();
  21325. Client cli(HOST, PORT);
  21326. // Non-stream path
  21327. auto r1 = cli.Get(path);
  21328. ASSERT_TRUE(r1);
  21329. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21330. // Stream path
  21331. auto h = cli.open_stream("GET", path);
  21332. ASSERT_TRUE(h.is_valid());
  21333. EXPECT_EQ(r1->body, read_all(h));
  21334. }
  21335. // Helper to compress data with provided compressor type T
  21336. template <typename Compressor>
  21337. static std::string compress_payload_for_parity(const std::string &in) {
  21338. std::string out;
  21339. Compressor compressor;
  21340. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21341. [&](const char *data, size_t n) {
  21342. out.append(data, n);
  21343. return true;
  21344. });
  21345. EXPECT_TRUE(ok);
  21346. return out;
  21347. }
  21348. // Helper function for compression parity tests
  21349. template <typename Compressor>
  21350. static void test_compression_parity(const std::string &original,
  21351. const std::string &path,
  21352. const std::string &encoding) {
  21353. const std::string compressed =
  21354. compress_payload_for_parity<Compressor>(original);
  21355. Server svr;
  21356. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21357. res.set_content(compressed, "application/octet-stream");
  21358. res.set_header("Content-Encoding", encoding);
  21359. });
  21360. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21361. auto se = detail::scope_exit([&] {
  21362. svr.stop();
  21363. t.join();
  21364. ASSERT_FALSE(svr.is_running());
  21365. });
  21366. svr.wait_until_ready();
  21367. Client cli(HOST, PORT);
  21368. // Non-streaming
  21369. {
  21370. auto res = cli.Get(path);
  21371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21372. EXPECT_EQ(StatusCode::OK_200, res->status);
  21373. EXPECT_EQ(original, res->body);
  21374. }
  21375. // Streaming
  21376. {
  21377. auto h = cli.open_stream("GET", path);
  21378. ASSERT_TRUE(h.is_valid());
  21379. EXPECT_EQ(original, read_all(h));
  21380. }
  21381. }
  21382. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21383. TEST(ParityTest, Gzip) {
  21384. test_compression_parity<detail::gzip_compressor>(
  21385. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21386. }
  21387. #endif
  21388. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21389. TEST(ParityTest, Brotli) {
  21390. test_compression_parity<detail::brotli_compressor>(
  21391. "Hello, brotli parity test payload", "/parity-br", "br");
  21392. }
  21393. #endif
  21394. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21395. TEST(ParityTest, Zstd) {
  21396. test_compression_parity<detail::zstd_compressor>(
  21397. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21398. }
  21399. #endif
  21400. //==============================================================================
  21401. // New Stream API Tests
  21402. //==============================================================================
  21403. inline std::string read_body(httplib::stream::Result &result) {
  21404. std::string body;
  21405. while (result.next()) {
  21406. body.append(result.data(), result.size());
  21407. }
  21408. return body;
  21409. }
  21410. TEST(ClientConnectionTest, Basic) {
  21411. httplib::ClientConnection conn;
  21412. EXPECT_FALSE(conn.is_open());
  21413. conn.sock = 1;
  21414. EXPECT_TRUE(conn.is_open());
  21415. httplib::ClientConnection conn2(std::move(conn));
  21416. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21417. conn2.sock = INVALID_SOCKET;
  21418. }
  21419. // Unified test server for all stream::* tests
  21420. class StreamApiTest : public ::testing::Test {
  21421. protected:
  21422. void SetUp() override {
  21423. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21424. res.set_content("Hello World!", "text/plain");
  21425. });
  21426. svr_.Get("/echo-params",
  21427. [](const httplib::Request &req, httplib::Response &res) {
  21428. std::string r;
  21429. for (const auto &p : req.params) {
  21430. if (!r.empty()) r += "&";
  21431. r += p.first + "=" + p.second;
  21432. }
  21433. res.set_content(r, "text/plain");
  21434. });
  21435. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21436. res.set_content(req.body, req.get_header_value("Content-Type"));
  21437. });
  21438. svr_.Post("/echo-headers",
  21439. [](const httplib::Request &req, httplib::Response &res) {
  21440. std::string r;
  21441. for (const auto &h : req.headers)
  21442. r += h.first + ": " + h.second + "\n";
  21443. res.set_content(r, "text/plain");
  21444. });
  21445. svr_.Post("/echo-params",
  21446. [](const httplib::Request &req, httplib::Response &res) {
  21447. std::string r = "params:";
  21448. for (const auto &p : req.params)
  21449. r += p.first + "=" + p.second + ";";
  21450. res.set_content(r + " body:" + req.body, "text/plain");
  21451. });
  21452. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21453. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21454. });
  21455. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21456. res.set_content("PUT:" + req.body, "text/plain");
  21457. });
  21458. svr_.Patch("/echo",
  21459. [](const httplib::Request &req, httplib::Response &res) {
  21460. res.set_content("PATCH:" + req.body, "text/plain");
  21461. });
  21462. svr_.Delete(
  21463. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21464. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21465. "text/plain");
  21466. });
  21467. svr_.Get("/head-test",
  21468. [](const httplib::Request &, httplib::Response &res) {
  21469. res.set_content("body for HEAD", "text/plain");
  21470. });
  21471. svr_.Options("/options",
  21472. [](const httplib::Request &, httplib::Response &res) {
  21473. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21474. });
  21475. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21476. svr_.wait_until_ready();
  21477. }
  21478. void TearDown() override {
  21479. svr_.stop();
  21480. if (thread_.joinable()) thread_.join();
  21481. }
  21482. httplib::Server svr_;
  21483. std::thread thread_;
  21484. };
  21485. // stream::Get tests
  21486. TEST_F(StreamApiTest, GetBasic) {
  21487. httplib::Client cli(HOST, PORT);
  21488. auto result = httplib::stream::Get(cli, "/hello");
  21489. ASSERT_TRUE(result.is_valid());
  21490. EXPECT_EQ(200, result.status());
  21491. EXPECT_EQ("Hello World!", read_body(result));
  21492. }
  21493. TEST_F(StreamApiTest, GetWithParams) {
  21494. httplib::Client cli(HOST, PORT);
  21495. httplib::Params params{{"foo", "bar"}};
  21496. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21497. ASSERT_TRUE(result.is_valid());
  21498. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21499. }
  21500. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21501. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21502. httplib::Client cli(HOST, PORT);
  21503. cli.set_payload_max_length(0);
  21504. auto result = httplib::stream::Get(cli, "/hello");
  21505. ASSERT_TRUE(result.is_valid());
  21506. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21507. EXPECT_EQ("Hello World!", read_body(result));
  21508. }
  21509. #endif
  21510. TEST_F(StreamApiTest, GetConnectionError) {
  21511. httplib::Client cli(HOST, 9999);
  21512. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21513. }
  21514. TEST_F(StreamApiTest, Get404) {
  21515. httplib::Client cli(HOST, PORT);
  21516. auto result = httplib::stream::Get(cli, "/nonexistent");
  21517. EXPECT_TRUE(result.is_valid());
  21518. EXPECT_EQ(404, result.status());
  21519. }
  21520. // stream::Post tests
  21521. TEST_F(StreamApiTest, PostBasic) {
  21522. httplib::Client cli(HOST, PORT);
  21523. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21524. "application/json");
  21525. ASSERT_TRUE(result.is_valid());
  21526. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21527. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21528. }
  21529. TEST_F(StreamApiTest, PostWithHeaders) {
  21530. httplib::Client cli(HOST, PORT);
  21531. httplib::Headers headers{{"X-Custom", "value"}};
  21532. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21533. "text/plain");
  21534. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21535. }
  21536. TEST_F(StreamApiTest, PostWithParams) {
  21537. httplib::Client cli(HOST, PORT);
  21538. httplib::Params params{{"k", "v"}};
  21539. auto result =
  21540. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21541. auto body = read_body(result);
  21542. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21543. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21544. }
  21545. TEST_F(StreamApiTest, PostLarge) {
  21546. httplib::Client cli(HOST, PORT);
  21547. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21548. size_t total = 0;
  21549. while (result.next()) {
  21550. total += result.size();
  21551. }
  21552. EXPECT_EQ(100u * 1024u, total);
  21553. }
  21554. // stream::Put/Patch tests
  21555. TEST_F(StreamApiTest, PutAndPatch) {
  21556. httplib::Client cli(HOST, PORT);
  21557. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21558. EXPECT_EQ("PUT:test", read_body(put));
  21559. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21560. EXPECT_EQ("PATCH:test", read_body(patch));
  21561. }
  21562. // stream::Delete tests
  21563. TEST_F(StreamApiTest, Delete) {
  21564. httplib::Client cli(HOST, PORT);
  21565. auto del1 = httplib::stream::Delete(cli, "/resource");
  21566. EXPECT_EQ("Deleted", read_body(del1));
  21567. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21568. EXPECT_EQ("Deleted:data", read_body(del2));
  21569. }
  21570. // stream::Head/Options tests
  21571. TEST_F(StreamApiTest, HeadAndOptions) {
  21572. httplib::Client cli(HOST, PORT);
  21573. auto head = httplib::stream::Head(cli, "/head-test");
  21574. EXPECT_TRUE(head.is_valid());
  21575. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21576. auto opts = httplib::stream::Options(cli, "/options");
  21577. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21578. }
  21579. // SSL stream::* tests
  21580. #ifdef CPPHTTPLIB_SSL_ENABLED
  21581. class SSLStreamApiTest : public ::testing::Test {
  21582. protected:
  21583. void SetUp() override {
  21584. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21585. res.set_content("Hello SSL!", "text/plain");
  21586. });
  21587. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21588. res.set_content(req.body, "text/plain");
  21589. });
  21590. port_ = svr_.bind_to_any_port("127.0.0.1");
  21591. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21592. svr_.wait_until_ready();
  21593. }
  21594. void TearDown() override {
  21595. svr_.stop();
  21596. if (thread_.joinable()) thread_.join();
  21597. }
  21598. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21599. std::thread thread_;
  21600. int port_ = 0;
  21601. };
  21602. TEST_F(SSLStreamApiTest, GetAndPost) {
  21603. httplib::SSLClient cli("127.0.0.1", port_);
  21604. cli.enable_server_certificate_verification(false);
  21605. auto get = httplib::stream::Get(cli, "/hello");
  21606. EXPECT_EQ("Hello SSL!", read_body(get));
  21607. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21608. EXPECT_EQ("test", read_body(post));
  21609. }
  21610. #endif
  21611. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21612. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21613. // BodyReader
  21614. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21615. // Test that read timeout during streaming is detected
  21616. // Use a large content-length response where server delays mid-stream
  21617. Server svr;
  21618. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21619. // Send a large response with delay in the middle
  21620. res.set_content_provider(
  21621. 1000, // content_length
  21622. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21623. if (offset < 100) {
  21624. // Send first 100 bytes immediately
  21625. std::string data(100, 'A');
  21626. sink.write(data.c_str(), data.size());
  21627. return true;
  21628. }
  21629. // Then delay longer than client timeout
  21630. std::this_thread::sleep_for(std::chrono::seconds(3));
  21631. std::string data(900, 'B');
  21632. sink.write(data.c_str(), data.size());
  21633. return true;
  21634. });
  21635. });
  21636. auto port = 8091;
  21637. std::thread t([&]() { svr.listen("localhost", port); });
  21638. svr.wait_until_ready();
  21639. Client cli("localhost", port);
  21640. cli.set_read_timeout(1, 0); // 1 second timeout
  21641. auto handle = cli.open_stream("GET", "/slow-stream");
  21642. ASSERT_TRUE(handle.is_valid());
  21643. char buf[256];
  21644. ssize_t total = 0;
  21645. ssize_t n;
  21646. bool got_error = false;
  21647. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21648. total += n;
  21649. }
  21650. if (n < 0) {
  21651. got_error = true;
  21652. // Should be timeout or read error
  21653. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21654. handle.get_read_error() == Error::Read)
  21655. << "Actual error: " << to_string(handle.get_read_error());
  21656. }
  21657. // Either we got an error, or we got less data than expected
  21658. EXPECT_TRUE(got_error || total < 1000)
  21659. << "Expected timeout but got all " << total << " bytes";
  21660. svr.stop();
  21661. t.join();
  21662. }
  21663. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21664. // Test connection closed detection via BodyReader
  21665. Server svr;
  21666. std::atomic<bool> close_now{false};
  21667. svr.Get("/will-close", [&](const Request &, Response &res) {
  21668. res.set_content_provider(
  21669. 10000, // Large content_length that we won't fully send
  21670. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21671. if (offset < 100) {
  21672. std::string data(100, 'X');
  21673. sink.write(data.c_str(), data.size());
  21674. return true;
  21675. }
  21676. // Wait for signal then abort
  21677. while (!close_now) {
  21678. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21679. }
  21680. return false; // Abort - server will close connection
  21681. });
  21682. });
  21683. auto port = 8092;
  21684. std::thread t([&]() { svr.listen("localhost", port); });
  21685. svr.wait_until_ready();
  21686. Client cli("localhost", port);
  21687. auto handle = cli.open_stream("GET", "/will-close");
  21688. ASSERT_TRUE(handle.is_valid());
  21689. char buf[256];
  21690. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21691. EXPECT_GT(n, 0) << "First read should succeed";
  21692. // Signal server to close
  21693. close_now = true;
  21694. // Keep reading until error or EOF
  21695. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21696. // Keep reading
  21697. }
  21698. // Should get an error since content_length wasn't satisfied
  21699. if (n < 0) {
  21700. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21701. handle.get_read_error() == Error::Read)
  21702. << "Actual error: " << to_string(handle.get_read_error());
  21703. }
  21704. svr.stop();
  21705. t.join();
  21706. }
  21707. #ifdef CPPHTTPLIB_SSL_ENABLED
  21708. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21709. // Test that read timeout during SSL streaming is detected
  21710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21711. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21712. res.set_content_provider(
  21713. 1000, "text/plain",
  21714. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21715. if (offset < 100) {
  21716. std::string data(100, 'A');
  21717. sink.write(data.c_str(), data.size());
  21718. return true;
  21719. }
  21720. std::this_thread::sleep_for(std::chrono::seconds(3));
  21721. std::string data(900, 'B');
  21722. sink.write(data.c_str(), data.size());
  21723. return true;
  21724. });
  21725. });
  21726. auto port = 8093;
  21727. std::thread t([&]() { svr.listen("localhost", port); });
  21728. svr.wait_until_ready();
  21729. SSLClient cli("localhost", port);
  21730. cli.enable_server_certificate_verification(false);
  21731. cli.set_read_timeout(1, 0); // 1 second timeout
  21732. auto handle = cli.open_stream("GET", "/slow-stream");
  21733. ASSERT_TRUE(handle.is_valid());
  21734. char buf[256];
  21735. ssize_t total = 0;
  21736. ssize_t n;
  21737. bool got_error = false;
  21738. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21739. total += n;
  21740. }
  21741. if (n < 0) {
  21742. got_error = true;
  21743. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21744. handle.get_read_error() == Error::Read)
  21745. << "Actual error: " << to_string(handle.get_read_error());
  21746. }
  21747. EXPECT_TRUE(got_error || total < 1000)
  21748. << "Expected timeout but got all " << total << " bytes";
  21749. svr.stop();
  21750. t.join();
  21751. }
  21752. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21753. // Test SSL connection closed detection
  21754. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21755. std::atomic<bool> close_now{false};
  21756. svr.Get("/will-close", [&](const Request &, Response &res) {
  21757. res.set_content_provider(
  21758. 10000, "text/plain",
  21759. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21760. if (offset < 100) {
  21761. std::string data(100, 'X');
  21762. sink.write(data.c_str(), data.size());
  21763. return true;
  21764. }
  21765. while (!close_now) {
  21766. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21767. }
  21768. return false;
  21769. });
  21770. });
  21771. auto port = 8094;
  21772. std::thread t([&]() { svr.listen("localhost", port); });
  21773. svr.wait_until_ready();
  21774. SSLClient cli("localhost", port);
  21775. cli.enable_server_certificate_verification(false);
  21776. auto handle = cli.open_stream("GET", "/will-close");
  21777. ASSERT_TRUE(handle.is_valid());
  21778. char buf[256];
  21779. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21780. EXPECT_GT(n, 0);
  21781. // Signal server to close
  21782. close_now = true;
  21783. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21784. // Keep reading
  21785. }
  21786. if (n < 0) {
  21787. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21788. handle.get_read_error() == Error::Read)
  21789. << "Actual error: " << to_string(handle.get_read_error());
  21790. }
  21791. svr.stop();
  21792. t.join();
  21793. }
  21794. #endif
  21795. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21796. using namespace httplib;
  21797. // Create a test file
  21798. const char *fname = "etag_testfile.txt";
  21799. const char *content = "etag-content";
  21800. {
  21801. std::ofstream ofs(fname);
  21802. ofs << content;
  21803. ASSERT_TRUE(ofs.good());
  21804. }
  21805. Server svr;
  21806. svr.set_mount_point("/static", ".");
  21807. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21808. svr.wait_until_ready();
  21809. Client cli(HOST, PORT);
  21810. // First request: should get 200 with ETag header
  21811. auto res1 = cli.Get("/static/etag_testfile.txt");
  21812. ASSERT_TRUE(res1);
  21813. ASSERT_EQ(200, res1->status);
  21814. ASSERT_TRUE(res1->has_header("ETag"));
  21815. std::string etag = res1->get_header_value("ETag");
  21816. EXPECT_FALSE(etag.empty());
  21817. // Verify ETag format: W/"hex-hex"
  21818. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21819. EXPECT_EQ('W', etag[0]);
  21820. EXPECT_EQ('/', etag[1]);
  21821. EXPECT_EQ('"', etag[2]);
  21822. EXPECT_EQ('"', etag.back());
  21823. // Exact match: expect 304 Not Modified
  21824. Headers h2 = {{"If-None-Match", etag}};
  21825. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21826. ASSERT_TRUE(res2);
  21827. EXPECT_EQ(304, res2->status);
  21828. // Wildcard match: expect 304 Not Modified
  21829. Headers h3 = {{"If-None-Match", "*"}};
  21830. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21831. ASSERT_TRUE(res3);
  21832. EXPECT_EQ(304, res3->status);
  21833. // Non-matching ETag: expect 200
  21834. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21835. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21836. ASSERT_TRUE(res4);
  21837. EXPECT_EQ(200, res4->status);
  21838. // Multiple ETags with one matching: expect 304
  21839. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21840. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21841. ASSERT_TRUE(res5);
  21842. EXPECT_EQ(304, res5->status);
  21843. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21844. // that equivalent to the single comma-separated list above, so the match on
  21845. // the second line must still be found.
  21846. Headers h6;
  21847. h6.emplace("If-None-Match", "W/\"other\"");
  21848. h6.emplace("If-None-Match", etag);
  21849. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21850. ASSERT_TRUE(res6);
  21851. EXPECT_EQ(304, res6->status);
  21852. svr.stop();
  21853. t.join();
  21854. std::remove(fname);
  21855. }
  21856. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21857. using namespace httplib;
  21858. Server svr;
  21859. svr.set_mount_point("/static", ".");
  21860. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21861. svr.wait_until_ready();
  21862. Client cli(HOST, PORT);
  21863. // Send If-None-Match: * to a non-existent file
  21864. Headers h = {{"If-None-Match", "*"}};
  21865. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21867. EXPECT_EQ(404, res->status);
  21868. svr.stop();
  21869. t.join();
  21870. }
  21871. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21872. using namespace httplib;
  21873. // Create a test file
  21874. const char *fname = "etag_boundary_testfile.txt";
  21875. const char *content = "boundary-test";
  21876. {
  21877. std::ofstream ofs(fname);
  21878. ofs << content;
  21879. ASSERT_TRUE(ofs.good());
  21880. }
  21881. Server svr;
  21882. svr.set_mount_point("/static", ".");
  21883. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21884. svr.wait_until_ready();
  21885. Client cli(HOST, PORT);
  21886. // Get the actual ETag
  21887. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21888. ASSERT_TRUE(res1);
  21889. ASSERT_EQ(200, res1->status);
  21890. ASSERT_TRUE(res1->has_header("ETag"));
  21891. std::string etag = res1->get_header_value("ETag");
  21892. // Test 1: Very long ETag value (longer than actual ETag)
  21893. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21894. Headers h1 = {{"If-None-Match", "W/"
  21895. "\"very-long-etag-value-that-is-much-longer-"
  21896. "than-the-actual-etag-value\""}};
  21897. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21898. ASSERT_TRUE(res2);
  21899. EXPECT_EQ(200, res2->status); // Should not match
  21900. // Test 2: Long string followed by wildcard
  21901. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21902. // string)
  21903. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21904. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21905. ASSERT_TRUE(res3);
  21906. EXPECT_EQ(304, res3->status); // Should match on "*"
  21907. // Test 3: Wildcard followed by long string
  21908. // Should match on "*" immediately and return 304
  21909. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21910. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21911. ASSERT_TRUE(res4);
  21912. EXPECT_EQ(304, res4->status); // Should match on "*"
  21913. // Test 4: Multiple long non-matching values
  21914. // Should NOT match and return 200 (test that all comparisons are safe)
  21915. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21916. "W/\"second-long-non-matching-value\", "
  21917. "W/\"third-long-non-matching-value\""}};
  21918. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21919. ASSERT_TRUE(res5);
  21920. EXPECT_EQ(200, res5->status); // Should not match
  21921. // Test 5: Single character that is not "*" (edge case)
  21922. Headers h5 = {{"If-None-Match", "X"}};
  21923. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21924. ASSERT_TRUE(res6);
  21925. EXPECT_EQ(200, res6->status); // Should not match
  21926. svr.stop();
  21927. t.join();
  21928. std::remove(fname);
  21929. }
  21930. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21931. using namespace httplib;
  21932. // Create a test file
  21933. const char *fname = "ims_testfile.txt";
  21934. const char *content = "if-modified-since-test";
  21935. {
  21936. std::ofstream ofs(fname);
  21937. ofs << content;
  21938. ASSERT_TRUE(ofs.good());
  21939. }
  21940. Server svr;
  21941. svr.set_mount_point("/static", ".");
  21942. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21943. svr.wait_until_ready();
  21944. Client cli(HOST, PORT);
  21945. // First request: should get 200 with Last-Modified header
  21946. auto res1 = cli.Get("/static/ims_testfile.txt");
  21947. ASSERT_TRUE(res1);
  21948. ASSERT_EQ(200, res1->status);
  21949. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21950. std::string last_modified = res1->get_header_value("Last-Modified");
  21951. EXPECT_FALSE(last_modified.empty());
  21952. // If-Modified-Since with same time: expect 304
  21953. Headers h2 = {{"If-Modified-Since", last_modified}};
  21954. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21955. ASSERT_TRUE(res2);
  21956. EXPECT_EQ(304, res2->status);
  21957. // If-Modified-Since with future time: expect 304
  21958. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21959. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21960. ASSERT_TRUE(res3);
  21961. EXPECT_EQ(304, res3->status);
  21962. // If-Modified-Since with past time: expect 200
  21963. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21964. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21965. ASSERT_TRUE(res4);
  21966. EXPECT_EQ(200, res4->status);
  21967. // If-None-Match takes precedence over If-Modified-Since
  21968. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21969. ASSERT_TRUE(res1->has_header("ETag"));
  21970. std::string etag = res1->get_header_value("ETag");
  21971. Headers h5 = {{"If-None-Match", etag},
  21972. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21973. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21974. ASSERT_TRUE(res5);
  21975. EXPECT_EQ(304, res5->status);
  21976. svr.stop();
  21977. t.join();
  21978. std::remove(fname);
  21979. }
  21980. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21981. using namespace httplib;
  21982. Server svr;
  21983. // Endpoint that returns compressible content
  21984. svr.Get("/compressible", [](const Request &, Response &res) {
  21985. // Return a large enough body to trigger compression
  21986. std::string body(1000, 'a');
  21987. res.set_content(body, "text/plain");
  21988. });
  21989. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21990. svr.wait_until_ready();
  21991. Client cli(HOST, PORT);
  21992. // Request with gzip support: should get Vary header when compressed
  21993. cli.set_compress(true);
  21994. auto res1 = cli.Get("/compressible");
  21995. ASSERT_TRUE(res1);
  21996. EXPECT_EQ(200, res1->status);
  21997. // If Content-Encoding is set, Vary should also be set
  21998. if (res1->has_header("Content-Encoding")) {
  21999. EXPECT_TRUE(res1->has_header("Vary"));
  22000. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22001. }
  22002. // Request without Accept-Encoding header: should not have compression
  22003. Headers h_no_compress;
  22004. auto res2 = cli.Get("/compressible", h_no_compress);
  22005. ASSERT_TRUE(res2);
  22006. EXPECT_EQ(200, res2->status);
  22007. // Verify Vary header is present when compression is applied
  22008. // (the exact behavior depends on server configuration)
  22009. svr.stop();
  22010. t.join();
  22011. }
  22012. TEST(ETagTest, IfRangeWithETag) {
  22013. using namespace httplib;
  22014. // Create a test file with known content
  22015. const char *fname = "if_range_testfile.txt";
  22016. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22017. {
  22018. std::ofstream ofs(fname);
  22019. ofs << content;
  22020. ASSERT_TRUE(ofs.good());
  22021. }
  22022. Server svr;
  22023. svr.set_mount_point("/static", ".");
  22024. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22025. svr.wait_until_ready();
  22026. Client cli(HOST, PORT);
  22027. // First request: get ETag
  22028. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22029. ASSERT_TRUE(res1);
  22030. ASSERT_EQ(200, res1->status);
  22031. ASSERT_TRUE(res1->has_header("ETag"));
  22032. std::string etag = res1->get_header_value("ETag");
  22033. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22034. // Since our server generates weak ETags (W/"..."), If-Range with our
  22035. // ETag should NOT result in partial content - it should return full content.
  22036. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22037. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22038. ASSERT_TRUE(res2);
  22039. // Weak ETag in If-Range -> full content (200), not partial (206)
  22040. EXPECT_EQ(200, res2->status);
  22041. EXPECT_EQ(content, res2->body);
  22042. EXPECT_FALSE(res2->has_header("Content-Range"));
  22043. // Range request with non-matching If-Range (ETag): should get 200 (full
  22044. // content)
  22045. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22046. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22047. ASSERT_TRUE(res3);
  22048. EXPECT_EQ(200, res3->status);
  22049. EXPECT_EQ(content, res3->body);
  22050. EXPECT_FALSE(res3->has_header("Content-Range"));
  22051. // Range request with strong ETag (hypothetical - our server doesn't generate
  22052. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22053. // should return full content)
  22054. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22055. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22056. ASSERT_TRUE(res4);
  22057. EXPECT_EQ(200, res4->status);
  22058. EXPECT_EQ(content, res4->body);
  22059. EXPECT_FALSE(res4->has_header("Content-Range"));
  22060. svr.stop();
  22061. t.join();
  22062. std::remove(fname);
  22063. }
  22064. TEST(ETagTest, IfRangeWithDate) {
  22065. using namespace httplib;
  22066. // Create a test file
  22067. const char *fname = "if_range_date_testfile.txt";
  22068. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22069. {
  22070. std::ofstream ofs(fname);
  22071. ofs << content;
  22072. ASSERT_TRUE(ofs.good());
  22073. }
  22074. Server svr;
  22075. svr.set_mount_point("/static", ".");
  22076. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22077. svr.wait_until_ready();
  22078. Client cli(HOST, PORT);
  22079. // First request: get Last-Modified
  22080. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22081. ASSERT_TRUE(res1);
  22082. ASSERT_EQ(200, res1->status);
  22083. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22084. std::string last_modified = res1->get_header_value("Last-Modified");
  22085. // Range request with matching If-Range (date): should get 206
  22086. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22087. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22088. ASSERT_TRUE(res2);
  22089. EXPECT_EQ(206, res2->status);
  22090. EXPECT_EQ("FGHIJ", res2->body);
  22091. // Range request with old If-Range date: should get 200 (full content)
  22092. Headers h3 = {{"Range", "bytes=5-9"},
  22093. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22094. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22095. ASSERT_TRUE(res3);
  22096. EXPECT_EQ(200, res3->status);
  22097. EXPECT_EQ(content, res3->body);
  22098. // Range request with future If-Range date: should get 206
  22099. Headers h4 = {{"Range", "bytes=0-4"},
  22100. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22101. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22102. ASSERT_TRUE(res4);
  22103. EXPECT_EQ(206, res4->status);
  22104. EXPECT_EQ("ABCDE", res4->body);
  22105. svr.stop();
  22106. t.join();
  22107. std::remove(fname);
  22108. }
  22109. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22110. using namespace httplib;
  22111. const char *fname = "etag_malformed.txt";
  22112. const char *content = "malformed-etag";
  22113. {
  22114. std::ofstream ofs(fname);
  22115. ofs << content;
  22116. ASSERT_TRUE(ofs.good());
  22117. }
  22118. Server svr;
  22119. svr.set_mount_point("/static", ".");
  22120. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22121. svr.wait_until_ready();
  22122. Client cli(HOST, PORT);
  22123. // baseline: should get 200 and an ETag
  22124. auto res1 = cli.Get("/static/etag_malformed.txt");
  22125. ASSERT_TRUE(res1);
  22126. ASSERT_EQ(200, res1->status);
  22127. ASSERT_TRUE(res1->has_header("ETag"));
  22128. // Malformed ETag value (missing quotes) should be treated as non-matching
  22129. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22130. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22131. ASSERT_TRUE(res_bad);
  22132. EXPECT_EQ(200, res_bad->status);
  22133. // Whitespace-only header value should be considered invalid / non-matching
  22134. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22135. "Host: localhost\r\n"
  22136. "If-None-Match: \r\n"
  22137. "Connection: close\r\n"
  22138. "\r\n";
  22139. std::string out;
  22140. ASSERT_TRUE(send_request(5, raw_req, &out));
  22141. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22142. svr.stop();
  22143. t.join();
  22144. std::remove(fname);
  22145. }
  22146. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22147. using namespace httplib;
  22148. const char *fname = "ims_invalid_format.txt";
  22149. const char *content = "ims-bad-format";
  22150. {
  22151. std::ofstream ofs(fname);
  22152. ofs << content;
  22153. ASSERT_TRUE(ofs.good());
  22154. }
  22155. Server svr;
  22156. svr.set_mount_point("/static", ".");
  22157. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22158. svr.wait_until_ready();
  22159. Client cli(HOST, PORT);
  22160. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22161. ASSERT_TRUE(res1);
  22162. ASSERT_EQ(200, res1->status);
  22163. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22164. // If-Modified-Since with invalid format should not result in 304
  22165. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22166. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22167. ASSERT_TRUE(res_bad);
  22168. EXPECT_EQ(200, res_bad->status);
  22169. // If-Range with invalid date format should be treated as mismatch -> full
  22170. // content (200)
  22171. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22172. {"If-Range", "invalid-date"}};
  22173. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22174. ASSERT_TRUE(res_ifrange);
  22175. EXPECT_EQ(200, res_ifrange->status);
  22176. svr.stop();
  22177. t.join();
  22178. std::remove(fname);
  22179. }
  22180. TEST(ETagTest, IfRangeWithMalformedETag) {
  22181. using namespace httplib;
  22182. const char *fname = "ifrange_malformed.txt";
  22183. const std::string content = "0123456789";
  22184. {
  22185. std::ofstream ofs(fname);
  22186. ofs << content;
  22187. ASSERT_TRUE(ofs.good());
  22188. }
  22189. Server svr;
  22190. svr.set_mount_point("/static", ".");
  22191. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22192. svr.wait_until_ready();
  22193. Client cli(HOST, PORT);
  22194. // First request: get ETag
  22195. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22196. ASSERT_TRUE(res1);
  22197. ASSERT_EQ(200, res1->status);
  22198. ASSERT_TRUE(res1->has_header("ETag"));
  22199. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22200. // full content (200)
  22201. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22202. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22203. ASSERT_TRUE(res2);
  22204. EXPECT_EQ(200, res2->status);
  22205. EXPECT_EQ(content, res2->body);
  22206. svr.stop();
  22207. t.join();
  22208. std::remove(fname);
  22209. }
  22210. TEST(ETagTest, ExtremeLargeDateValues) {
  22211. using namespace httplib;
  22212. const char *fname = "ims_extreme_date.txt";
  22213. const char *content = "ims-extreme-date";
  22214. {
  22215. std::ofstream ofs(fname);
  22216. ofs << content;
  22217. ASSERT_TRUE(ofs.good());
  22218. }
  22219. Server svr;
  22220. svr.set_mount_point("/static", ".");
  22221. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22222. svr.wait_until_ready();
  22223. Client cli(HOST, PORT);
  22224. auto res1 = cli.Get(std::string("/static/") + fname);
  22225. ASSERT_TRUE(res1);
  22226. ASSERT_EQ(200, res1->status);
  22227. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22228. // Extremely large year that may overflow date parsing routines.
  22229. Headers h_large_date = {
  22230. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22231. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22232. ASSERT_TRUE(res_bad);
  22233. // Expect server to treat this as invalid/mismatch and return full content
  22234. EXPECT_EQ(200, res_bad->status);
  22235. // If-Range with extremely large date should be treated as mismatch -> full
  22236. // content (200)
  22237. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22238. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22239. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22240. ASSERT_TRUE(res_ifrange);
  22241. EXPECT_EQ(200, res_ifrange->status);
  22242. svr.stop();
  22243. t.join();
  22244. std::remove(fname);
  22245. }
  22246. TEST(ETagTest, NegativeFileModificationTime) {
  22247. using namespace httplib;
  22248. const char *fname = "ims_negative_mtime.txt";
  22249. const std::string content = "negative-mtime";
  22250. {
  22251. std::ofstream ofs(fname);
  22252. ofs << content;
  22253. ASSERT_TRUE(ofs.good());
  22254. }
  22255. // Try to set file mtime to a negative value. This may fail on some
  22256. // platforms/filesystems; if it fails, the test will still verify server
  22257. // behaves safely by performing a regular conditional request.
  22258. #if defined(__APPLE__) || defined(__linux__)
  22259. bool set_negative = false;
  22260. do {
  22261. struct timeval times[2];
  22262. // access time: now
  22263. times[0].tv_sec = time(nullptr);
  22264. times[0].tv_usec = 0;
  22265. // modification time: negative (e.g., -1)
  22266. times[1].tv_sec = -1;
  22267. times[1].tv_usec = 0;
  22268. if (utimes(fname, times) == 0) { set_negative = true; }
  22269. } while (0);
  22270. #else
  22271. bool set_negative = false;
  22272. #endif
  22273. Server svr;
  22274. svr.set_mount_point("/static", ".");
  22275. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22276. svr.wait_until_ready();
  22277. Client cli(HOST, PORT);
  22278. auto res1 = cli.Get(std::string("/static/") + fname);
  22279. ASSERT_TRUE(res1);
  22280. ASSERT_EQ(200, res1->status);
  22281. bool has_last_modified = res1->has_header("Last-Modified");
  22282. std::string last_modified;
  22283. if (has_last_modified) {
  22284. last_modified = res1->get_header_value("Last-Modified");
  22285. }
  22286. if (set_negative) {
  22287. // If we successfully set a negative mtime, ensure server returns a
  22288. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22289. // with an old date and ensure server handles it without crash.
  22290. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22291. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22292. ASSERT_TRUE(res2);
  22293. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22294. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22295. } else {
  22296. // Could not set negative mtime on this platform; fall back to verifying
  22297. // that normal invalid/malformed dates are treated safely (non-304).
  22298. Headers h_bad_date = {
  22299. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22300. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22301. ASSERT_TRUE(res_bad);
  22302. EXPECT_EQ(200, res_bad->status);
  22303. }
  22304. svr.stop();
  22305. t.join();
  22306. std::remove(fname);
  22307. }
  22308. //==============================================================================
  22309. // Integration Tests with Server
  22310. //==============================================================================
  22311. class SSEIntegrationTest : public ::testing::Test {
  22312. protected:
  22313. void SetUp() override {
  22314. stop_server_.store(false);
  22315. events_.clear();
  22316. server_ = httplib::detail::make_unique<Server>();
  22317. setup_server();
  22318. start_server();
  22319. }
  22320. void TearDown() override {
  22321. stop_server_.store(true);
  22322. event_cv_.notify_all();
  22323. server_->stop();
  22324. if (server_thread_.joinable()) { server_thread_.join(); }
  22325. }
  22326. void setup_server() {
  22327. // Simple SSE endpoint
  22328. server_->Get("/events", [this](const Request &req, Response &res) {
  22329. auto last_id = req.get_header_value("Last-Event-ID");
  22330. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22331. res.set_chunked_content_provider(
  22332. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22333. std::unique_lock<std::mutex> lock(event_mutex_);
  22334. if (event_cv_.wait_for(
  22335. lock, std::chrono::milliseconds(200), [this] {
  22336. return !events_.empty() || stop_server_.load();
  22337. })) {
  22338. if (stop_server_.load()) { return false; }
  22339. if (!events_.empty()) {
  22340. std::string event = events_.front();
  22341. events_.erase(events_.begin());
  22342. sink.write(event.data(), event.size());
  22343. return true;
  22344. }
  22345. }
  22346. return !stop_server_.load();
  22347. });
  22348. });
  22349. // Endpoint that returns error
  22350. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22351. res.status = 500;
  22352. res.set_content("Internal Server Error", "text/plain");
  22353. });
  22354. // Endpoint for custom event types
  22355. server_->Get("/custom-events", [](const Request &, Response &res) {
  22356. res.set_chunked_content_provider(
  22357. "text/event-stream", [](size_t offset, DataSink &sink) {
  22358. if (offset == 0) {
  22359. std::string event = "event: update\ndata: updated\n\n"
  22360. "event: delete\ndata: deleted\n\n";
  22361. sink.write(event.data(), event.size());
  22362. }
  22363. return false; // End stream after sending
  22364. });
  22365. });
  22366. }
  22367. void start_server() {
  22368. port_ = server_->bind_to_any_port(HOST);
  22369. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22370. // Wait for server to start
  22371. while (!server_->is_running()) {
  22372. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22373. }
  22374. }
  22375. int get_port() const { return port_; }
  22376. void send_event(const std::string &event) {
  22377. std::lock_guard<std::mutex> lock(event_mutex_);
  22378. events_.push_back(event);
  22379. event_cv_.notify_all();
  22380. }
  22381. std::unique_ptr<Server> server_;
  22382. std::thread server_thread_;
  22383. std::mutex event_mutex_;
  22384. std::condition_variable event_cv_;
  22385. std::vector<std::string> events_;
  22386. std::atomic<bool> stop_server_{false};
  22387. std::string last_received_event_id_;
  22388. int port_ = 0;
  22389. };
  22390. //==============================================================================
  22391. // SSE Parsing Tests
  22392. //==============================================================================
  22393. class SSEParsingTest : public SSEIntegrationTest {
  22394. protected:
  22395. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22396. // A trailing sentinel event tells when the whole stream has been parsed.
  22397. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22398. auto body = stream + "event: end\ndata: end\n\n";
  22399. server_->Get("/parse", [body](const Request &, Response &res) {
  22400. res.set_content(body, "text/event-stream");
  22401. });
  22402. return collect("/parse");
  22403. }
  22404. // Runs SSEClient against path until an "end" event arrives and returns the
  22405. // messages dispatched before it
  22406. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22407. Client client(HOST, get_port());
  22408. sse::SSEClient sse(client, path);
  22409. std::mutex mutex;
  22410. std::condition_variable cv;
  22411. std::vector<sse::SSEMessage> messages;
  22412. auto done = false;
  22413. sse.on_message([&](const sse::SSEMessage &msg) {
  22414. std::lock_guard<std::mutex> lock(mutex);
  22415. // Ignore a replay from a reconnect that races with stop()
  22416. if (!done) { messages.push_back(msg); }
  22417. });
  22418. sse.on_event("end", [&](const sse::SSEMessage &) {
  22419. std::lock_guard<std::mutex> lock(mutex);
  22420. done = true;
  22421. cv.notify_all();
  22422. });
  22423. sse.set_reconnect_interval(100);
  22424. sse.start_async();
  22425. {
  22426. std::unique_lock<std::mutex> lock(mutex);
  22427. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22428. }
  22429. sse.stop();
  22430. EXPECT_TRUE(done);
  22431. return messages;
  22432. }
  22433. };
  22434. TEST_F(SSEParsingTest, SingleLineData) {
  22435. auto msgs = parse("data: hello\n\n");
  22436. ASSERT_EQ(msgs.size(), 1u);
  22437. EXPECT_EQ(msgs[0].data, "hello");
  22438. EXPECT_EQ(msgs[0].event, "message");
  22439. }
  22440. TEST_F(SSEParsingTest, MultiLineData) {
  22441. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22442. ASSERT_EQ(msgs.size(), 1u);
  22443. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22444. }
  22445. TEST_F(SSEParsingTest, CustomEventType) {
  22446. auto msgs = parse("event: update\ndata: payload\n\n");
  22447. ASSERT_EQ(msgs.size(), 1u);
  22448. EXPECT_EQ(msgs[0].event, "update");
  22449. EXPECT_EQ(msgs[0].data, "payload");
  22450. }
  22451. TEST_F(SSEParsingTest, EventIdHandling) {
  22452. auto msgs = parse("id: 12345\ndata: test\n\n");
  22453. ASSERT_EQ(msgs.size(), 1u);
  22454. EXPECT_EQ(msgs[0].id, "12345");
  22455. }
  22456. TEST_F(SSEParsingTest, EmptyEventId) {
  22457. auto msgs = parse("id:\ndata: test\n\n");
  22458. ASSERT_EQ(msgs.size(), 1u);
  22459. EXPECT_EQ(msgs[0].id, "");
  22460. }
  22461. TEST_F(SSEParsingTest, CommentsIgnored) {
  22462. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22463. ASSERT_EQ(msgs.size(), 1u);
  22464. EXPECT_EQ(msgs[0].data, "hello");
  22465. EXPECT_EQ(msgs[0].event, "message");
  22466. }
  22467. TEST_F(SSEParsingTest, ColonInValue) {
  22468. auto msgs = parse("data: hello:world:test\n\n");
  22469. ASSERT_EQ(msgs.size(), 1u);
  22470. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22471. }
  22472. TEST_F(SSEParsingTest, FieldNameOnly) {
  22473. // A line without a colon is a field name with an empty value
  22474. auto msgs = parse("data\n\n");
  22475. ASSERT_EQ(msgs.size(), 1u);
  22476. EXPECT_EQ(msgs[0].data, "");
  22477. }
  22478. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22479. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22480. ASSERT_EQ(msgs.size(), 1u);
  22481. EXPECT_EQ(msgs[0].event, "update");
  22482. EXPECT_EQ(msgs[0].data, "hello");
  22483. }
  22484. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22485. auto msgs = parse("data\r\n\r\n");
  22486. ASSERT_EQ(msgs.size(), 1u);
  22487. EXPECT_EQ(msgs[0].data, "");
  22488. }
  22489. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22490. auto msgs = parse("event: update\rdata: hello\r\r");
  22491. ASSERT_EQ(msgs.size(), 1u);
  22492. EXPECT_EQ(msgs[0].event, "update");
  22493. EXPECT_EQ(msgs[0].data, "hello");
  22494. }
  22495. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22496. // Chunk boundaries fall inside every \r\n and right before the first one
  22497. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22498. "\n\r", "\nevent: end\ndata: end\n\n"};
  22499. server_->Get("/split", [chunks](const Request &, Response &res) {
  22500. auto i = std::make_shared<size_t>(0);
  22501. res.set_chunked_content_provider(
  22502. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22503. if (*i == chunks.size()) {
  22504. sink.done();
  22505. } else {
  22506. sink.write(chunks[*i].data(), chunks[*i].size());
  22507. (*i)++;
  22508. }
  22509. return true;
  22510. });
  22511. });
  22512. auto msgs = collect("/split");
  22513. ASSERT_EQ(msgs.size(), 1u);
  22514. EXPECT_EQ(msgs[0].event, "update");
  22515. EXPECT_EQ(msgs[0].data, "hello");
  22516. }
  22517. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22518. // Only a BOM at the start of the stream is ignored
  22519. auto msgs = parse("\xEF\xBB\xBF"
  22520. "data: first\n\n"
  22521. "\xEF\xBB\xBF"
  22522. "data: second\n\n");
  22523. ASSERT_EQ(msgs.size(), 1u);
  22524. EXPECT_EQ(msgs[0].data, "first");
  22525. }
  22526. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22527. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22528. ASSERT_EQ(msgs.size(), 1u);
  22529. EXPECT_EQ(msgs[0].data, "hello");
  22530. EXPECT_EQ(msgs[0].event, "message");
  22531. }
  22532. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22533. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22534. ASSERT_EQ(msgs.size(), 2u);
  22535. EXPECT_EQ(msgs[0].data, "hello");
  22536. EXPECT_EQ(msgs[1].data, "hello");
  22537. }
  22538. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22539. // An event without data is not dispatched, and its type must not leak
  22540. // into the next event
  22541. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22542. ASSERT_EQ(msgs.size(), 1u);
  22543. EXPECT_EQ(msgs[0].event, "message");
  22544. EXPECT_EQ(msgs[0].data, "hello");
  22545. }
  22546. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22547. // Also when the empty field replaces an earlier type
  22548. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22549. ASSERT_EQ(msgs.size(), 2u);
  22550. EXPECT_EQ(msgs[0].event, "message");
  22551. EXPECT_EQ(msgs[1].event, "message");
  22552. }
  22553. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22554. // The first connection sends only an id; the second echoes back the
  22555. // Last-Event-ID it was reconnected with
  22556. std::atomic<int> connection_count{0};
  22557. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22558. if (connection_count++ == 0) {
  22559. res.set_content("id: 42\n\n", "text/event-stream");
  22560. } else {
  22561. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22562. "\n\nevent: end\ndata: end\n\n",
  22563. "text/event-stream");
  22564. }
  22565. });
  22566. auto msgs = collect("/id-only");
  22567. ASSERT_EQ(msgs.size(), 1u);
  22568. EXPECT_EQ(msgs[0].data, "42");
  22569. }
  22570. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22571. // The first connection sets an id and then clears it with an empty one; the
  22572. // second reports whether it was reconnected with a Last-Event-ID
  22573. std::atomic<int> connection_count{0};
  22574. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22575. if (connection_count++ == 0) {
  22576. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22577. "text/event-stream");
  22578. } else {
  22579. res.set_content(
  22580. std::string("data: ") +
  22581. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22582. "\n\nevent: end\ndata: end\n\n",
  22583. "text/event-stream");
  22584. }
  22585. });
  22586. auto msgs = collect("/id-clear");
  22587. ASSERT_EQ(msgs.size(), 3u);
  22588. EXPECT_EQ(msgs[0].id, "1");
  22589. EXPECT_EQ(msgs[1].id, "");
  22590. EXPECT_EQ(msgs[2].data, "not sent");
  22591. }
  22592. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22593. // The first connection sets an id and then sends ids that cannot be carried
  22594. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22595. // with
  22596. std::atomic<int> connection_count{0};
  22597. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22598. if (connection_count++ == 0) {
  22599. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22600. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22601. "text/event-stream");
  22602. } else {
  22603. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22604. "\n\nevent: end\ndata: end\n\n",
  22605. "text/event-stream");
  22606. }
  22607. });
  22608. auto msgs = collect("/id-unsendable");
  22609. ASSERT_EQ(msgs.size(), 1u);
  22610. EXPECT_EQ(msgs[0].data, "42");
  22611. }
  22612. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22613. auto msgs = parse("event: notification\nid: evt-42\n"
  22614. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22615. ASSERT_EQ(msgs.size(), 1u);
  22616. EXPECT_EQ(msgs[0].event, "notification");
  22617. EXPECT_EQ(msgs[0].id, "evt-42");
  22618. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22619. }
  22620. TEST(SSEMessageTest, Clear) {
  22621. sse::SSEMessage msg;
  22622. msg.event = "custom";
  22623. msg.data = "some data";
  22624. msg.id = "123";
  22625. msg.clear();
  22626. EXPECT_EQ(msg.event, "message");
  22627. EXPECT_EQ(msg.data, "");
  22628. EXPECT_EQ(msg.id, "");
  22629. }
  22630. //==============================================================================
  22631. // SSE Integration Tests
  22632. //==============================================================================
  22633. // Test: Successful connection and on_open callback
  22634. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22635. // Add a simple endpoint that sends one event and closes
  22636. server_->Get("/simple-event", [](const Request &, Response &res) {
  22637. res.set_chunked_content_provider(
  22638. "text/event-stream", [](size_t offset, DataSink &sink) {
  22639. if (offset == 0) {
  22640. std::string event = "data: hello\n\n";
  22641. sink.write(event.data(), event.size());
  22642. }
  22643. return false; // Close stream after sending
  22644. });
  22645. });
  22646. Client client("localhost", get_port());
  22647. sse::SSEClient sse(client, "/simple-event");
  22648. std::atomic<bool> open_called{false};
  22649. std::atomic<bool> message_received{false};
  22650. sse.on_open([&open_called]() { open_called.store(true); });
  22651. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22652. if (msg.data == "hello") { message_received.store(true); }
  22653. });
  22654. sse.set_reconnect_interval(100);
  22655. sse.set_max_reconnect_attempts(1);
  22656. // Start async
  22657. sse.start_async();
  22658. // Wait for message to be processed
  22659. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22660. sse.stop();
  22661. EXPECT_TRUE(open_called.load());
  22662. EXPECT_TRUE(message_received.load());
  22663. }
  22664. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22665. // A data line that never ends.
  22666. server_->Get("/endless-line", [](const Request &, Response &res) {
  22667. res.set_chunked_content_provider(
  22668. "text/event-stream", [](size_t offset, DataSink &sink) {
  22669. if (offset == 0) { sink.write("data: ", 6); }
  22670. std::string chunk(64 * 1024, 'A');
  22671. return sink.write(chunk.data(), chunk.size());
  22672. });
  22673. });
  22674. Client client("localhost", get_port());
  22675. sse::SSEClient sse(client, "/endless-line");
  22676. std::atomic<bool> too_long{false};
  22677. sse.on_error([&](Error err) {
  22678. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22679. });
  22680. sse.set_max_reconnect_attempts(1);
  22681. sse.start_async();
  22682. for (int i = 0; i < 500 && !too_long; i++) {
  22683. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22684. }
  22685. sse.stop();
  22686. EXPECT_TRUE(too_long);
  22687. }
  22688. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22689. // Far more in all than the client's payload limit below.
  22690. server_->Get("/many-events", [](const Request &, Response &res) {
  22691. res.set_chunked_content_provider(
  22692. "text/event-stream", [](size_t offset, DataSink &sink) {
  22693. if (offset == 0) {
  22694. std::string events;
  22695. for (int i = 0; i < 1000; i++) {
  22696. events += "data: message\n\n";
  22697. }
  22698. sink.write(events.data(), events.size());
  22699. }
  22700. return false;
  22701. });
  22702. });
  22703. Client client("localhost", get_port());
  22704. client.set_payload_max_length(1024);
  22705. sse::SSEClient sse(client, "/many-events");
  22706. std::atomic<int> messages{0};
  22707. std::atomic<bool> too_large{false};
  22708. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22709. sse.on_error([&](Error err) {
  22710. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22711. });
  22712. sse.set_max_reconnect_attempts(1);
  22713. sse.start_async();
  22714. for (int i = 0; i < 500 && messages < 1000; i++) {
  22715. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22716. }
  22717. sse.stop();
  22718. EXPECT_GE(messages.load(), 1000);
  22719. EXPECT_FALSE(too_large);
  22720. }
  22721. // Test: on_message callback
  22722. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22723. // Endpoint that sends multiple events then closes
  22724. server_->Get("/multi-event", [](const Request &, Response &res) {
  22725. res.set_chunked_content_provider(
  22726. "text/event-stream", [](size_t offset, DataSink &sink) {
  22727. if (offset == 0) {
  22728. std::string events = "data: message1\n\ndata: message2\n\n";
  22729. sink.write(events.data(), events.size());
  22730. }
  22731. return false;
  22732. });
  22733. });
  22734. Client client("localhost", get_port());
  22735. sse::SSEClient sse(client, "/multi-event");
  22736. std::vector<std::string> received_messages;
  22737. std::mutex messages_mutex;
  22738. sse.on_message([&](const sse::SSEMessage &msg) {
  22739. std::lock_guard<std::mutex> lock(messages_mutex);
  22740. received_messages.push_back(msg.data);
  22741. });
  22742. sse.set_reconnect_interval(100);
  22743. sse.set_max_reconnect_attempts(1);
  22744. sse.start_async();
  22745. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22746. sse.stop();
  22747. std::lock_guard<std::mutex> lock(messages_mutex);
  22748. EXPECT_GE(received_messages.size(), 2u);
  22749. if (received_messages.size() >= 2) {
  22750. EXPECT_EQ(received_messages[0], "message1");
  22751. EXPECT_EQ(received_messages[1], "message2");
  22752. }
  22753. }
  22754. // Test: on_event for specific types
  22755. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22756. Client client("localhost", get_port());
  22757. sse::SSEClient sse(client, "/custom-events");
  22758. std::atomic<bool> update_received{false};
  22759. std::atomic<bool> delete_received{false};
  22760. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22761. if (msg.data == "updated") { update_received.store(true); }
  22762. });
  22763. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22764. if (msg.data == "deleted") { delete_received.store(true); }
  22765. });
  22766. sse.set_max_reconnect_attempts(1);
  22767. sse.start_async();
  22768. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22769. sse.stop();
  22770. EXPECT_TRUE(update_received.load());
  22771. EXPECT_TRUE(delete_received.load());
  22772. }
  22773. // Test: on_error callback on connection failure
  22774. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22775. // Connect to a non-existent port
  22776. Client client("localhost", 59999);
  22777. sse::SSEClient sse(client, "/events");
  22778. std::atomic<bool> error_called{false};
  22779. Error received_error = Error::Success;
  22780. sse.on_error([&](Error err) {
  22781. error_called.store(true);
  22782. received_error = err;
  22783. });
  22784. sse.set_reconnect_interval(50);
  22785. sse.set_max_reconnect_attempts(1);
  22786. sse.start_async();
  22787. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22788. sse.stop();
  22789. EXPECT_TRUE(error_called.load());
  22790. EXPECT_NE(received_error, Error::Success);
  22791. }
  22792. // Test: Last-Event-ID header sent on reconnect
  22793. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22794. // Endpoint that sends event with ID
  22795. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22796. res.set_chunked_content_provider(
  22797. "text/event-stream", [](size_t offset, DataSink &sink) {
  22798. if (offset == 0) {
  22799. std::string event = "id: evt-123\ndata: test\n\n";
  22800. sink.write(event.data(), event.size());
  22801. }
  22802. return false;
  22803. });
  22804. });
  22805. Client client("localhost", get_port());
  22806. sse::SSEClient sse(client, "/event-with-id");
  22807. std::atomic<bool> id_received{false};
  22808. sse.on_message([&](const sse::SSEMessage &msg) {
  22809. if (!msg.id.empty()) { id_received.store(true); }
  22810. });
  22811. sse.set_reconnect_interval(100);
  22812. sse.set_max_reconnect_attempts(1);
  22813. sse.start_async();
  22814. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22815. sse.stop();
  22816. EXPECT_TRUE(id_received.load());
  22817. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22818. }
  22819. // Test: last_event_id() read from another thread while start_async() runs
  22820. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22821. // Ids of every length up to 200, so the stored id keeps changing size
  22822. server_->Get("/many-ids", [](const Request &, Response &res) {
  22823. res.set_chunked_content_provider(
  22824. "text/event-stream", [](size_t offset, DataSink &sink) {
  22825. if (offset == 0) {
  22826. std::string events;
  22827. for (size_t i = 0; i < 2000; i++) {
  22828. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22829. events += "data: x\n\n";
  22830. }
  22831. events += "id: end\ndata: x\n\n";
  22832. sink.write(events.data(), events.size());
  22833. }
  22834. return false;
  22835. });
  22836. });
  22837. Client client("localhost", get_port());
  22838. sse::SSEClient sse(client, "/many-ids");
  22839. // Wait out the rest of the test rather than replay the stream
  22840. sse.set_reconnect_interval(10000);
  22841. sse.set_max_reconnect_attempts(1);
  22842. sse.start_async();
  22843. auto well_formed = true;
  22844. std::string id;
  22845. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22846. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22847. id = sse.last_event_id();
  22848. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22849. well_formed = false;
  22850. }
  22851. }
  22852. sse.stop();
  22853. EXPECT_TRUE(well_formed);
  22854. EXPECT_EQ(sse.last_event_id(), "end");
  22855. }
  22856. // Test: Manual stop
  22857. TEST_F(SSEIntegrationTest, ManualStop) {
  22858. // Endpoint that sends one event and stays open briefly. The server outlives
  22859. // this test body, so the provider uses the fixture's flag, not a local.
  22860. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22861. res.set_chunked_content_provider(
  22862. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22863. if (offset == 0) {
  22864. std::string event = "data: connected\n\n";
  22865. sink.write(event.data(), event.size());
  22866. }
  22867. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22868. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22869. }
  22870. return false;
  22871. });
  22872. });
  22873. Client client("localhost", get_port());
  22874. sse::SSEClient sse(client, "/stay-open");
  22875. std::atomic<bool> connected{false};
  22876. sse.on_open([&connected]() { connected.store(true); });
  22877. sse.set_reconnect_interval(100);
  22878. sse.set_max_reconnect_attempts(1);
  22879. sse.start_async();
  22880. // Wait for connection to establish
  22881. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22882. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22883. }
  22884. EXPECT_TRUE(connected.load());
  22885. EXPECT_TRUE(sse.is_connected());
  22886. // Signal handler to stop
  22887. stop_server_.store(true);
  22888. // Stop SSE client
  22889. sse.stop();
  22890. EXPECT_FALSE(sse.is_connected());
  22891. }
  22892. // Sends one event, then nothing until stop is set
  22893. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22894. return [&stop](const Request &, Response &res) {
  22895. res.set_chunked_content_provider(
  22896. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22897. if (offset == 0) {
  22898. std::string event = "data: hello\n\n";
  22899. sink.write(event.data(), event.size());
  22900. }
  22901. while (!stop.load()) {
  22902. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22903. }
  22904. return false;
  22905. });
  22906. };
  22907. }
  22908. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22909. static void check_stop_interrupts_blocked_read(Client &client) {
  22910. client.set_read_timeout(30, 0);
  22911. for (auto by_destructor : {false, true}) {
  22912. std::atomic<bool> received{false};
  22913. std::chrono::steady_clock::time_point start;
  22914. {
  22915. sse::SSEClient sse(client, "/idle-stream");
  22916. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22917. sse.start_async();
  22918. for (int i = 0; i < 500 && !received.load(); ++i) {
  22919. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22920. }
  22921. ASSERT_TRUE(received.load());
  22922. // Let the client block in the next read
  22923. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22924. start = std::chrono::steady_clock::now();
  22925. if (!by_destructor) { sse.stop(); }
  22926. }
  22927. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22928. std::chrono::seconds(2));
  22929. }
  22930. }
  22931. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22932. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22933. Client client("localhost", get_port());
  22934. check_stop_interrupts_blocked_read(client);
  22935. }
  22936. #ifdef CPPHTTPLIB_SSL_ENABLED
  22937. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22939. std::atomic<bool> done{false};
  22940. svr.Get("/idle-stream", idle_event_stream(done));
  22941. auto port = svr.bind_to_any_port(HOST);
  22942. std::thread t([&] { svr.listen_after_bind(); });
  22943. auto se = detail::scope_exit([&] {
  22944. done.store(true);
  22945. svr.stop();
  22946. t.join();
  22947. });
  22948. svr.wait_until_ready();
  22949. Client client("https://localhost:" + std::to_string(port));
  22950. client.enable_server_certificate_verification(false);
  22951. check_stop_interrupts_blocked_read(client);
  22952. }
  22953. #endif
  22954. // Test: SSEClient with custom headers
  22955. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22956. // Setup a server endpoint that checks for custom header
  22957. std::atomic<bool> header_received{false};
  22958. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22959. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22960. header_received.store(true);
  22961. }
  22962. res.set_chunked_content_provider("text/event-stream",
  22963. [](size_t, DataSink &) { return false; });
  22964. });
  22965. Client client("localhost", get_port());
  22966. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22967. sse::SSEClient sse(client, "/header-check", headers);
  22968. sse.set_max_reconnect_attempts(1);
  22969. sse.start_async();
  22970. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22971. sse.stop();
  22972. EXPECT_TRUE(header_received.load());
  22973. }
  22974. // Test: Reconnect interval configuration
  22975. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22976. Client client("localhost", get_port());
  22977. sse::SSEClient sse(client, "/events");
  22978. auto &result = sse.set_reconnect_interval(500);
  22979. // Builder pattern should return reference to self
  22980. EXPECT_EQ(&result, &sse);
  22981. }
  22982. // Test: Max reconnect attempts
  22983. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22984. // Connect to non-existent port to force reconnects
  22985. Client client("localhost", 59998);
  22986. sse::SSEClient sse(client, "/events");
  22987. std::atomic<int> error_count{0};
  22988. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22989. sse.set_reconnect_interval(50);
  22990. sse.set_max_reconnect_attempts(2);
  22991. auto start = std::chrono::steady_clock::now();
  22992. sse.start(); // Blocking call
  22993. auto end = std::chrono::steady_clock::now();
  22994. // Should have stopped after 2 failed attempts
  22995. EXPECT_GE(error_count.load(), 2);
  22996. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22997. auto duration =
  22998. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22999. #ifdef _WIN32
  23000. // Windows is much slower for socket connection failures
  23001. EXPECT_LT(duration.count(), 7000);
  23002. #else
  23003. EXPECT_LT(duration.count(), 1000);
  23004. #endif
  23005. }
  23006. // Test: Multi-line data in integration
  23007. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23008. // Endpoint with multi-line data
  23009. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23010. res.set_chunked_content_provider(
  23011. "text/event-stream", [](size_t offset, DataSink &sink) {
  23012. if (offset == 0) {
  23013. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23014. sink.write(event.data(), event.size());
  23015. }
  23016. return false;
  23017. });
  23018. });
  23019. Client client("localhost", get_port());
  23020. sse::SSEClient sse(client, "/multiline-data");
  23021. std::string received_data;
  23022. std::mutex data_mutex;
  23023. sse.on_message([&](const sse::SSEMessage &msg) {
  23024. std::lock_guard<std::mutex> lock(data_mutex);
  23025. received_data = msg.data;
  23026. });
  23027. sse.set_reconnect_interval(100);
  23028. sse.set_max_reconnect_attempts(1);
  23029. sse.start_async();
  23030. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23031. sse.stop();
  23032. std::lock_guard<std::mutex> lock(data_mutex);
  23033. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23034. }
  23035. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23036. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23037. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23038. DataSink &sink) {
  23039. if (offset == 0) {
  23040. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23041. sink.write(events.data(), events.size());
  23042. }
  23043. return false;
  23044. });
  23045. });
  23046. Client client("localhost", get_port());
  23047. sse::SSEClient sse(client, "/empty-data-lines");
  23048. std::mutex mutex;
  23049. std::condition_variable cv;
  23050. std::vector<std::string> received;
  23051. sse.on_message([&](const sse::SSEMessage &msg) {
  23052. std::lock_guard<std::mutex> lock(mutex);
  23053. received.push_back(msg.data);
  23054. cv.notify_all();
  23055. });
  23056. sse.set_max_reconnect_attempts(1);
  23057. sse.start_async();
  23058. {
  23059. std::unique_lock<std::mutex> lock(mutex);
  23060. cv.wait_for(lock, std::chrono::seconds(2),
  23061. [&] { return received.size() >= 3; });
  23062. }
  23063. sse.stop();
  23064. ASSERT_GE(received.size(), 3u);
  23065. EXPECT_EQ(received[0], "");
  23066. EXPECT_EQ(received[1], "\nhello");
  23067. EXPECT_EQ(received[2], "");
  23068. }
  23069. // Test: Auto-reconnect after server disconnection
  23070. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23071. std::atomic<int> connection_count{0};
  23072. std::atomic<int> message_count{0};
  23073. // Endpoint that sends one event and closes, forcing reconnect
  23074. server_->Get("/reconnect-test",
  23075. [&connection_count](const Request &, Response &res) {
  23076. connection_count.fetch_add(1);
  23077. res.set_chunked_content_provider(
  23078. "text/event-stream", [](size_t offset, DataSink &sink) {
  23079. if (offset == 0) {
  23080. std::string event = "data: hello\n\n";
  23081. sink.write(event.data(), event.size());
  23082. }
  23083. return false; // Close connection after sending
  23084. });
  23085. });
  23086. Client client("localhost", get_port());
  23087. sse::SSEClient sse(client, "/reconnect-test");
  23088. sse.on_message([&message_count](const sse::SSEMessage &) {
  23089. message_count.fetch_add(1);
  23090. });
  23091. sse.set_reconnect_interval(100);
  23092. sse.set_max_reconnect_attempts(3);
  23093. sse.start_async();
  23094. // Wait long enough for multiple reconnects
  23095. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23096. sse.stop();
  23097. // Should have connected multiple times (initial + reconnects)
  23098. EXPECT_GE(connection_count.load(), 2);
  23099. // Should have received messages from multiple connections
  23100. EXPECT_GE(message_count.load(), 2);
  23101. }
  23102. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23103. std::atomic<int> connection_count{0};
  23104. // Neither Content-Length nor chunked: the close ends the stream
  23105. server_->Get("/close-delimited",
  23106. [&connection_count](const Request &, Response &res) {
  23107. connection_count.fetch_add(1);
  23108. res.set_content_provider(
  23109. "text/event-stream", [](size_t offset, DataSink &sink) {
  23110. if (offset == 0) {
  23111. std::string event = "data: hello\n\n";
  23112. sink.write(event.data(), event.size());
  23113. } else {
  23114. sink.done();
  23115. }
  23116. return true;
  23117. });
  23118. });
  23119. Client client("localhost", get_port());
  23120. sse::SSEClient sse(client, "/close-delimited");
  23121. std::atomic<int> error_count{0};
  23122. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23123. sse.set_reconnect_interval(100);
  23124. sse.start_async();
  23125. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23127. }
  23128. sse.stop();
  23129. // Reconnects as after any end of the stream, but reports no error
  23130. EXPECT_GE(connection_count.load(), 2);
  23131. EXPECT_EQ(0, error_count.load());
  23132. }
  23133. // Test: A retry field that is not all ASCII digits is ignored
  23134. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  23135. std::atomic<int> connection_count{0};
  23136. server_->Get("/bad-retry",
  23137. [&connection_count](const Request &, Response &res) {
  23138. connection_count.fetch_add(1);
  23139. res.set_chunked_content_provider(
  23140. "text/event-stream", [](size_t offset, DataSink &sink) {
  23141. if (offset == 0) {
  23142. std::string event = "retry: -1\ndata: hello\n\n";
  23143. sink.write(event.data(), event.size());
  23144. }
  23145. return false;
  23146. });
  23147. });
  23148. Client client("localhost", get_port());
  23149. sse::SSEClient sse(client, "/bad-retry");
  23150. sse.set_reconnect_interval(10000);
  23151. sse.start_async();
  23152. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23153. sse.stop();
  23154. EXPECT_EQ(connection_count.load(), 1);
  23155. }
  23156. // Test: A retry field of all ASCII digits sets the reconnection time
  23157. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23158. std::mutex mutex;
  23159. std::condition_variable cv;
  23160. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23161. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23162. {
  23163. std::lock_guard<std::mutex> lock(mutex);
  23164. connected_at.push_back(std::chrono::steady_clock::now());
  23165. cv.notify_all();
  23166. }
  23167. res.set_chunked_content_provider(
  23168. "text/event-stream", [](size_t offset, DataSink &sink) {
  23169. if (offset == 0) {
  23170. std::string event = "retry: 0\ndata: hello\n\n";
  23171. sink.write(event.data(), event.size());
  23172. }
  23173. return false;
  23174. });
  23175. });
  23176. Client client("localhost", get_port());
  23177. sse::SSEClient sse(client, "/zero-retry");
  23178. sse.set_reconnect_interval(10000);
  23179. sse.start_async();
  23180. {
  23181. std::unique_lock<std::mutex> lock(mutex);
  23182. cv.wait_for(lock, std::chrono::seconds(5),
  23183. [&] { return connected_at.size() >= 2; });
  23184. }
  23185. sse.stop();
  23186. // The server-supplied interval is applied, but never below 100ms, so
  23187. // "retry: 0" does not cause a busy reconnect loop
  23188. std::lock_guard<std::mutex> lock(mutex);
  23189. ASSERT_GE(connected_at.size(), 2u);
  23190. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23191. connected_at[1] - connected_at[0])
  23192. .count();
  23193. EXPECT_GE(interval_ms, 100);
  23194. }
  23195. // Test: Last-Event-ID sent on reconnect
  23196. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23197. std::atomic<int> connection_count{0};
  23198. std::vector<std::string> received_last_event_ids;
  23199. std::mutex id_mutex;
  23200. // Endpoint that checks Last-Event-ID header and sends event with ID
  23201. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23202. int conn = connection_count.fetch_add(1);
  23203. // Capture the Last-Event-ID header from each connection
  23204. {
  23205. std::lock_guard<std::mutex> lock(id_mutex);
  23206. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23207. }
  23208. res.set_chunked_content_provider(
  23209. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23210. if (offset == 0) {
  23211. std::string event =
  23212. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23213. sink.write(event.data(), event.size());
  23214. }
  23215. return false;
  23216. });
  23217. });
  23218. Client client("localhost", get_port());
  23219. sse::SSEClient sse(client, "/reconnect-with-id");
  23220. sse.set_reconnect_interval(100);
  23221. sse.set_max_reconnect_attempts(3);
  23222. sse.start_async();
  23223. // Wait for at least 2 connections
  23224. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23225. sse.stop();
  23226. // Verify behavior
  23227. std::lock_guard<std::mutex> lock(id_mutex);
  23228. EXPECT_GE(received_last_event_ids.size(), 2u);
  23229. // First connection should have no Last-Event-ID
  23230. if (!received_last_event_ids.empty()) {
  23231. EXPECT_EQ(received_last_event_ids[0], "");
  23232. }
  23233. // Second connection should have Last-Event-ID from first connection
  23234. if (received_last_event_ids.size() >= 2) {
  23235. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23236. }
  23237. }
  23238. // Test: set_headers updates headers used on reconnect
  23239. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23240. std::vector<std::string> received_tokens;
  23241. std::mutex token_mutex;
  23242. // Endpoint that captures Authorization header
  23243. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23244. {
  23245. std::lock_guard<std::mutex> lock(token_mutex);
  23246. received_tokens.push_back(req.get_header_value("Authorization"));
  23247. }
  23248. res.set_chunked_content_provider(
  23249. "text/event-stream", [](size_t offset, DataSink &sink) {
  23250. if (offset == 0) {
  23251. std::string event = "data: hello\n\n";
  23252. sink.write(event.data(), event.size());
  23253. }
  23254. return false; // Close connection to trigger reconnect
  23255. });
  23256. });
  23257. Client client("localhost", get_port());
  23258. Headers headers = {{"Authorization", "Bearer old-token"}};
  23259. sse::SSEClient sse(client, "/auth-check", headers);
  23260. // Update headers on each successful connection
  23261. sse.on_open(
  23262. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23263. sse.set_reconnect_interval(100);
  23264. sse.set_max_reconnect_attempts(3);
  23265. sse.start_async();
  23266. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23267. sse.stop();
  23268. std::lock_guard<std::mutex> lock(token_mutex);
  23269. ASSERT_GE(received_tokens.size(), 2u);
  23270. // First connection uses original header
  23271. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23272. // Second connection uses updated header from set_headers
  23273. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23274. }
  23275. // Test: 401 allows reconnection (so on_error can refresh headers)
  23276. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23277. std::atomic<int> connection_count{0};
  23278. // Endpoint: returns 401 on first attempt, 200 on second
  23279. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23280. int conn = connection_count.fetch_add(1);
  23281. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23282. res.status = StatusCode::Unauthorized_401;
  23283. res.set_content("Unauthorized", "text/plain");
  23284. return;
  23285. }
  23286. res.set_chunked_content_provider(
  23287. "text/event-stream", [](size_t offset, DataSink &sink) {
  23288. if (offset == 0) {
  23289. std::string event = "data: authenticated\n\n";
  23290. sink.write(event.data(), event.size());
  23291. }
  23292. return false;
  23293. });
  23294. });
  23295. Client client("localhost", get_port());
  23296. Headers headers = {{"Authorization", "Bearer expired"}};
  23297. sse::SSEClient sse(client, "/auth-retry", headers);
  23298. std::atomic<bool> message_received{false};
  23299. // Refresh token on error
  23300. sse.on_error(
  23301. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23302. sse.on_message([&](const sse::SSEMessage &msg) {
  23303. if (msg.data == "authenticated") { message_received.store(true); }
  23304. });
  23305. sse.set_reconnect_interval(100);
  23306. sse.set_max_reconnect_attempts(3);
  23307. sse.start_async();
  23308. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23309. sse.stop();
  23310. // Should have reconnected after 401 and succeeded with new token
  23311. EXPECT_GE(connection_count.load(), 2);
  23312. EXPECT_TRUE(message_received.load());
  23313. }
  23314. TEST(Issue2318Test, EmptyHostString) {
  23315. {
  23316. httplib::Client cli_empty("", PORT);
  23317. auto res = cli_empty.Get("/");
  23318. ASSERT_FALSE(res);
  23319. EXPECT_EQ(httplib::Error::Connection, res.error());
  23320. }
  23321. {
  23322. httplib::Client cli(" ", PORT);
  23323. auto res = cli.Get("/");
  23324. ASSERT_FALSE(res);
  23325. EXPECT_EQ(httplib::Error::Connection, res.error());
  23326. }
  23327. }
  23328. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23329. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23330. Server svr;
  23331. // Set a small payload limit (1KB)
  23332. svr.set_payload_max_length(1024);
  23333. svr.Post("/test", [&](const Request &req, Response &res) {
  23334. res.set_content("Body size: " + std::to_string(req.body.size()),
  23335. "text/plain");
  23336. });
  23337. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23338. auto se = detail::scope_exit([&] {
  23339. svr.stop();
  23340. listen_thread.join();
  23341. });
  23342. svr.wait_until_ready();
  23343. // Create data that compresses well but exceeds limit when decompressed
  23344. // 8KB of repeated null bytes compresses to a very small size
  23345. std::string original_data(8 * 1024, '\0');
  23346. // Compress the data using gzip
  23347. std::string compressed_data;
  23348. detail::gzip_compressor compressor;
  23349. compressor.compress(original_data.data(), original_data.size(), true,
  23350. [&](const char *data, size_t size) {
  23351. compressed_data.append(data, size);
  23352. return true;
  23353. });
  23354. // Verify compression worked (compressed should be much smaller)
  23355. ASSERT_LT(compressed_data.size(), original_data.size());
  23356. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23357. // Send compressed data with Content-Encoding: gzip
  23358. Client cli(HOST, PORT);
  23359. Headers headers = {{"Content-Encoding", "gzip"}};
  23360. auto res =
  23361. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23362. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23364. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23365. }
  23366. #endif
  23367. // ============================================================================
  23368. // OpenSSL-Specific Tests
  23369. // ============================================================================
  23370. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23371. X509 *readCertificate(const std::string &strFileName) {
  23372. std::ifstream inStream(strFileName);
  23373. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23374. std::istreambuf_iterator<char>());
  23375. if (strCertPEM.empty()) return (nullptr);
  23376. BIO *pbCert = BIO_new(BIO_s_mem());
  23377. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23378. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23379. BIO_free(pbCert);
  23380. return (pCert);
  23381. }
  23382. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23383. std::ifstream inStream(strFileName);
  23384. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23385. std::istreambuf_iterator<char>());
  23386. if (strPrivateKeyPEM.empty()) return (nullptr);
  23387. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23388. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23389. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23390. BIO_free(pbPrivKey);
  23391. return (pPrivateKey);
  23392. }
  23393. TEST(BindServerTest, UpdateCerts) {
  23394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23395. int port = svr.bind_to_any_port("0.0.0.0");
  23396. ASSERT_TRUE(svr.is_valid());
  23397. ASSERT_TRUE(port > 0);
  23398. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23399. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23400. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23401. ASSERT_TRUE(cert != nullptr);
  23402. ASSERT_TRUE(ca_cert != nullptr);
  23403. ASSERT_TRUE(key != nullptr);
  23404. X509_STORE *cert_store = X509_STORE_new();
  23405. X509_STORE_add_cert(cert_store, ca_cert);
  23406. // svr.update_certs(cert, key, cert_store); // deprecated
  23407. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23408. CLIENT_CA_CERT_FILE);
  23409. ASSERT_TRUE(svr.is_valid());
  23410. svr.stop();
  23411. X509_STORE_free(cert_store);
  23412. X509_free(cert);
  23413. X509_free(ca_cert);
  23414. EVP_PKEY_free(key);
  23415. }
  23416. // Test that update_certs() updates client CA list correctly
  23417. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23418. // Start with file-based constructor
  23419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23420. ASSERT_TRUE(svr.is_valid());
  23421. // Initially no client CA list should be set
  23422. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23423. ASSERT_TRUE(ssl_ctx != nullptr);
  23424. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23425. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23426. // Now update with client CA (PEM string)
  23427. std::string cert_pem, key_pem, ca_pem;
  23428. read_file(SERVER_CERT_FILE, cert_pem);
  23429. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23430. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23431. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23432. ASSERT_TRUE(svr.is_valid());
  23433. // Now client CA list should be set
  23434. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23435. ASSERT_TRUE(ca_list_after != nullptr);
  23436. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23437. }
  23438. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23439. // Test that the file-path SSLServer constructor properly sets the client CA
  23440. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23442. ASSERT_TRUE(svr.is_valid());
  23443. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23444. ASSERT_TRUE(ssl_ctx != nullptr);
  23445. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23446. ASSERT_TRUE(ca_list != nullptr);
  23447. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23448. }
  23449. #endif
  23450. // ============================================================================
  23451. // MbedTLS-Specific Tests
  23452. // ============================================================================
  23453. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23454. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23455. using namespace httplib::tls;
  23456. // Track if callback was invoked
  23457. bool callback_invoked = false;
  23458. // The callback receives void* ctx which is actually MbedTlsContext*
  23459. // We can access the mbedtls_ssl_config via the context
  23460. auto setup_callback = [&callback_invoked](void *ctx) {
  23461. callback_invoked = true;
  23462. // Cast to MbedTlsContext* to access the ssl config
  23463. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23464. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23465. // Use static variables to hold certificate data (simplified for test)
  23466. static mbedtls_x509_crt own_cert;
  23467. static mbedtls_pk_context own_key;
  23468. static mbedtls_x509_crt ca_chain;
  23469. static bool initialized = false;
  23470. if (!initialized) {
  23471. mbedtls_x509_crt_init(&own_cert);
  23472. mbedtls_pk_init(&own_key);
  23473. mbedtls_x509_crt_init(&ca_chain);
  23474. // Load server certificate
  23475. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23476. return false;
  23477. }
  23478. // Load server private key.
  23479. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23480. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23481. #if MBEDTLS_VERSION_MAJOR == 3
  23482. ,
  23483. mbedtls_ctr_drbg_random, nullptr
  23484. #endif
  23485. ) != 0) {
  23486. return false;
  23487. }
  23488. // Load CA chain for client verification
  23489. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23490. return false;
  23491. }
  23492. initialized = true;
  23493. }
  23494. // Configure the SSL config
  23495. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23496. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23497. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23498. // Set minimum TLS version using mbedTLS native API
  23499. #if MBEDTLS_VERSION_MAJOR >= 3
  23500. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23501. #else
  23502. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23503. MBEDTLS_SSL_MINOR_VERSION_3);
  23504. #endif
  23505. return true;
  23506. };
  23507. SSLServer svr(setup_callback);
  23508. ASSERT_TRUE(svr.is_valid());
  23509. ASSERT_TRUE(callback_invoked);
  23510. svr.Get("/test", [&](const Request &req, Response &res) {
  23511. res.set_content("test", "text/plain");
  23512. auto cert = req.peer_cert();
  23513. ASSERT_TRUE(static_cast<bool>(cert));
  23514. auto common_name = cert.subject_cn();
  23515. EXPECT_EQ("Common Name", common_name);
  23516. });
  23517. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23518. auto se = detail::scope_exit([&] {
  23519. svr.stop();
  23520. t.join();
  23521. ASSERT_FALSE(svr.is_running());
  23522. });
  23523. svr.wait_until_ready();
  23524. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23525. cli.enable_server_certificate_verification(false);
  23526. cli.set_connection_timeout(30);
  23527. auto res = cli.Get("/test");
  23528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23529. ASSERT_EQ(StatusCode::OK_200, res->status);
  23530. }
  23531. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23532. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23533. // keep-alive SSL session, which reads through that config in
  23534. // mbedtls_ssl_close_notify.
  23535. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23536. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23537. ASSERT_TRUE(svr.is_valid());
  23538. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23539. res.set_content("test", "text/plain");
  23540. });
  23541. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23542. auto se = detail::scope_exit([&] {
  23543. svr.stop();
  23544. t.join();
  23545. ASSERT_FALSE(svr.is_running());
  23546. });
  23547. svr.wait_until_ready();
  23548. {
  23549. SSLClient cli(HOST, PORT);
  23550. cli.enable_server_certificate_verification(false);
  23551. cli.set_keep_alive(true);
  23552. auto res = cli.Get("/test");
  23553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23554. ASSERT_EQ(StatusCode::OK_200, res->status);
  23555. // cli is destructed here with the keep-alive SSL session still open.
  23556. }
  23557. }
  23558. #endif
  23559. // WebSocket Tests
  23560. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23561. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23562. // defining the meaning of these bits has been negotiated.
  23563. auto make_frame = [](uint8_t first_byte) {
  23564. std::string frame;
  23565. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23566. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23567. frame += "Hello";
  23568. return frame;
  23569. };
  23570. // RSV1 set (0x40)
  23571. {
  23572. detail::BufferStream strm;
  23573. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23574. ws::Opcode opcode;
  23575. std::string payload;
  23576. bool fin;
  23577. EXPECT_EQ(
  23578. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23579. ws::impl::FrameRead::Fail);
  23580. }
  23581. // RSV2 set (0x20)
  23582. {
  23583. detail::BufferStream strm;
  23584. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23585. ws::Opcode opcode;
  23586. std::string payload;
  23587. bool fin;
  23588. EXPECT_EQ(
  23589. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23590. ws::impl::FrameRead::Fail);
  23591. }
  23592. // RSV3 set (0x10)
  23593. {
  23594. detail::BufferStream strm;
  23595. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23596. ws::Opcode opcode;
  23597. std::string payload;
  23598. bool fin;
  23599. EXPECT_EQ(
  23600. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23601. ws::impl::FrameRead::Fail);
  23602. }
  23603. // No RSV bits set - should succeed
  23604. {
  23605. detail::BufferStream strm;
  23606. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23607. ws::Opcode opcode;
  23608. std::string payload;
  23609. bool fin;
  23610. EXPECT_EQ(
  23611. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23612. ws::impl::FrameRead::Ok);
  23613. EXPECT_EQ(ws::Opcode::Text, opcode);
  23614. EXPECT_EQ("Hello", payload);
  23615. EXPECT_TRUE(fin);
  23616. }
  23617. }
  23618. TEST(WebSocketTest, ControlFrameValidation) {
  23619. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23620. // payload length <= 125.
  23621. // Ping with FIN=0 - must be rejected
  23622. {
  23623. detail::BufferStream strm;
  23624. std::string frame;
  23625. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23626. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23627. strm.write(frame.data(), frame.size());
  23628. ws::Opcode opcode;
  23629. std::string payload;
  23630. bool fin;
  23631. EXPECT_EQ(
  23632. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23633. ws::impl::FrameRead::Fail);
  23634. }
  23635. // Close with FIN=0 - must be rejected
  23636. {
  23637. detail::BufferStream strm;
  23638. std::string frame;
  23639. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23640. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23641. strm.write(frame.data(), frame.size());
  23642. ws::Opcode opcode;
  23643. std::string payload;
  23644. bool fin;
  23645. EXPECT_EQ(
  23646. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23647. ws::impl::FrameRead::Fail);
  23648. }
  23649. // Ping with payload_len=126 (extended length) - must be rejected
  23650. {
  23651. detail::BufferStream strm;
  23652. std::string frame;
  23653. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23654. frame += static_cast<char>(126); // payload_len=126 (>125)
  23655. frame += static_cast<char>(0x00); // extended length high byte
  23656. frame += static_cast<char>(126); // extended length low byte
  23657. frame += std::string(126, 'x');
  23658. strm.write(frame.data(), frame.size());
  23659. ws::Opcode opcode;
  23660. std::string payload;
  23661. bool fin;
  23662. EXPECT_EQ(
  23663. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23664. ws::impl::FrameRead::Fail);
  23665. }
  23666. // Ping with FIN=1 and payload_len=125 - should succeed
  23667. {
  23668. detail::BufferStream strm;
  23669. std::string frame;
  23670. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23671. frame += static_cast<char>(125); // payload_len=125
  23672. frame += std::string(125, 'x');
  23673. strm.write(frame.data(), frame.size());
  23674. ws::Opcode opcode;
  23675. std::string payload;
  23676. bool fin;
  23677. EXPECT_EQ(
  23678. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23679. ws::impl::FrameRead::Ok);
  23680. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23681. EXPECT_EQ(125u, payload.size());
  23682. EXPECT_TRUE(fin);
  23683. }
  23684. }
  23685. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23686. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23687. // length MUST be 0.
  23688. // MSB set - must be rejected
  23689. {
  23690. detail::BufferStream strm;
  23691. std::string frame;
  23692. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23693. frame += static_cast<char>(127); // 64-bit extended length
  23694. frame += static_cast<char>(0x80); // MSB set (invalid)
  23695. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23696. strm.write(frame.data(), frame.size());
  23697. ws::Opcode opcode;
  23698. std::string payload;
  23699. bool fin;
  23700. EXPECT_EQ(
  23701. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23702. ws::impl::FrameRead::Fail);
  23703. }
  23704. // MSB clear - should pass length parsing (will be rejected by max_len,
  23705. // but that's a different check; use a small length to verify)
  23706. {
  23707. detail::BufferStream strm;
  23708. std::string frame;
  23709. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23710. frame += static_cast<char>(127); // 64-bit extended length
  23711. frame += std::string(7, '\0'); // high bytes = 0
  23712. frame += static_cast<char>(0x03); // length = 3
  23713. frame += "abc";
  23714. strm.write(frame.data(), frame.size());
  23715. ws::Opcode opcode;
  23716. std::string payload;
  23717. bool fin;
  23718. EXPECT_EQ(
  23719. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23720. ws::impl::FrameRead::Ok);
  23721. EXPECT_EQ(ws::Opcode::Text, opcode);
  23722. EXPECT_EQ("abc", payload);
  23723. }
  23724. }
  23725. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23726. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23727. // Valid UTF-8
  23728. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23729. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23730. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23731. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23732. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23733. // Invalid UTF-8
  23734. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23735. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23736. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23737. EXPECT_FALSE(
  23738. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23739. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23740. }
  23741. TEST(WebSocketTest, ConnectAndDisconnect) {
  23742. Server svr;
  23743. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23744. std::string msg;
  23745. while (ws.read(msg)) {}
  23746. });
  23747. auto port = svr.bind_to_any_port(HOST);
  23748. std::thread t([&]() { svr.listen_after_bind(); });
  23749. svr.wait_until_ready();
  23750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23751. auto res = client.connect();
  23752. ASSERT_TRUE(res);
  23753. EXPECT_EQ(Error::Success, res.error());
  23754. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23755. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23756. EXPECT_TRUE(client.is_open());
  23757. client.close();
  23758. EXPECT_FALSE(client.is_open());
  23759. svr.stop();
  23760. t.join();
  23761. }
  23762. TEST(WebSocketTest, ValidURL) {
  23763. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23764. EXPECT_TRUE(ws1.is_valid());
  23765. ws::WebSocketClient ws2("ws://example.com/path");
  23766. EXPECT_TRUE(ws2.is_valid());
  23767. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23768. EXPECT_TRUE(ws3.is_valid());
  23769. #ifdef CPPHTTPLIB_SSL_ENABLED
  23770. ws::WebSocketClient wss1("wss://example.com/path");
  23771. EXPECT_TRUE(wss1.is_valid());
  23772. ws::WebSocketClient wss2("wss://example.com:443/path");
  23773. EXPECT_TRUE(wss2.is_valid());
  23774. #endif
  23775. }
  23776. TEST(WebSocketTest, InvalidURL) {
  23777. // No scheme
  23778. ws::WebSocketClient ws1("localhost:8080/path");
  23779. EXPECT_FALSE(ws1.is_valid());
  23780. // No path
  23781. ws::WebSocketClient ws2("ws://localhost:8080");
  23782. EXPECT_FALSE(ws2.is_valid());
  23783. // Empty string
  23784. ws::WebSocketClient ws3("");
  23785. EXPECT_FALSE(ws3.is_valid());
  23786. // Missing host
  23787. ws::WebSocketClient ws4("ws://:8080/path");
  23788. EXPECT_FALSE(ws4.is_valid());
  23789. // Port number overflow — should not crash
  23790. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23791. EXPECT_FALSE(ws5.is_valid());
  23792. // Port out of range
  23793. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23794. EXPECT_FALSE(ws6.is_valid());
  23795. }
  23796. TEST(WebSocketTest, UnsupportedScheme) {
  23797. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23798. ws::WebSocketClient ws1("http://localhost:8080/path");
  23799. EXPECT_FALSE(ws1.is_valid());
  23800. ws::WebSocketClient ws2("https://localhost:8080/path");
  23801. EXPECT_FALSE(ws2.is_valid());
  23802. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23803. EXPECT_FALSE(ws3.is_valid());
  23804. #else
  23805. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23806. std::invalid_argument);
  23807. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23808. std::invalid_argument);
  23809. #endif
  23810. }
  23811. TEST(WebSocketTest, ConnectWhenInvalid) {
  23812. ws::WebSocketClient ws("not a valid url");
  23813. EXPECT_FALSE(ws.is_valid());
  23814. auto res = ws.connect();
  23815. EXPECT_FALSE(res);
  23816. EXPECT_EQ(Error::Connection, res.error());
  23817. EXPECT_EQ(-1, res.status());
  23818. }
  23819. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23820. // Grab a port that is free, then close it again so nothing listens there
  23821. Server svr;
  23822. auto port = svr.bind_to_any_port(HOST);
  23823. svr.stop();
  23824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23825. auto res = client.connect();
  23826. ASSERT_FALSE(res);
  23827. EXPECT_EQ(Error::Connection, res.error());
  23828. EXPECT_EQ(-1, res.status());
  23829. }
  23830. TEST(WebSocketTest, DefaultPort) {
  23831. ws::WebSocketClient ws1("ws://example.com/path");
  23832. EXPECT_TRUE(ws1.is_valid());
  23833. // ws:// defaults to port 80 (verified by successful parse)
  23834. #ifdef CPPHTTPLIB_SSL_ENABLED
  23835. ws::WebSocketClient ws2("wss://example.com/path");
  23836. EXPECT_TRUE(ws2.is_valid());
  23837. // wss:// defaults to port 443 (verified by successful parse)
  23838. #endif
  23839. }
  23840. TEST(WebSocketTest, IPv6LiteralAddress) {
  23841. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23842. EXPECT_TRUE(ws1.is_valid());
  23843. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23844. EXPECT_TRUE(ws2.is_valid());
  23845. }
  23846. TEST(WebSocketTest, ComplexPath) {
  23847. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23848. EXPECT_TRUE(ws1.is_valid());
  23849. ws::WebSocketClient ws2("ws://localhost:8080/");
  23850. EXPECT_TRUE(ws2.is_valid());
  23851. }
  23852. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23853. Server svr;
  23854. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23855. std::string msg;
  23856. while (ws.read(msg)) {}
  23857. });
  23858. auto port = svr.bind_to_any_port(HOST);
  23859. std::thread t([&]() { svr.listen_after_bind(); });
  23860. svr.wait_until_ready();
  23861. auto another_host = "example.com";
  23862. auto wrong_ip = "192.0.2.1";
  23863. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23864. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  23865. ASSERT_TRUE(client.connect());
  23866. EXPECT_TRUE(client.is_open());
  23867. client.close();
  23868. svr.stop();
  23869. t.join();
  23870. }
  23871. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23872. Server svr;
  23873. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23874. std::string msg;
  23875. while (ws.read(msg)) {}
  23876. });
  23877. auto port = svr.bind_to_any_port(HOST);
  23878. std::thread t([&]() { svr.listen_after_bind(); });
  23879. svr.wait_until_ready();
  23880. auto wrong_ip = "192.0.2.1";
  23881. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23882. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  23883. client.set_connection_timeout(1);
  23884. client.set_read_timeout(1);
  23885. client.set_write_timeout(1);
  23886. EXPECT_FALSE(client.connect());
  23887. EXPECT_FALSE(client.is_open());
  23888. svr.stop();
  23889. t.join();
  23890. }
  23891. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23892. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23893. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23894. // (RFC 6761) is only a map key and the Host header value.
  23895. auto host = "target.invalid";
  23896. Server svr;
  23897. std::string received_host;
  23898. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23899. received_host = req.get_header_value("Host");
  23900. std::string msg;
  23901. while (ws.read(msg)) {}
  23902. });
  23903. auto port = svr.bind_to_any_port(HOST);
  23904. std::thread t([&]() { svr.listen_after_bind(); });
  23905. // ASSERT_* below returns from the test body, which would leave t joinable
  23906. // and make ~thread call std::terminate.
  23907. auto se = detail::scope_exit([&] {
  23908. svr.stop();
  23909. if (t.joinable()) { t.join(); }
  23910. });
  23911. svr.wait_until_ready();
  23912. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23913. std::to_string(port) + "/ws");
  23914. client.set_direct_hostname_addr_map({{host, HOST}});
  23915. ASSERT_TRUE(client.connect());
  23916. EXPECT_TRUE(client.is_open());
  23917. client.close();
  23918. svr.stop();
  23919. t.join();
  23920. // The mapping only redirects the connection; the identity stays host_.
  23921. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23922. }
  23923. class WebSocketIntegrationTest : public ::testing::Test {
  23924. protected:
  23925. void SetUp() override {
  23926. server_ = httplib::detail::make_unique<Server>();
  23927. setup_server();
  23928. start_server();
  23929. }
  23930. void TearDown() override {
  23931. server_->stop();
  23932. if (server_thread_.joinable()) { server_thread_.join(); }
  23933. }
  23934. void setup_server() {
  23935. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23936. std::string msg;
  23937. ws::ReadResult ret;
  23938. while ((ret = ws.read(msg))) {
  23939. if (ret == ws::Binary) {
  23940. ws.send(msg.data(), msg.size());
  23941. } else {
  23942. ws.send(msg);
  23943. }
  23944. }
  23945. });
  23946. server_->WebSocket("/ws-echo-string",
  23947. [](const Request &, ws::WebSocket &ws) {
  23948. std::string msg;
  23949. while (ws.read(msg)) {
  23950. ws.send("echo: " + msg);
  23951. }
  23952. });
  23953. server_->WebSocket(
  23954. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23955. // Echo back request metadata
  23956. ws.send("path:" + req.path);
  23957. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23958. std::string msg;
  23959. while (ws.read(msg)) {}
  23960. });
  23961. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23962. std::string msg;
  23963. ws.read(msg); // wait for a message
  23964. ws.close();
  23965. });
  23966. server_->WebSocket("/ws-close-status",
  23967. [](const Request &, ws::WebSocket &ws) {
  23968. std::string msg;
  23969. ws.read(msg); // wait for a message
  23970. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23971. });
  23972. server_->WebSocket(
  23973. "/ws-subprotocol",
  23974. [](const Request &, ws::WebSocket &ws) {
  23975. std::string msg;
  23976. while (ws.read(msg)) {
  23977. ws.send(msg);
  23978. }
  23979. },
  23980. [](const std::vector<std::string> &protocols) -> std::string {
  23981. for (const auto &p : protocols) {
  23982. if (p == "graphql-ws") { return p; }
  23983. }
  23984. return "";
  23985. });
  23986. server_->WebSocket(
  23987. "/ws-subprotocol-unoffered",
  23988. [](const Request &, ws::WebSocket &ws) {
  23989. std::string msg;
  23990. while (ws.read(msg)) {
  23991. ws.send(msg);
  23992. }
  23993. },
  23994. [](const std::vector<std::string> &) -> std::string {
  23995. return "admin";
  23996. });
  23997. }
  23998. void start_server() {
  23999. port_ = server_->bind_to_any_port(HOST);
  24000. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24001. server_->wait_until_ready();
  24002. }
  24003. std::unique_ptr<Server> server_;
  24004. std::thread server_thread_;
  24005. int port_ = 0;
  24006. };
  24007. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24009. "/ws-echo");
  24010. ASSERT_TRUE(client.connect());
  24011. ASSERT_TRUE(client.is_open());
  24012. ASSERT_TRUE(client.send("Hello WebSocket"));
  24013. std::string msg;
  24014. EXPECT_EQ(ws::Text, client.read(msg));
  24015. EXPECT_EQ("Hello WebSocket", msg);
  24016. client.close();
  24017. }
  24018. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24020. "/ws-echo");
  24021. ASSERT_TRUE(client.connect());
  24022. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24023. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24024. std::string msg;
  24025. EXPECT_EQ(ws::Binary, client.read(msg));
  24026. EXPECT_EQ(binary_data, msg);
  24027. client.close();
  24028. }
  24029. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24030. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24031. "/ws-echo");
  24032. ASSERT_TRUE(client.connect());
  24033. for (int i = 0; i < 10; i++) {
  24034. auto text = "message " + std::to_string(i);
  24035. ASSERT_TRUE(client.send(text));
  24036. std::string msg;
  24037. ASSERT_TRUE(client.read(msg));
  24038. EXPECT_EQ(text, msg);
  24039. }
  24040. client.close();
  24041. }
  24042. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24044. "/ws-close");
  24045. ASSERT_TRUE(client.connect());
  24046. // Send a message to trigger the server to close
  24047. ASSERT_TRUE(client.send("trigger close"));
  24048. // The server will close, so read should return false
  24049. std::string msg;
  24050. EXPECT_FALSE(client.read(msg));
  24051. EXPECT_FALSE(client.is_open());
  24052. }
  24053. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24054. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24055. "/ws-echo");
  24056. ASSERT_TRUE(client.connect());
  24057. // 128KB message
  24058. std::string large_data(128 * 1024, 'X');
  24059. ASSERT_TRUE(client.send(large_data));
  24060. std::string msg;
  24061. ASSERT_TRUE(client.read(msg));
  24062. EXPECT_EQ(large_data, msg);
  24063. client.close();
  24064. }
  24065. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24067. "/ws-echo");
  24068. ASSERT_TRUE(client.connect());
  24069. const int num_threads = 4;
  24070. std::vector<std::thread> threads;
  24071. std::atomic<int> send_count{0};
  24072. for (int t = 0; t < num_threads; t++) {
  24073. threads.emplace_back([&client, &send_count, t]() {
  24074. for (int i = 0; i < 5; i++) {
  24075. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24076. if (client.send(text)) { send_count++; }
  24077. }
  24078. });
  24079. }
  24080. for (auto &th : threads) {
  24081. th.join();
  24082. }
  24083. int received = 0;
  24084. std::string msg;
  24085. while (received < send_count.load()) {
  24086. if (!client.read(msg)) { break; }
  24087. received++;
  24088. }
  24089. EXPECT_EQ(send_count.load(), received);
  24090. client.close();
  24091. }
  24092. TEST_F(WebSocketIntegrationTest, ReadString) {
  24093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24094. "/ws-echo-string");
  24095. ASSERT_TRUE(client.connect());
  24096. ASSERT_TRUE(client.send("hello"));
  24097. std::string msg;
  24098. ASSERT_TRUE(client.read(msg));
  24099. EXPECT_EQ("echo: hello", msg);
  24100. ASSERT_TRUE(client.send("world"));
  24101. ASSERT_TRUE(client.read(msg));
  24102. EXPECT_EQ("echo: world", msg);
  24103. client.close();
  24104. }
  24105. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24106. Headers headers = {{"X-Test-Header", "test-value"}};
  24107. ws::WebSocketClient client(
  24108. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24109. ASSERT_TRUE(client.connect());
  24110. std::string msg;
  24111. ASSERT_TRUE(client.read(msg));
  24112. EXPECT_EQ("path:/ws-request-info", msg);
  24113. ASSERT_TRUE(client.read(msg));
  24114. EXPECT_EQ("header:test-value", msg);
  24115. client.close();
  24116. }
  24117. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24118. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24119. "/ws-echo");
  24120. client.set_read_timeout(1, 0); // 1 second
  24121. ASSERT_TRUE(client.connect());
  24122. // Don't send anything — server echo handler waits for a message, so read()
  24123. // should time out. The connection survives it: nothing was consumed.
  24124. std::string msg;
  24125. EXPECT_EQ(client.read(msg), ws::Timeout);
  24126. EXPECT_TRUE(client.is_open());
  24127. // And it is still usable afterwards.
  24128. EXPECT_TRUE(client.send("after timeout"));
  24129. EXPECT_EQ(client.read(msg), ws::Text);
  24130. EXPECT_EQ(msg, "after timeout");
  24131. }
  24132. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24133. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24134. "/ws-echo");
  24135. client.set_read_timeout(1, 0);
  24136. ASSERT_TRUE(client.connect());
  24137. ASSERT_TRUE(client.send("first"));
  24138. std::string msg;
  24139. ASSERT_EQ(client.read(msg), ws::Text);
  24140. ASSERT_EQ(msg, "first");
  24141. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24142. // not be used with a read timeout: it would reprocess the previous message.
  24143. EXPECT_EQ(client.read(msg), ws::Timeout);
  24144. EXPECT_EQ(msg, "first");
  24145. }
  24146. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24147. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24148. "/ws-echo");
  24149. ASSERT_TRUE(client.connect());
  24150. // Setting it once the connection is open reaches the live stream, not just
  24151. // the seed for the next connect().
  24152. client.set_read_timeout(1, 0);
  24153. std::string msg;
  24154. EXPECT_EQ(client.read(msg), ws::Timeout);
  24155. EXPECT_TRUE(client.is_open());
  24156. }
  24157. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24158. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24159. "/ws-echo");
  24160. client.set_read_timeout(5, 0);
  24161. ASSERT_TRUE(client.connect());
  24162. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24163. // The server should reject it and close the connection.
  24164. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24165. client.send(oversized);
  24166. // The server's read() should have failed due to payload limit,
  24167. // so our read() should return false (connection closed).
  24168. std::string msg;
  24169. EXPECT_FALSE(client.read(msg));
  24170. }
  24171. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24172. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24173. "/ws-echo");
  24174. client.set_read_timeout(10, 0);
  24175. ASSERT_TRUE(client.connect());
  24176. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24177. // This should succeed.
  24178. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24179. ASSERT_TRUE(client.send(at_limit));
  24180. std::string msg;
  24181. ASSERT_TRUE(client.read(msg));
  24182. EXPECT_EQ(at_limit.size(), msg.size());
  24183. client.close();
  24184. }
  24185. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24187. "/nonexistent");
  24188. auto res = client.connect();
  24189. EXPECT_FALSE(res);
  24190. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24191. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24192. EXPECT_FALSE(client.is_open());
  24193. }
  24194. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24196. "/ws-echo");
  24197. ASSERT_TRUE(client.connect());
  24198. ASSERT_TRUE(client.send(""));
  24199. std::string msg;
  24200. EXPECT_EQ(ws::Text, client.read(msg));
  24201. EXPECT_EQ("", msg);
  24202. client.close();
  24203. }
  24204. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24205. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24206. "/ws-echo");
  24207. // First connection
  24208. ASSERT_TRUE(client.connect());
  24209. ASSERT_TRUE(client.send("first"));
  24210. std::string msg;
  24211. ASSERT_TRUE(client.read(msg));
  24212. EXPECT_EQ("first", msg);
  24213. client.close();
  24214. EXPECT_FALSE(client.is_open());
  24215. // Reconnect using the same client object
  24216. ASSERT_TRUE(client.connect());
  24217. ASSERT_TRUE(client.is_open());
  24218. ASSERT_TRUE(client.send("second"));
  24219. ASSERT_TRUE(client.read(msg));
  24220. EXPECT_EQ("second", msg);
  24221. client.close();
  24222. }
  24223. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24224. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24225. "/ws-close-status");
  24226. ASSERT_TRUE(client.connect());
  24227. // Trigger the server to close with GoingAway status
  24228. ASSERT_TRUE(client.send("trigger"));
  24229. // read() should return false after receiving the close frame
  24230. std::string msg;
  24231. EXPECT_FALSE(client.read(msg));
  24232. EXPECT_FALSE(client.is_open());
  24233. }
  24234. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24235. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24236. "/ws-echo");
  24237. ASSERT_TRUE(client.connect());
  24238. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24239. EXPECT_FALSE(client.is_open());
  24240. }
  24241. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24242. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24243. ws::WebSocketClient client(
  24244. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24245. ASSERT_TRUE(client.connect());
  24246. // Server should have selected graphql-ws
  24247. EXPECT_EQ("graphql-ws", client.subprotocol());
  24248. client.close();
  24249. }
  24250. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24251. Headers headers;
  24252. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24253. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24254. ws::WebSocketClient client(
  24255. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24256. ASSERT_TRUE(client.connect());
  24257. // The offer on the second field line counts too, so graphql-ws is selected
  24258. EXPECT_EQ("graphql-ws", client.subprotocol());
  24259. client.close();
  24260. }
  24261. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24262. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24263. ws::WebSocketClient client(
  24264. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24265. ASSERT_TRUE(client.connect());
  24266. // Server should not have selected any subprotocol
  24267. EXPECT_TRUE(client.subprotocol().empty());
  24268. client.close();
  24269. }
  24270. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24271. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24272. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24273. "/ws-subprotocol-unoffered",
  24274. headers);
  24275. ASSERT_TRUE(client.connect());
  24276. EXPECT_TRUE(client.subprotocol().empty());
  24277. client.close();
  24278. }
  24279. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24280. // Connect without requesting any subprotocol
  24281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24282. "/ws-subprotocol");
  24283. ASSERT_TRUE(client.connect());
  24284. EXPECT_TRUE(client.subprotocol().empty());
  24285. client.close();
  24286. }
  24287. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24288. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24289. "/ws-echo");
  24290. client.set_tcp_nodelay(true);
  24291. client.set_connection_timeout(3, 0);
  24292. bool socket_options_called = false;
  24293. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24294. ASSERT_TRUE(client.connect());
  24295. ASSERT_TRUE(client.is_open());
  24296. EXPECT_TRUE(socket_options_called);
  24297. ASSERT_TRUE(client.send("hello"));
  24298. std::string msg;
  24299. auto result = client.read(msg);
  24300. EXPECT_EQ(result, ws::ReadResult::Text);
  24301. EXPECT_EQ(msg, "hello");
  24302. client.close();
  24303. }
  24304. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24305. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24306. "/ws-echo");
  24307. client.set_connection_timeout(std::chrono::seconds(3));
  24308. client.set_write_timeout(std::chrono::seconds(3));
  24309. // A sub-second remainder exercises the seconds/microseconds split.
  24310. client.set_read_timeout(std::chrono::milliseconds(1500));
  24311. ASSERT_TRUE(client.connect());
  24312. auto start = std::chrono::steady_clock::now();
  24313. std::string msg;
  24314. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24315. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24316. std::chrono::steady_clock::now() - start)
  24317. .count();
  24318. // Above 1s so that dropping the microseconds half of the split fails here.
  24319. // Ignoring the setter altogether would not reach this line at all: a client
  24320. // waits forever by default.
  24321. EXPECT_GE(elapsed, 1400);
  24322. EXPECT_LT(elapsed, 30000);
  24323. }
  24324. #ifndef _WIN32
  24325. // A send() that times out after part of the data went out returns the count
  24326. // written so far. Every byte of the frame must still be sent, or the peer reads
  24327. // the next frame's header and payload as the rest of this one.
  24328. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24329. signal(SIGPIPE, SIG_IGN);
  24330. const std::string large(4 * 1024 * 1024, 'A');
  24331. std::atomic<bool> large_sent{false};
  24332. std::atomic<bool> small_sent{false};
  24333. Server svr;
  24334. svr.set_write_timeout(0, 500000);
  24335. svr.set_socket_options([](socket_t sock) {
  24336. int size = 8192;
  24337. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24338. reinterpret_cast<const char *>(&size), sizeof(size));
  24339. });
  24340. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24341. large_sent = ws.send(large.data(), large.size());
  24342. small_sent = ws.send("after");
  24343. std::string msg;
  24344. while (ws.read(msg)) {}
  24345. });
  24346. auto port = svr.bind_to_any_port(HOST);
  24347. std::thread t([&]() { svr.listen_after_bind(); });
  24348. auto se = detail::scope_exit([&] {
  24349. svr.stop();
  24350. t.join();
  24351. });
  24352. svr.wait_until_ready();
  24353. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24354. std::to_string(port) + "/ws");
  24355. client.set_read_timeout(5);
  24356. client.set_socket_options([](socket_t sock) {
  24357. int size = 8192;
  24358. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24359. reinterpret_cast<const char *>(&size), sizeof(size));
  24360. });
  24361. ASSERT_TRUE(client.connect());
  24362. // Outlast the server's write timeout, then drain.
  24363. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24364. std::string msg;
  24365. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24366. EXPECT_TRUE(msg == large);
  24367. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24368. EXPECT_EQ("after", msg);
  24369. EXPECT_TRUE(large_sent);
  24370. EXPECT_TRUE(small_sent);
  24371. client.close();
  24372. }
  24373. #endif
  24374. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24375. Server svr;
  24376. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24377. if (!req.has_header("Authorization")) {
  24378. res.status = StatusCode::Unauthorized_401;
  24379. res.set_content("Unauthorized", "text/plain");
  24380. return Server::HandlerResponse::Handled;
  24381. }
  24382. return Server::HandlerResponse::Unhandled;
  24383. });
  24384. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24385. std::string msg;
  24386. while (ws.read(msg)) {
  24387. ws.send(msg);
  24388. }
  24389. });
  24390. auto port = svr.bind_to_any_port("localhost");
  24391. std::thread t([&]() { svr.listen_after_bind(); });
  24392. svr.wait_until_ready();
  24393. // Without Authorization header - should be rejected before upgrade
  24394. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24395. EXPECT_FALSE(client1.connect());
  24396. // The rejection is framed like any other HTTP response
  24397. {
  24398. Client cli("localhost", port);
  24399. Headers headers = {{"Upgrade", "websocket"},
  24400. {"Connection", "Upgrade"},
  24401. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24402. {"Sec-WebSocket-Version", "13"}};
  24403. auto res = cli.Get("/ws", headers);
  24404. ASSERT_TRUE(res);
  24405. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24406. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24407. EXPECT_EQ("Unauthorized", res->body);
  24408. }
  24409. // With Authorization header - should succeed
  24410. Headers headers = {{"Authorization", "Bearer token123"}};
  24411. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24412. headers);
  24413. ASSERT_TRUE(client2.connect());
  24414. ASSERT_TRUE(client2.send("hello"));
  24415. std::string msg;
  24416. ASSERT_TRUE(client2.read(msg));
  24417. EXPECT_EQ("hello", msg);
  24418. client2.close();
  24419. svr.stop();
  24420. t.join();
  24421. }
  24422. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24423. Server svr;
  24424. std::atomic<int> pre_routing_calls{0};
  24425. std::atomic<int> pre_request_calls{0};
  24426. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24427. pre_routing_calls++;
  24428. if (req.path == "/handled") {
  24429. res.set_content("handled", "text/plain");
  24430. return Server::HandlerResponse::Handled;
  24431. }
  24432. return Server::HandlerResponse::Unhandled;
  24433. });
  24434. svr.set_pre_request_handler([&](const Request &, Response &) {
  24435. pre_request_calls++;
  24436. return Server::HandlerResponse::Unhandled;
  24437. });
  24438. svr.Get("/http", [](const Request &, Response &res) {
  24439. res.set_content("http", "text/plain");
  24440. });
  24441. svr.WebSocket("/ws",
  24442. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24443. auto port = svr.bind_to_any_port("localhost");
  24444. std::thread t([&]() { svr.listen_after_bind(); });
  24445. auto se = detail::scope_exit([&] {
  24446. svr.stop();
  24447. t.join();
  24448. });
  24449. svr.wait_until_ready();
  24450. Headers upgrade = {{"Upgrade", "websocket"},
  24451. {"Connection", "Upgrade"},
  24452. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24453. {"Sec-WebSocket-Version", "13"}};
  24454. auto get = [&](const char *path) {
  24455. pre_routing_calls = 0;
  24456. return Client("localhost", port).Get(path, upgrade);
  24457. };
  24458. // No WebSocket route, but an HTTP one
  24459. auto res = get("/http");
  24460. ASSERT_TRUE(res);
  24461. EXPECT_EQ(StatusCode::OK_200, res->status);
  24462. EXPECT_EQ("http", res->body);
  24463. EXPECT_EQ(1, pre_routing_calls);
  24464. EXPECT_EQ(1, pre_request_calls);
  24465. // No route at all
  24466. res = get("/none");
  24467. ASSERT_TRUE(res);
  24468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24469. EXPECT_EQ(1, pre_routing_calls);
  24470. // Answered by the pre-routing handler
  24471. res = get("/handled");
  24472. ASSERT_TRUE(res);
  24473. EXPECT_EQ(StatusCode::OK_200, res->status);
  24474. EXPECT_EQ("handled", res->body);
  24475. EXPECT_EQ(1, pre_routing_calls);
  24476. // A WebSocket route
  24477. pre_routing_calls = 0;
  24478. pre_request_calls = 0;
  24479. {
  24480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24481. "/ws");
  24482. ASSERT_TRUE(client.connect());
  24483. std::string msg;
  24484. ASSERT_TRUE(client.read(msg));
  24485. EXPECT_EQ("ws", msg);
  24486. client.close();
  24487. }
  24488. EXPECT_EQ(1, pre_routing_calls);
  24489. EXPECT_EQ(1, pre_request_calls);
  24490. }
  24491. // An upgrade request answered by a hook leaves its body unread, so that body
  24492. // must not be served as the next request on the connection.
  24493. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24494. Server svr;
  24495. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24496. if (req.path == "/pre-routing") {
  24497. res.set_content("pre-routing", "text/plain");
  24498. return Server::HandlerResponse::Handled;
  24499. }
  24500. return Server::HandlerResponse::Unhandled;
  24501. });
  24502. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24503. if (req.matched_route == "/pre-request") {
  24504. res.set_content("pre-request", "text/plain");
  24505. return Server::HandlerResponse::Handled;
  24506. }
  24507. return Server::HandlerResponse::Unhandled;
  24508. });
  24509. svr.Get("/smuggled", [](const Request &, Response &res) {
  24510. res.set_content("smuggled", "text/plain");
  24511. });
  24512. svr.WebSocket("/pre-request",
  24513. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24514. auto port = svr.bind_to_any_port(HOST);
  24515. std::thread t([&]() { svr.listen_after_bind(); });
  24516. auto se = detail::scope_exit([&] {
  24517. svr.stop();
  24518. t.join();
  24519. });
  24520. svr.wait_until_ready();
  24521. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24522. for (auto path : {"/pre-routing", "/pre-request"}) {
  24523. std::string req = std::string("GET ") + path +
  24524. " HTTP/1.1\r\n"
  24525. "Host: localhost\r\n"
  24526. "Upgrade: websocket\r\n"
  24527. "Connection: Upgrade\r\n"
  24528. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24529. "Sec-WebSocket-Version: 13\r\n"
  24530. "Content-Length: " +
  24531. std::to_string(body.size()) + "\r\n\r\n" + body;
  24532. std::string res;
  24533. ASSERT_TRUE(send_request(5, req, &res, port));
  24534. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24535. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24536. // Only one response, and the body was not served as a request
  24537. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24538. }
  24539. }
  24540. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24541. Server svr;
  24542. std::atomic<int> pre_request_calls{0};
  24543. std::atomic<bool> route_matched{false};
  24544. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24545. pre_request_calls++;
  24546. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24547. if (req.get_header_value("Authorization") != "Bearer token123") {
  24548. res.status = StatusCode::Unauthorized_401;
  24549. res.set_content("Unauthorized", "text/plain");
  24550. return Server::HandlerResponse::Handled;
  24551. }
  24552. return Server::HandlerResponse::Unhandled;
  24553. });
  24554. std::atomic<bool> handler_called{false};
  24555. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24556. handler_called = true;
  24557. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24558. });
  24559. auto port = svr.bind_to_any_port("localhost");
  24560. std::thread t([&]() { svr.listen_after_bind(); });
  24561. svr.wait_until_ready();
  24562. // Without Authorization header - should be rejected before upgrade
  24563. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24564. "/ws/1");
  24565. EXPECT_FALSE(client1.connect());
  24566. EXPECT_FALSE(handler_called);
  24567. EXPECT_EQ(1, pre_request_calls);
  24568. EXPECT_TRUE(route_matched);
  24569. // The rejection is an ordinary HTTP response, not a protocol switch
  24570. {
  24571. Client cli("localhost", port);
  24572. Headers headers = {{"Upgrade", "websocket"},
  24573. {"Connection", "Upgrade"},
  24574. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24575. {"Sec-WebSocket-Version", "13"}};
  24576. auto res = cli.Get("/ws/1", headers);
  24577. ASSERT_TRUE(res);
  24578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24579. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24580. EXPECT_EQ("Unauthorized", res->body);
  24581. }
  24582. EXPECT_FALSE(handler_called);
  24583. // With Authorization header - should succeed
  24584. Headers headers = {{"Authorization", "Bearer token123"}};
  24585. ws::WebSocketClient client2(
  24586. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24587. ASSERT_TRUE(client2.connect());
  24588. std::string msg;
  24589. ASSERT_TRUE(client2.read(msg));
  24590. EXPECT_EQ("/ws/:id 2", msg);
  24591. EXPECT_TRUE(handler_called);
  24592. client2.close();
  24593. svr.stop();
  24594. t.join();
  24595. }
  24596. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24597. static Headers websocket_upgrade_headers() {
  24598. return {{"Upgrade", "websocket"},
  24599. {"Connection", "Upgrade"},
  24600. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24601. {"Sec-WebSocket-Version", "13"},
  24602. {"Sec-WebSocket-Protocol", "chat"}};
  24603. }
  24604. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24605. Server svr;
  24606. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24607. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24608. return Server::HandlerResponse::Unhandled;
  24609. });
  24610. svr.set_pre_request_handler([](const Request &req, Response &) {
  24611. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24612. return Server::HandlerResponse::Unhandled;
  24613. });
  24614. svr.set_exception_handler(
  24615. [](const Request &, Response &res, std::exception_ptr ep) {
  24616. try {
  24617. std::rethrow_exception(ep);
  24618. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24619. });
  24620. auto handler = [](const Request &, ws::WebSocket &) {};
  24621. svr.WebSocket("/pre-routing", handler);
  24622. svr.WebSocket("/pre-request", handler);
  24623. svr.WebSocket("/sub-protocol", handler,
  24624. [](const std::vector<std::string> &) -> std::string {
  24625. throw std::runtime_error("/sub-protocol");
  24626. });
  24627. auto port = svr.bind_to_any_port(HOST);
  24628. ASSERT_GT(port, 0);
  24629. thread t = thread([&] { svr.listen_after_bind(); });
  24630. auto se = detail::scope_exit([&] {
  24631. svr.stop();
  24632. t.join();
  24633. ASSERT_FALSE(svr.is_running());
  24634. });
  24635. svr.wait_until_ready();
  24636. Client cli(HOST, port);
  24637. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24638. auto res = cli.Get(path, websocket_upgrade_headers());
  24639. if (!res) {
  24640. ADD_FAILURE() << path << ": " << to_string(res.error());
  24641. continue;
  24642. }
  24643. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24644. EXPECT_EQ(path, res->body);
  24645. }
  24646. }
  24647. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24648. Server svr;
  24649. svr.set_pre_routing_handler(
  24650. [](const Request &, Response &) -> Server::HandlerResponse {
  24651. throw std::runtime_error("pre-routing");
  24652. });
  24653. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24654. auto port = svr.bind_to_any_port(HOST);
  24655. ASSERT_GT(port, 0);
  24656. thread t = thread([&] { svr.listen_after_bind(); });
  24657. auto se = detail::scope_exit([&] {
  24658. svr.stop();
  24659. t.join();
  24660. ASSERT_FALSE(svr.is_running());
  24661. });
  24662. svr.wait_until_ready();
  24663. Client cli(HOST, port);
  24664. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24665. ASSERT_TRUE(res) << to_string(res.error());
  24666. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24667. }
  24668. #endif
  24669. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24670. Server svr;
  24671. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24672. // A read timeout is how a handler gets control back. Without it, a handler
  24673. // parked in read() can never write on the connection it is reading.
  24674. ws.set_read_timeout(std::chrono::milliseconds(100));
  24675. std::string msg;
  24676. while (ws.is_open()) {
  24677. auto r = ws.read(msg);
  24678. if (r == httplib::ws::Timeout) {
  24679. ws.send("tick");
  24680. continue;
  24681. }
  24682. if (r == httplib::ws::Fail) { break; }
  24683. ws.send(msg);
  24684. }
  24685. });
  24686. auto port = svr.bind_to_any_port("localhost");
  24687. std::thread t([&]() { svr.listen_after_bind(); });
  24688. svr.wait_until_ready();
  24689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24690. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24691. ASSERT_TRUE(client.connect());
  24692. // The client sends nothing, so anything it receives came out of the
  24693. // handler's timeout path.
  24694. std::string msg;
  24695. ASSERT_EQ(client.read(msg), ws::Text);
  24696. EXPECT_EQ("tick", msg);
  24697. client.close();
  24698. svr.stop();
  24699. t.join();
  24700. }
  24701. // Stream::read may return fewer bytes than asked for. This is that contract at
  24702. // its worst -- one byte per call -- which is what a frame header straddling a
  24703. // read buffer's boundary looks like to the frame parser.
  24704. class WsByteAtATimeStream : public Stream {
  24705. public:
  24706. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24707. bool is_readable() const override { return true; }
  24708. bool wait_readable() const override { return true; }
  24709. bool wait_writable() const override { return true; }
  24710. ssize_t read(char *ptr, size_t size) override {
  24711. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24712. *ptr = data_[pos_++];
  24713. return 1;
  24714. }
  24715. ssize_t write(const char *, size_t size) override {
  24716. return static_cast<ssize_t>(size);
  24717. }
  24718. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24719. ip = "127.0.0.1";
  24720. port = 0;
  24721. }
  24722. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24723. ip = "127.0.0.1";
  24724. port = 0;
  24725. }
  24726. socket_t socket() const override { return INVALID_SOCKET; }
  24727. time_t duration() const override { return 0; }
  24728. private:
  24729. std::string data_;
  24730. size_t pos_ = 0;
  24731. };
  24732. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24733. // The payload uses the 16-bit extended length, so the header, the length
  24734. // and the mask key are all multi-byte fields here. Each used to be read
  24735. // with a single read() call, which fails as soon as one is split. The
  24736. // payload is also a little over one read chunk, so it is read in two.
  24737. std::string body;
  24738. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24739. body += static_cast<char>(i % 251);
  24740. }
  24741. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24742. std::string frame;
  24743. frame += static_cast<char>(0x81); // FIN + Text
  24744. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24745. frame += static_cast<char>(body.size() >> 8);
  24746. frame += static_cast<char>(body.size() & 0xff);
  24747. for (size_t i = 0; i < 4; i++) {
  24748. frame += static_cast<char>(mask[i]);
  24749. }
  24750. for (size_t i = 0; i < body.size(); i++) {
  24751. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24752. }
  24753. WsByteAtATimeStream strm(frame);
  24754. ws::Opcode opcode;
  24755. std::string payload;
  24756. bool fin = false;
  24757. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24758. /*expect_masked=*/true, body.size()),
  24759. ws::impl::FrameRead::Ok);
  24760. EXPECT_TRUE(fin);
  24761. EXPECT_EQ(opcode, ws::Opcode::Text);
  24762. EXPECT_EQ(payload, body);
  24763. }
  24764. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24765. std::string body(2000, 'x');
  24766. std::string frame;
  24767. frame += static_cast<char>(0x82); // FIN + Binary
  24768. frame += static_cast<char>(126); // 16-bit length follows
  24769. frame += static_cast<char>(body.size() >> 8);
  24770. frame += static_cast<char>(body.size() & 0xff);
  24771. frame += body;
  24772. detail::BufferStream strm;
  24773. strm.write(frame.data(), frame.size());
  24774. ws::Opcode opcode;
  24775. std::string payload;
  24776. bool fin;
  24777. EXPECT_EQ(
  24778. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24779. ws::impl::FrameRead::Ok);
  24780. EXPECT_EQ(body, payload);
  24781. }
  24782. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24783. // The header announces the largest payload allowed, and only 3 bytes of it
  24784. // ever arrive.
  24785. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24786. std::string frame;
  24787. frame += static_cast<char>(0x82); // FIN + Binary
  24788. frame += static_cast<char>(127); // 64-bit length follows
  24789. for (int shift = 56; shift >= 0; shift -= 8) {
  24790. frame += static_cast<char>((len >> shift) & 0xff);
  24791. }
  24792. frame += "abc";
  24793. detail::BufferStream strm;
  24794. strm.write(frame.data(), frame.size());
  24795. ws::Opcode opcode;
  24796. std::string payload;
  24797. bool fin;
  24798. EXPECT_EQ(
  24799. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24800. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24801. ws::impl::FrameRead::Fail);
  24802. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24803. }
  24804. TEST(WebSocketTest, QueryStringInHandshake) {
  24805. Server svr;
  24806. std::mutex mtx;
  24807. std::string received_target;
  24808. std::string received_token;
  24809. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24810. {
  24811. std::lock_guard<std::mutex> lock(mtx);
  24812. received_target = req.target;
  24813. if (req.has_param("token")) {
  24814. received_token = req.get_param_value("token");
  24815. }
  24816. }
  24817. std::string msg;
  24818. while (ws.read(msg)) {
  24819. ws.send(msg);
  24820. }
  24821. });
  24822. auto port = svr.bind_to_any_port("localhost");
  24823. std::thread t([&]() { svr.listen_after_bind(); });
  24824. svr.wait_until_ready();
  24825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24826. "/ws?token=ABC&session=123");
  24827. ASSERT_TRUE(client.connect());
  24828. // Round-trip ensures the handler has run and captured the request.
  24829. ASSERT_TRUE(client.send("hello"));
  24830. std::string msg;
  24831. ASSERT_TRUE(client.read(msg));
  24832. EXPECT_EQ("hello", msg);
  24833. client.close();
  24834. {
  24835. std::lock_guard<std::mutex> lock(mtx);
  24836. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24837. EXPECT_EQ("ABC", received_token);
  24838. }
  24839. svr.stop();
  24840. t.join();
  24841. }
  24842. // Run a handshake against a throwaway server and hand the request the server
  24843. // received back to the caller, so tests can assert on the headers the client
  24844. // actually put on the wire.
  24845. static void capture_websocket_handshake_request(
  24846. const Headers &client_headers,
  24847. std::function<void(const Request &, int port)> verify) {
  24848. Server svr;
  24849. std::mutex mtx;
  24850. Request received;
  24851. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24852. {
  24853. std::lock_guard<std::mutex> lock(mtx);
  24854. received = req;
  24855. }
  24856. std::string msg;
  24857. while (ws.read(msg)) {
  24858. ws.send(msg);
  24859. }
  24860. });
  24861. auto port = svr.bind_to_any_port("localhost");
  24862. std::thread t([&]() { svr.listen_after_bind(); });
  24863. auto se = detail::scope_exit([&] {
  24864. svr.stop();
  24865. t.join();
  24866. });
  24867. svr.wait_until_ready();
  24868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24869. client_headers);
  24870. ASSERT_TRUE(client.connect());
  24871. ASSERT_TRUE(client.send("hello"));
  24872. std::string msg;
  24873. ASSERT_TRUE(client.read(msg));
  24874. client.close();
  24875. {
  24876. std::lock_guard<std::mutex> lock(mtx);
  24877. verify(received, port);
  24878. }
  24879. }
  24880. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24881. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24882. // Non-default port must be present in the Host header. Default ports
  24883. // (80/443) are omitted; that logic is covered by
  24884. // MakeHostAndPortStringTest.
  24885. EXPECT_EQ("localhost:" + std::to_string(port),
  24886. req.get_header_value("Host"));
  24887. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24888. req.get_header_value("User-Agent"));
  24889. EXPECT_FALSE(req.has_header("Accept"));
  24890. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24891. EXPECT_FALSE(req.has_header("Content-Length"));
  24892. });
  24893. }
  24894. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24895. capture_websocket_handshake_request(
  24896. {{"Host", "example.com"},
  24897. {"User-Agent", "custom-agent"},
  24898. {"X-Custom", "value"}},
  24899. [](const Request &req, int) {
  24900. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24901. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24902. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24903. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24904. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24905. });
  24906. }
  24907. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24908. capture_websocket_handshake_request(
  24909. {{"Upgrade", "bogus"},
  24910. {"Connection", "close"},
  24911. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24912. {"Sec-WebSocket-Version", "8"}},
  24913. [](const Request &req, int) {
  24914. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24915. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24916. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24917. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24918. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24919. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24920. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24921. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24922. req.get_header_value("Sec-WebSocket-Key"));
  24923. });
  24924. }
  24925. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24926. // A header the client refuses to send must abort the handshake before any
  24927. // part of it reaches the wire; a lone request line would otherwise sit in
  24928. // the peer's buffer as a truncated request.
  24929. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24930. ASSERT_NE(INVALID_SOCKET, srv);
  24931. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24932. sockaddr_in addr{};
  24933. addr.sin_family = AF_INET;
  24934. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24935. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24936. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24937. ASSERT_EQ(0, ::listen(srv, 1));
  24938. sockaddr_in bound{};
  24939. socklen_t bound_len = sizeof(bound);
  24940. ASSERT_EQ(
  24941. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24942. auto port = ntohs(bound.sin_port);
  24943. ssize_t received = -1;
  24944. std::thread t([&] {
  24945. // Bound every blocking call so a regression fails the test with a bad
  24946. // value instead of hanging the suite.
  24947. fd_set rfds;
  24948. FD_ZERO(&rfds);
  24949. FD_SET(srv, &rfds);
  24950. timeval tv{5, 0};
  24951. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24952. 0) {
  24953. return;
  24954. }
  24955. sockaddr_in cli_addr{};
  24956. socklen_t cli_len = sizeof(cli_addr);
  24957. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24958. if (cli == INVALID_SOCKET) { return; }
  24959. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24960. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24961. char buf[4096];
  24962. received = ::recv(cli, buf, sizeof(buf), 0);
  24963. });
  24964. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24965. // connect() has already shut the socket down by the time it returns false,
  24966. // so the peer sees EOF without waiting for the client to be destroyed.
  24967. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24968. {{"X-Bad", "a\r\nInjected: 1"}});
  24969. EXPECT_FALSE(client.connect());
  24970. t.join();
  24971. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24972. EXPECT_EQ(0, received);
  24973. }
  24974. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24975. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24976. // contains "upgrade" as a substring is a different token and must not
  24977. // start a WebSocket handshake.
  24978. auto make_request = [](const std::vector<std::string> &connection_values) {
  24979. Request req;
  24980. req.method = "GET";
  24981. req.headers.emplace("Upgrade", "websocket");
  24982. for (const auto &value : connection_values) {
  24983. req.headers.emplace("Connection", value);
  24984. }
  24985. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24986. req.headers.emplace("Sec-WebSocket-Version", "13");
  24987. return req;
  24988. };
  24989. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24990. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24991. EXPECT_TRUE(
  24992. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24993. EXPECT_TRUE(
  24994. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24995. EXPECT_TRUE(
  24996. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24997. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24998. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24999. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25000. EXPECT_FALSE(
  25001. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25002. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25003. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25004. }
  25005. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25006. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25007. // asks recipients to match each protocol-name case-insensitively, and RFC
  25008. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25009. // client naming websocket alongside another protocol, or on a second field
  25010. // line, is offering websocket; a value that merely contains "websocket" as a
  25011. // substring is a different protocol name and is not.
  25012. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25013. Request req;
  25014. req.method = "GET";
  25015. for (const auto &value : upgrade_values) {
  25016. req.headers.emplace("Upgrade", value);
  25017. }
  25018. req.headers.emplace("Connection", "Upgrade");
  25019. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25020. req.headers.emplace("Sec-WebSocket-Version", "13");
  25021. return req;
  25022. };
  25023. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25024. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25025. EXPECT_TRUE(
  25026. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25027. EXPECT_TRUE(
  25028. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25029. EXPECT_TRUE(
  25030. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25031. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25032. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25033. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25034. EXPECT_FALSE(
  25035. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25036. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25037. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25038. }
  25039. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25040. Server svr;
  25041. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25042. auto port = svr.bind_to_any_port("localhost");
  25043. std::thread t([&]() { svr.listen_after_bind(); });
  25044. auto se = detail::scope_exit([&] {
  25045. svr.stop();
  25046. t.join();
  25047. });
  25048. svr.wait_until_ready();
  25049. Headers headers = {{"Upgrade", "websocket"},
  25050. {"Connection", "notupgrade"},
  25051. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25052. {"Sec-WebSocket-Version", "13"}};
  25053. Client cli("localhost", port);
  25054. auto res = cli.Get("/ws", headers);
  25055. // The route exists only as a WebSocket route, so a request that fails the
  25056. // handshake check falls through to ordinary routing.
  25057. ASSERT_TRUE(res);
  25058. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25059. }
  25060. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25061. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25062. // Connection value is the only thing left for the client to reject.
  25063. Server svr;
  25064. svr.Get("/ws", [](const Request &req, Response &res) {
  25065. res.status = StatusCode::SwitchingProtocol_101;
  25066. res.set_header("Upgrade", "websocket");
  25067. res.set_header("Connection", "notupgrade");
  25068. res.set_header("Sec-WebSocket-Accept",
  25069. detail::websocket_accept_key(
  25070. req.get_header_value("Sec-WebSocket-Key")));
  25071. });
  25072. auto port = svr.bind_to_any_port("localhost");
  25073. std::thread t([&]() { svr.listen_after_bind(); });
  25074. auto se = detail::scope_exit([&] {
  25075. svr.stop();
  25076. t.join();
  25077. });
  25078. svr.wait_until_ready();
  25079. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25080. auto res = client.connect();
  25081. EXPECT_FALSE(res);
  25082. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25083. EXPECT_FALSE(client.is_open());
  25084. }
  25085. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25086. Server svr;
  25087. svr.Get("/ws", [](const Request &req, Response &res) {
  25088. res.status = StatusCode::SwitchingProtocol_101;
  25089. res.set_header("Upgrade", "websocket");
  25090. res.set_header("Connection", "Upgrade");
  25091. res.set_header("Sec-WebSocket-Accept",
  25092. detail::websocket_accept_key(
  25093. req.get_header_value("Sec-WebSocket-Key")));
  25094. res.set_header("Sec-WebSocket-Protocol", "admin");
  25095. });
  25096. auto port = svr.bind_to_any_port("localhost");
  25097. std::thread t([&]() { svr.listen_after_bind(); });
  25098. auto se = detail::scope_exit([&] {
  25099. svr.stop();
  25100. t.join();
  25101. });
  25102. svr.wait_until_ready();
  25103. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25104. // Server selects a subprotocol the client never offered
  25105. {
  25106. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25107. ws::WebSocketClient client(url, headers);
  25108. auto res = client.connect();
  25109. EXPECT_FALSE(res);
  25110. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25111. EXPECT_FALSE(client.is_open());
  25112. EXPECT_TRUE(client.subprotocol().empty());
  25113. }
  25114. // Client offered none but the server named one anyway
  25115. {
  25116. ws::WebSocketClient client(url);
  25117. auto res = client.connect();
  25118. EXPECT_FALSE(res);
  25119. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25120. EXPECT_FALSE(client.is_open());
  25121. EXPECT_TRUE(client.subprotocol().empty());
  25122. }
  25123. }
  25124. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25125. // The socket path doubles as the URL host, so it must not contain '/'.
  25126. const char *shard = getenv("GTEST_SHARD_INDEX");
  25127. const std::string sock_path =
  25128. shard ? std::string("httplib-ws-") + shard + ".sock"
  25129. : std::string("httplib-ws.sock");
  25130. std::remove(sock_path.c_str());
  25131. Server svr;
  25132. std::mutex mtx;
  25133. std::string received_host;
  25134. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25135. {
  25136. std::lock_guard<std::mutex> lock(mtx);
  25137. received_host = req.get_header_value("Host");
  25138. }
  25139. std::string msg;
  25140. while (ws.read(msg)) {
  25141. ws.send(msg);
  25142. }
  25143. });
  25144. svr.set_address_family(AF_UNIX);
  25145. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25146. auto se = detail::scope_exit([&] {
  25147. svr.stop();
  25148. t.join();
  25149. std::remove(sock_path.c_str());
  25150. });
  25151. svr.wait_until_ready();
  25152. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25153. client.set_address_family(AF_UNIX);
  25154. ASSERT_TRUE(client.connect());
  25155. ASSERT_TRUE(client.send("hello"));
  25156. std::string msg;
  25157. ASSERT_TRUE(client.read(msg));
  25158. client.close();
  25159. {
  25160. std::lock_guard<std::mutex> lock(mtx);
  25161. // There is no host:port for a Unix socket, so the same "localhost"
  25162. // placeholder the HTTP client uses is expected.
  25163. EXPECT_EQ("localhost", received_host);
  25164. }
  25165. }
  25166. // Two threads must never parse WebSocket frames from the same stream.
  25167. // close() used to read the peer's Close reply with its own frame read, so it
  25168. // raced a reader thread that was in the middle of a payload: the payload loop
  25169. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25170. // so bytes taken by close() were replaced with bytes from further along the
  25171. // stream. The message kept its length and silently changed content.
  25172. //
  25173. // The raw peer below sends a frame header plus part of the payload, waits for
  25174. // the handler to call close(), and only then sends the rest. Whichever thread
  25175. // would win the race for those bytes, the message must arrive intact, because
  25176. // close() must not touch the stream while read() owns it.
  25177. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25178. #ifndef _WIN32
  25179. signal(SIGPIPE, SIG_IGN);
  25180. #endif
  25181. const size_t payload_len = 120; // fits the 7-bit length field
  25182. const size_t prefix_len = 8;
  25183. const int attempts = 8;
  25184. std::string expected(payload_len, '\0');
  25185. for (size_t i = 0; i < payload_len; i++) {
  25186. expected[i] = static_cast<char>('a' + i % 26);
  25187. }
  25188. std::atomic<bool> peer_stalled{false};
  25189. std::atomic<bool> handler_done{false};
  25190. std::mutex received_mutex;
  25191. std::vector<std::string> received;
  25192. // Bound every wait, so a regression fails the test instead of hanging the
  25193. // suite.
  25194. auto wait_for = [](const std::atomic<bool> &flag) {
  25195. for (int i = 0; i < 500 && !flag; i++) {
  25196. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25197. }
  25198. };
  25199. Server svr;
  25200. svr.set_websocket_ping_interval(0);
  25201. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25202. std::thread reader([&]() {
  25203. std::string msg;
  25204. while (ws.read(msg)) {
  25205. std::lock_guard<std::mutex> guard(received_mutex);
  25206. received.push_back(msg);
  25207. }
  25208. });
  25209. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25210. // inside read_websocket_frame() when close() runs.
  25211. wait_for(peer_stalled);
  25212. ws.close();
  25213. reader.join();
  25214. handler_done = true;
  25215. });
  25216. auto port = svr.bind_to_any_port("127.0.0.1");
  25217. std::thread t([&]() { svr.listen_after_bind(); });
  25218. auto se = detail::scope_exit([&] {
  25219. svr.stop();
  25220. t.join();
  25221. });
  25222. svr.wait_until_ready();
  25223. auto send_bytes = [](socket_t s, const std::string &data) {
  25224. #ifdef _WIN32
  25225. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25226. #else
  25227. auto n = ::send(s, data.data(), data.size(), 0);
  25228. #endif
  25229. return n == static_cast<decltype(n)>(data.size());
  25230. };
  25231. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25232. // Every length used here fits the 7-bit length field.
  25233. auto masked_header = [](uint8_t first_byte, size_t len) {
  25234. std::string h;
  25235. h += static_cast<char>(first_byte);
  25236. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25237. h.append(4, '\0'); // mask key
  25238. return h;
  25239. };
  25240. for (int attempt = 0; attempt < attempts; attempt++) {
  25241. peer_stalled = false;
  25242. handler_done = false;
  25243. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25244. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25245. auto se_sock = detail::scope_exit([&] {
  25246. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25247. });
  25248. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25249. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25250. sockaddr_in addr{};
  25251. addr.sin_family = AF_INET;
  25252. addr.sin_port = htons(static_cast<uint16_t>(port));
  25253. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25254. ASSERT_EQ(
  25255. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25256. << "attempt " << attempt;
  25257. ASSERT_TRUE(send_bytes(sock,
  25258. "GET /ws HTTP/1.1\r\n"
  25259. "Host: 127.0.0.1\r\n"
  25260. "Upgrade: websocket\r\n"
  25261. "Connection: Upgrade\r\n"
  25262. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25263. "Sec-WebSocket-Version: 13\r\n"
  25264. "\r\n"))
  25265. << "attempt " << attempt;
  25266. std::string response;
  25267. while (response.find("\r\n\r\n") == std::string::npos) {
  25268. char buf[512];
  25269. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25270. if (n <= 0) { break; }
  25271. response.append(buf, static_cast<size_t>(n));
  25272. }
  25273. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25274. << "attempt " << attempt;
  25275. // Send the header of a Binary message but only the first prefix_len bytes
  25276. // of its payload, leaving the reader thread stalled inside the payload.
  25277. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25278. expected.substr(0, prefix_len)))
  25279. << "attempt " << attempt;
  25280. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25281. peer_stalled = true;
  25282. // Let close() send its Close frame and park in its own read before the
  25283. // rest of the payload arrives, so both threads are waiting for it.
  25284. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25285. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25286. close_frame += static_cast<char>(0x03); // status 1000
  25287. close_frame += static_cast<char>(0xE8);
  25288. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25289. << "attempt " << attempt;
  25290. // Closing the peer releases the reader thread even on the buggy path,
  25291. // where it waits for bytes another thread already consumed.
  25292. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25293. detail::close_socket(sock);
  25294. sock = INVALID_SOCKET;
  25295. wait_for(handler_done);
  25296. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25297. }
  25298. std::lock_guard<std::mutex> guard(received_mutex);
  25299. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25300. << "a message in flight when close() ran was dropped";
  25301. for (size_t i = 0; i < received.size(); i++) {
  25302. EXPECT_EQ(expected, received[i]) << "message " << i;
  25303. }
  25304. }
  25305. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25306. // returning the socket, or INVALID_SOCKET.
  25307. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25308. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25309. if (sock == INVALID_SOCKET) { return sock; }
  25310. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25311. sockaddr_in addr{};
  25312. addr.sin_family = AF_INET;
  25313. addr.sin_port = htons(static_cast<uint16_t>(port));
  25314. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25315. std::string req = "GET " + path +
  25316. " HTTP/1.1\r\n"
  25317. "Host: 127.0.0.1\r\n"
  25318. "Upgrade: websocket\r\n"
  25319. "Connection: Upgrade\r\n"
  25320. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25321. "Sec-WebSocket-Version: 13\r\n"
  25322. "\r\n";
  25323. std::string res;
  25324. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25325. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25326. static_cast<ssize_t>(req.size())) {
  25327. char c;
  25328. while (res.find("\r\n\r\n") == std::string::npos &&
  25329. ::recv(sock, &c, 1, 0) == 1) {
  25330. res += c;
  25331. }
  25332. }
  25333. if (res.find(" 101 ") == std::string::npos) {
  25334. detail::close_socket(sock);
  25335. return INVALID_SOCKET;
  25336. }
  25337. return sock;
  25338. }
  25339. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25340. // The payload must fit the 7-bit length field.
  25341. static std::string masked_frame(uint8_t first_byte,
  25342. const std::string &payload) {
  25343. std::string f;
  25344. f += static_cast<char>(first_byte);
  25345. f += static_cast<char>(0x80 | payload.size());
  25346. f.append(4, '\0');
  25347. return f + payload;
  25348. }
  25349. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25350. std::atomic<bool> done{false};
  25351. std::string received;
  25352. Server svr;
  25353. svr.set_websocket_ping_interval(0);
  25354. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25355. std::string msg;
  25356. if (ws.read(msg) == ws::Binary) { received = msg; }
  25357. done = true;
  25358. });
  25359. auto port = svr.bind_to_any_port("127.0.0.1");
  25360. std::thread t([&]() { svr.listen_after_bind(); });
  25361. auto se = detail::scope_exit([&] {
  25362. svr.stop();
  25363. t.join();
  25364. });
  25365. svr.wait_until_ready();
  25366. auto sock = connect_raw_websocket(port, "/ws");
  25367. ASSERT_NE(INVALID_SOCKET, sock);
  25368. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25369. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25370. masked_frame(0x89, "p") + // FIN + Ping
  25371. masked_frame(0x80, "lo"); // FIN + Continuation
  25372. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25373. for (int i = 0; i < 500 && !done; i++) {
  25374. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25375. }
  25376. ASSERT_TRUE(done);
  25377. EXPECT_EQ("Hello", received);
  25378. // The Ping between the fragments is answered with a Pong.
  25379. char pong[3];
  25380. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25381. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25382. }
  25383. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25384. Server svr;
  25385. svr.set_websocket_ping_interval(-1);
  25386. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25387. std::string msg;
  25388. while (ws.read(msg)) {}
  25389. });
  25390. auto port = svr.bind_to_any_port("127.0.0.1");
  25391. std::thread t([&]() { svr.listen_after_bind(); });
  25392. auto se = detail::scope_exit([&] {
  25393. svr.stop();
  25394. t.join();
  25395. });
  25396. svr.wait_until_ready();
  25397. auto sock = connect_raw_websocket(port, "/ws");
  25398. ASSERT_NE(INVALID_SOCKET, sock);
  25399. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25400. // Nothing comes while the client stays quiet.
  25401. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25402. char c;
  25403. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25404. }
  25405. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25406. // and that has to end a read() already waiting on the peer, on every platform.
  25407. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25408. // The peer sends no pings, and its handler never calls read(), which is
  25409. // where pongs are written.
  25410. std::mutex mutex;
  25411. std::condition_variable cv;
  25412. auto release = false;
  25413. svr.set_websocket_ping_interval(0);
  25414. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25415. std::unique_lock<std::mutex> lock(mutex);
  25416. cv.wait(lock, [&] { return release; });
  25417. });
  25418. auto port = svr.bind_to_any_port(HOST);
  25419. std::thread t([&]() { svr.listen_after_bind(); });
  25420. auto se = detail::scope_exit([&] {
  25421. {
  25422. std::lock_guard<std::mutex> lock(mutex);
  25423. release = true;
  25424. }
  25425. cv.notify_all();
  25426. svr.stop();
  25427. t.join();
  25428. });
  25429. svr.wait_until_ready();
  25430. ws::WebSocketClient client(std::string(scheme) +
  25431. "://localhost:" + std::to_string(port) + "/ws");
  25432. #ifdef CPPHTTPLIB_SSL_ENABLED
  25433. client.enable_server_certificate_verification(false);
  25434. #endif
  25435. // A ping a second, given up on after two go unanswered: about 3s
  25436. client.set_websocket_ping_interval(1);
  25437. client.set_websocket_max_missed_pongs(2);
  25438. // Well past that, so that a read the timeout ends instead stands out
  25439. client.set_read_timeout(10);
  25440. ASSERT_TRUE(client.connect());
  25441. auto start = std::chrono::steady_clock::now();
  25442. std::string msg;
  25443. EXPECT_EQ(ws::Fail, client.read(msg));
  25444. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25445. std::chrono::steady_clock::now() - start)
  25446. .count(),
  25447. 6000);
  25448. EXPECT_FALSE(client.is_open());
  25449. }
  25450. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25451. Server svr;
  25452. check_pong_timeout_ends_read(svr, "ws");
  25453. }
  25454. #ifdef CPPHTTPLIB_SSL_ENABLED
  25455. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25456. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25457. ASSERT_TRUE(svr.is_valid());
  25458. check_pong_timeout_ends_read(svr, "wss");
  25459. }
  25460. #endif
  25461. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25462. Server svr;
  25463. svr.set_websocket_ping_interval(0);
  25464. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25465. std::string msg;
  25466. while (ws.read(msg)) {}
  25467. });
  25468. auto port = svr.bind_to_any_port("127.0.0.1");
  25469. std::thread t([&]() { svr.listen_after_bind(); });
  25470. auto se = detail::scope_exit([&] {
  25471. svr.stop();
  25472. t.join();
  25473. });
  25474. svr.wait_until_ready();
  25475. // Each Close payload and the reply it should get: an echo when valid, 1002
  25476. // otherwise.
  25477. std::vector<std::pair<std::string, std::string>> cases = {
  25478. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25479. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25480. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25481. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25482. };
  25483. // Also between the fragments of a message.
  25484. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25485. for (const auto &c : cases) {
  25486. auto sock = connect_raw_websocket(port, "/ws");
  25487. ASSERT_NE(INVALID_SOCKET, sock);
  25488. auto frames = prefix + masked_frame(0x88, c.first);
  25489. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25490. std::string reply;
  25491. char buf[256];
  25492. while (reply.size() < 2 + c.second.size()) {
  25493. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25494. if (n <= 0) { break; }
  25495. reply.append(buf, static_cast<size_t>(n));
  25496. }
  25497. detail::close_socket(sock);
  25498. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25499. c.second,
  25500. reply);
  25501. }
  25502. }
  25503. }
  25504. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25505. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25506. protected:
  25507. void SetUp() override {
  25508. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25509. SERVER_PRIVATE_KEY_FILE);
  25510. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25511. std::string msg;
  25512. ws::ReadResult ret;
  25513. while ((ret = ws.read(msg))) {
  25514. if (ret == ws::Binary) {
  25515. ws.send(msg.data(), msg.size());
  25516. } else {
  25517. ws.send(msg);
  25518. }
  25519. }
  25520. });
  25521. port_ = server_->bind_to_any_port(HOST);
  25522. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25523. server_->wait_until_ready();
  25524. }
  25525. void TearDown() override {
  25526. server_->stop();
  25527. if (server_thread_.joinable()) { server_thread_.join(); }
  25528. }
  25529. std::unique_ptr<SSLServer> server_;
  25530. std::thread server_thread_;
  25531. int port_ = 0;
  25532. };
  25533. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25534. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25535. {
  25536. ws::WebSocketClient client(url);
  25537. client.enable_server_certificate_verification(false);
  25538. auto calls = 0;
  25539. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25540. calls++;
  25541. return false;
  25542. });
  25543. EXPECT_FALSE(client.connect());
  25544. EXPECT_GT(calls, 0);
  25545. }
  25546. {
  25547. ws::WebSocketClient client(url);
  25548. client.enable_server_certificate_verification(false);
  25549. client.set_session_verifier([](tls::session_t) {
  25550. return SSLVerifierResponse::CertificateRejected;
  25551. });
  25552. EXPECT_FALSE(client.connect());
  25553. }
  25554. {
  25555. ws::WebSocketClient client(url);
  25556. client.enable_server_certificate_verification(false);
  25557. client.set_session_verifier([](tls::session_t) {
  25558. return SSLVerifierResponse::CertificateAccepted;
  25559. });
  25560. EXPECT_TRUE(client.connect());
  25561. }
  25562. }
  25563. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25564. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25565. "/ws-echo");
  25566. client.enable_server_certificate_verification(false);
  25567. ASSERT_TRUE(client.connect());
  25568. ASSERT_TRUE(client.is_open());
  25569. ASSERT_TRUE(client.send("Hello WSS"));
  25570. std::string msg;
  25571. EXPECT_EQ(ws::Text, client.read(msg));
  25572. EXPECT_EQ("Hello WSS", msg);
  25573. client.close();
  25574. }
  25575. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25576. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25577. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25578. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25579. // client (without calling close() first) is the only path that runs
  25580. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25581. // bug exactly.
  25582. //
  25583. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25584. // when linked against an instrumented libssl; run under Valgrind to catch it
  25585. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25586. // suite (the freed session otherwise stalls on the close handshake) — this test
  25587. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25588. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25589. {
  25590. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25591. "/ws-echo");
  25592. client.enable_server_certificate_verification(false);
  25593. client.set_read_timeout(2, 0);
  25594. client.set_write_timeout(2, 0);
  25595. ASSERT_TRUE(client.connect());
  25596. ASSERT_TRUE(client.is_open());
  25597. ASSERT_TRUE(client.send("still open"));
  25598. // Intentionally do NOT call client.close(): leaving scope runs
  25599. // shutdown_and_close() with the WebSocket still open, which must send the
  25600. // close frame while the TLS session is still alive.
  25601. }
  25602. }
  25603. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25604. // shutdown_and_close() at the start of connect(), reproducing the same
  25605. // use-after-free within the test body rather than at scope exit. The second
  25606. // connect must succeed and echo, proving the close handshake ran over a live
  25607. // session. See the note above about memory-tool requirements.
  25608. TEST_F(WebSocketSSLIntegrationTest,
  25609. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25610. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25611. "/ws-echo");
  25612. client.enable_server_certificate_verification(false);
  25613. client.set_read_timeout(2, 0);
  25614. client.set_write_timeout(2, 0);
  25615. ASSERT_TRUE(client.connect());
  25616. ASSERT_TRUE(client.is_open());
  25617. ASSERT_TRUE(client.send("still open"));
  25618. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25619. // the still-open connection, which must not touch a freed TLS session.
  25620. ASSERT_TRUE(client.connect());
  25621. ASSERT_TRUE(client.is_open());
  25622. ASSERT_TRUE(client.send("after reconnect"));
  25623. std::string msg;
  25624. EXPECT_EQ(ws::Text, client.read(msg));
  25625. EXPECT_EQ("after reconnect", msg);
  25626. client.close();
  25627. }
  25628. #endif
  25629. #ifdef CPPHTTPLIB_SSL_ENABLED
  25630. class WebSocketSSLCATest : public ::testing::Test {
  25631. protected:
  25632. void SetUp() override {
  25633. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25634. SERVER_PRIVATE_KEY_FILE);
  25635. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25636. std::string msg;
  25637. while (ws.read(msg)) {
  25638. ws.send(msg);
  25639. }
  25640. });
  25641. port_ = server_->bind_to_any_port("127.0.0.1");
  25642. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25643. server_->wait_until_ready();
  25644. }
  25645. void TearDown() override {
  25646. server_->stop();
  25647. if (server_thread_.joinable()) { server_thread_.join(); }
  25648. }
  25649. std::string url() const {
  25650. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25651. }
  25652. std::unique_ptr<SSLServer> server_;
  25653. std::thread server_thread_;
  25654. int port_ = 0;
  25655. };
  25656. // A custom CA loaded as PEM verifies the server with full certificate
  25657. // verification enabled
  25658. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25659. ws::WebSocketClient client(url());
  25660. std::string cert;
  25661. read_file(SERVER_CERT2_FILE, cert);
  25662. client.load_ca_cert_store(cert.c_str(), cert.size());
  25663. ASSERT_TRUE(client.connect());
  25664. ASSERT_TRUE(client.send("hello"));
  25665. std::string msg;
  25666. EXPECT_EQ(ws::Text, client.read(msg));
  25667. EXPECT_EQ("hello", msg);
  25668. client.close();
  25669. }
  25670. // A custom CA that does not cover the server must fail verification (the
  25671. // custom CA is exclusive; system certs are not loaded alongside it)
  25672. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25673. ws::WebSocketClient client(url());
  25674. std::string cert;
  25675. read_file(CLIENT_CA_CERT_FILE, cert);
  25676. client.load_ca_cert_store(cert.c_str(), cert.size());
  25677. auto res = client.connect();
  25678. ASSERT_FALSE(res);
  25679. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25680. EXPECT_EQ(-1, res.status());
  25681. EXPECT_NE(0u, res.ssl_backend_error());
  25682. }
  25683. // The same CA as a file path rather than PEM in memory
  25684. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25685. ws::WebSocketClient client(url());
  25686. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25687. ASSERT_TRUE(client.connect());
  25688. ASSERT_TRUE(client.send("hello"));
  25689. std::string msg;
  25690. EXPECT_EQ(ws::Text, client.read(msg));
  25691. EXPECT_EQ("hello", msg);
  25692. client.close();
  25693. }
  25694. // ...and a CA file that does not cover the server still fails, so it is the
  25695. // path above that decides the outcome
  25696. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25697. ws::WebSocketClient client(url());
  25698. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25699. ASSERT_FALSE(client.connect());
  25700. }
  25701. // Regression test: reconnecting with a native custom CA store used to reuse
  25702. // a store handle the previous TLS context had already freed (use-after-free
  25703. // under the OpenSSL backend). The context now lives as long as the client.
  25704. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25705. ws::WebSocketClient client(url());
  25706. std::string cert;
  25707. read_file(SERVER_CERT2_FILE, cert);
  25708. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25709. ASSERT_TRUE(client.connect());
  25710. client.close();
  25711. ASSERT_TRUE(client.connect());
  25712. ASSERT_TRUE(client.send("again"));
  25713. std::string msg;
  25714. EXPECT_EQ(ws::Text, client.read(msg));
  25715. EXPECT_EQ("again", msg);
  25716. client.close();
  25717. }
  25718. // Regression test: a certificate with a trusted chain but no identity match
  25719. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25720. // verification entirely for IP hosts, so this connection succeeded there.
  25721. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25722. // chain verification while the identity check must still fail.
  25723. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25725. ASSERT_TRUE(svr.is_valid());
  25726. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25727. std::string msg;
  25728. while (ws.read(msg)) {
  25729. ws.send(msg);
  25730. }
  25731. });
  25732. auto port = svr.bind_to_any_port("127.0.0.1");
  25733. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25734. auto se = detail::scope_exit([&] {
  25735. svr.stop();
  25736. t.join();
  25737. });
  25738. svr.wait_until_ready();
  25739. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25740. "/echo");
  25741. std::string cert;
  25742. read_file(SERVER_CERT_FILE, cert);
  25743. client.load_ca_cert_store(cert.c_str(), cert.size());
  25744. ASSERT_FALSE(client.connect());
  25745. }
  25746. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25747. // SNI, so nothing binds the host name to the TLS session. These bind the
  25748. // server to "localhost" instead, the only shape that exercises the SNI and
  25749. // hostname-verification path with certificate verification left enabled.
  25750. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25751. protected:
  25752. void Start(const char *cert_file) {
  25753. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25754. SERVER_PRIVATE_KEY_FILE);
  25755. ASSERT_TRUE(server_->is_valid());
  25756. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25757. std::string msg;
  25758. while (ws.read(msg)) {
  25759. ws.send(msg);
  25760. }
  25761. });
  25762. port_ = server_->bind_to_any_port("localhost");
  25763. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25764. server_->wait_until_ready();
  25765. }
  25766. void TearDown() override {
  25767. if (server_) { server_->stop(); }
  25768. if (server_thread_.joinable()) { server_thread_.join(); }
  25769. }
  25770. std::string url() const {
  25771. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25772. }
  25773. std::unique_ptr<SSLServer> server_;
  25774. std::thread server_thread_;
  25775. int port_ = 0;
  25776. };
  25777. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25778. // out and the connection is usable
  25779. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25780. Start(SERVER_CERT2_FILE);
  25781. ws::WebSocketClient client(url());
  25782. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25783. ASSERT_TRUE(client.connect());
  25784. ASSERT_TRUE(client.send("hello"));
  25785. std::string msg;
  25786. EXPECT_EQ(ws::Text, client.read(msg));
  25787. EXPECT_EQ("hello", msg);
  25788. client.close();
  25789. }
  25790. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25791. // while the identity check must still reject "localhost"
  25792. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25793. Start(SERVER_CERT_FILE);
  25794. ws::WebSocketClient client(url());
  25795. client.set_ca_cert_path(SERVER_CERT_FILE);
  25796. auto res = client.connect();
  25797. ASSERT_FALSE(res);
  25798. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25799. EXPECT_EQ(-1, res.status());
  25800. }
  25801. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25802. // disabled: the chain is still checked, only the identity check is skipped
  25803. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25804. Start(SERVER_CERT_FILE);
  25805. ws::WebSocketClient client(url());
  25806. client.set_ca_cert_path(SERVER_CERT_FILE);
  25807. client.enable_server_hostname_verification(false);
  25808. ASSERT_TRUE(client.connect());
  25809. ASSERT_TRUE(client.send("hello"));
  25810. std::string msg;
  25811. EXPECT_EQ(ws::Text, client.read(msg));
  25812. EXPECT_EQ("hello", msg);
  25813. client.close();
  25814. }
  25815. // A CA that did not sign the server certificate fails the chain, even though
  25816. // the name would match
  25817. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25818. Start(SERVER_CERT2_FILE);
  25819. ws::WebSocketClient client(url());
  25820. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25821. ASSERT_FALSE(client.connect());
  25822. }
  25823. // With verification disabled, neither the chain nor the name is checked
  25824. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25825. Start(SERVER_CERT_FILE);
  25826. ws::WebSocketClient client(url());
  25827. client.enable_server_certificate_verification(false);
  25828. ASSERT_TRUE(client.connect());
  25829. ASSERT_TRUE(client.send("hello"));
  25830. std::string msg;
  25831. EXPECT_EQ(ws::Text, client.read(msg));
  25832. EXPECT_EQ("hello", msg);
  25833. client.close();
  25834. }
  25835. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25836. protected:
  25837. void SetUp() override {
  25838. server_ = httplib::detail::make_unique<SSLServer>(
  25839. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25840. ASSERT_TRUE(server_->is_valid());
  25841. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25842. std::string msg;
  25843. while (ws.read(msg)) {
  25844. ws.send(msg);
  25845. }
  25846. });
  25847. port_ = server_->bind_to_any_port("localhost");
  25848. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25849. server_->wait_until_ready();
  25850. }
  25851. void TearDown() override {
  25852. server_->stop();
  25853. if (server_thread_.joinable()) { server_thread_.join(); }
  25854. }
  25855. std::string url() const {
  25856. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25857. }
  25858. void ConnectWithClientCert(const std::string &client_cert_file,
  25859. const std::string &client_private_key_file,
  25860. const char *private_key_password) {
  25861. std::string cert_pem, key_pem;
  25862. read_file(client_cert_file, cert_pem);
  25863. read_file(client_private_key_file, key_pem);
  25864. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25865. key_pem.c_str(), key_pem.size(),
  25866. private_key_password};
  25867. ConnectWithPem(pem);
  25868. }
  25869. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25870. ws::WebSocketClient client(url(), pem);
  25871. ASSERT_TRUE(client.is_valid());
  25872. client.enable_server_certificate_verification(false);
  25873. ASSERT_TRUE(client.connect());
  25874. ASSERT_TRUE(client.send("hello"));
  25875. std::string msg;
  25876. EXPECT_EQ(ws::Text, client.read(msg));
  25877. EXPECT_EQ("hello", msg);
  25878. client.close();
  25879. }
  25880. std::unique_ptr<SSLServer> server_;
  25881. std::thread server_thread_;
  25882. int port_ = 0;
  25883. };
  25884. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25885. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25886. }
  25887. // Control for the tests above: the fixture's server really does require a
  25888. // client certificate, so it is the PEM the constructor installed that decides
  25889. // the outcome.
  25890. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25891. ws::WebSocketClient client(url());
  25892. ASSERT_TRUE(client.is_valid());
  25893. client.enable_server_certificate_verification(false);
  25894. EXPECT_FALSE(client.connect());
  25895. }
  25896. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25897. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25898. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25899. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25900. }
  25901. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25902. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25903. std::string cert_pem, key_pem;
  25904. read_file(CLIENT_CERT_FILE, cert_pem);
  25905. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25906. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25907. std::vector<char> key(key_pem.begin(), key_pem.end());
  25908. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25909. key.size(), nullptr};
  25910. ConnectWithPem(pem);
  25911. }
  25912. #endif
  25913. #if !defined(_WIN32)
  25914. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25915. auto secret_dir = std::string("./symlink_test_secret");
  25916. auto served_dir = std::string("./symlink_test_served");
  25917. auto secret_file = secret_dir + "/secret.txt";
  25918. auto symlink_path = served_dir + "/escape";
  25919. // Setup: create directories and files
  25920. mkdir(secret_dir.c_str(), 0755);
  25921. mkdir(served_dir.c_str(), 0755);
  25922. {
  25923. std::ofstream ofs(secret_file);
  25924. ofs << "SECRET_DATA";
  25925. }
  25926. // Create symlink using absolute path so it resolves correctly
  25927. #ifdef PATH_MAX
  25928. char abs_secret[PATH_MAX];
  25929. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25930. #else
  25931. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25932. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25933. ASSERT_NE(nullptr, abs_secret);
  25934. #endif
  25935. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25936. auto se = detail::scope_exit([&] {
  25937. unlink(symlink_path.c_str());
  25938. unlink(secret_file.c_str());
  25939. rmdir(served_dir.c_str());
  25940. rmdir(secret_dir.c_str());
  25941. });
  25942. Server svr;
  25943. svr.set_mount_point("/", served_dir);
  25944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25945. auto se2 = detail::scope_exit([&] {
  25946. svr.stop();
  25947. listen_thread.join();
  25948. });
  25949. svr.wait_until_ready();
  25950. Client cli("localhost", PORT);
  25951. // Symlink pointing outside base dir should be blocked
  25952. auto res = cli.Get("/escape/secret.txt");
  25953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25954. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25955. }
  25956. #endif
  25957. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25958. // "GET /smuggled" request), reads the first response, and only then sends the
  25959. // embedded request as the body. Returns how many times /smuggled ran.
  25960. //
  25961. // The body is sent AFTER receiving the first response (as in the original
  25962. // PoC) so that the stream_line_reader cannot buffer it together with the
  25963. // headers of the first request.
  25964. static int count_smuggled_requests(const std::string &outer_head,
  25965. std::string &first_response) {
  25966. Server svr;
  25967. svr.set_mount_point("/", "./www");
  25968. std::atomic<int> smuggled_count(0);
  25969. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25970. smuggled_count++;
  25971. res.set_content("oops", "text/plain");
  25972. });
  25973. svr.Post("/post", [&](const Request &req, Response &res) {
  25974. res.set_content(req.body, "text/plain");
  25975. });
  25976. auto port = svr.bind_to_any_port("localhost");
  25977. thread t = thread([&] { svr.listen_after_bind(); });
  25978. auto se = detail::scope_exit([&] {
  25979. svr.stop();
  25980. t.join();
  25981. });
  25982. svr.wait_until_ready();
  25983. auto error = Error::Success;
  25984. auto sock = detail::create_client_socket(
  25985. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25986. /*connection_timeout_sec=*/2, 0,
  25987. /*read_timeout_sec=*/2, 0,
  25988. /*write_timeout_sec=*/2, 0, std::string(), error);
  25989. EXPECT_NE(INVALID_SOCKET, sock);
  25990. if (sock == INVALID_SOCKET) { return -1; }
  25991. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25992. // The "smuggled" request will be sent as the body of the outer request
  25993. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25994. "Host: localhost\r\n"
  25995. "Connection: close\r\n"
  25996. "\r\n";
  25997. auto head = outer_head;
  25998. auto len = std::to_string(smuggled.size());
  25999. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26000. pos = head.find("{len}", pos + len.size())) {
  26001. head.replace(pos, 5, len);
  26002. }
  26003. // Step 1: Send only the outer request headers (no body yet)
  26004. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26005. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26006. // Step 2: Read the first response
  26007. char buf[4096];
  26008. for (;;) {
  26009. auto n = recv(sock, buf, sizeof(buf), 0);
  26010. if (n <= 0) break;
  26011. first_response.append(buf, static_cast<size_t>(n));
  26012. // Stop once we have a complete response (headers + body)
  26013. auto hdr_end = first_response.find("\r\n\r\n");
  26014. if (hdr_end != std::string::npos) {
  26015. // Check for Content-Length to know when the body is complete
  26016. auto cl_pos = first_response.find("Content-Length:");
  26017. if (cl_pos != std::string::npos) {
  26018. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26019. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26020. auto cl = std::stoul(
  26021. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26022. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26023. } else {
  26024. break; // No Content-Length, assume headers-only response
  26025. }
  26026. }
  26027. }
  26028. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26029. // vulnerable server the keep-alive loop reads this as a second request. The
  26030. // server may already have closed the connection, so the result is ignored.
  26031. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26032. // Half-close so that a server which drained the body sees EOF and closes,
  26033. // instead of the read below waiting for the read timeout.
  26034. #ifdef _WIN32
  26035. ::shutdown(sock, SD_SEND);
  26036. #else
  26037. ::shutdown(sock, SHUT_WR);
  26038. #endif
  26039. // Step 4: Read until the server closes the connection
  26040. for (;;) {
  26041. auto n = recv(sock, buf, sizeof(buf), 0);
  26042. if (n <= 0) break;
  26043. }
  26044. return smuggled_count.load();
  26045. }
  26046. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26047. // A GET request with Content-Length to a static file handler must have its
  26048. // body drained before the keep-alive connection is reused. Otherwise the
  26049. // unread body bytes are interpreted as the next HTTP request.
  26050. std::string first_response;
  26051. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26052. "Host: localhost\r\n"
  26053. "Content-Length: {len}\r\n"
  26054. "\r\n",
  26055. first_response));
  26056. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26057. }
  26058. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26059. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26060. // be answered with 400 and the connection closed. Treating it as "no body"
  26061. // leaves the body to be parsed as the next request.
  26062. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26063. const char *targets[] = {
  26064. "GET /file", // handler that never reads the body
  26065. "GET /not-found", // no handler matches (404)
  26066. "POST /post", // handler that reads the body
  26067. };
  26068. for (auto target : targets) {
  26069. for (auto value : values) {
  26070. std::string first_response;
  26071. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26072. " HTTP/1.1\r\n"
  26073. "Host: localhost\r\n"
  26074. "Content-Length: " +
  26075. value + "\r\n\r\n",
  26076. first_response))
  26077. << target << " with Content-Length: " << value;
  26078. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  26079. << target << " with Content-Length: " << value;
  26080. }
  26081. }
  26082. }
  26083. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  26084. // A 400 for an unparseable request line leaves the rest of the message
  26085. // unread, so the connection must be closed rather than reused.
  26086. std::string first_response;
  26087. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  26088. "Host: localhost\r\n"
  26089. "Content-Length: {len}\r\n"
  26090. "\r\n",
  26091. first_response));
  26092. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26093. }
  26094. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  26095. // Same as above for a header block that fails to parse.
  26096. std::string first_response;
  26097. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26098. "Host: localhost\r\n"
  26099. "Bad Header\r\n"
  26100. "Content-Length: {len}\r\n"
  26101. "\r\n",
  26102. first_response));
  26103. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26104. }
  26105. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  26106. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  26107. // server must not read another request on that connection, even when the
  26108. // request had no body to drain.
  26109. std::string first_response;
  26110. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  26111. "Host: localhost\r\n"
  26112. "\r\n",
  26113. first_response));
  26114. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26115. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26116. }
  26117. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26118. // A content reader that stops early leaves the stream inside the body.
  26119. // Draining the whole Content-Length from there, or reading the body again,
  26120. // reads into the next request, and whatever follows is parsed as a request
  26121. // of its own.
  26122. Server svr;
  26123. std::atomic<int> smuggled_count(0);
  26124. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26125. svr.Post("/upload", [](const Request &req, Response &res,
  26126. const ContentReader &content_reader) {
  26127. // Stop at the last chunk, so the whole body has been read however it
  26128. // arrives.
  26129. auto length = req.get_header_value_u64("Content-Length");
  26130. size_t total = 0;
  26131. auto consumed = content_reader([&](const char *, size_t n) {
  26132. total += n;
  26133. return total < length;
  26134. });
  26135. EXPECT_FALSE(consumed);
  26136. if (req.has_param("retry")) {
  26137. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26138. }
  26139. // Replace the 400 the aborted read set, which would close the connection.
  26140. res.set_redirect("/done");
  26141. });
  26142. auto port = svr.bind_to_any_port(HOST);
  26143. thread t = thread([&] { svr.listen_after_bind(); });
  26144. auto se = detail::scope_exit([&] {
  26145. svr.stop();
  26146. t.join();
  26147. });
  26148. svr.wait_until_ready();
  26149. // A front end sees the second request as a POST whose body is the GET. The
  26150. // first body is as long as the POST's headers, so draining it again reads
  26151. // exactly those and leaves the GET to be parsed next.
  26152. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26153. "Host: localhost\r\n"
  26154. "\r\n";
  26155. std::string second_head = "POST /post HTTP/1.1\r\n"
  26156. "Host: localhost\r\n"
  26157. "Content-Length: " +
  26158. std::to_string(inner.size()) +
  26159. "\r\n"
  26160. "\r\n";
  26161. for (auto target : {"/upload", "/upload?retry"}) {
  26162. smuggled_count = 0;
  26163. std::string request = "POST " + std::string(target) +
  26164. " HTTP/1.1\r\n"
  26165. "Host: localhost\r\n"
  26166. "Content-Length: " +
  26167. std::to_string(second_head.size()) +
  26168. "\r\n"
  26169. "\r\n" +
  26170. std::string(second_head.size(), 'A') + second_head +
  26171. inner;
  26172. std::string response;
  26173. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26174. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26175. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26176. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26177. EXPECT_EQ(0, smuggled_count.load()) << target;
  26178. }
  26179. }
  26180. // An error response closes the connection anyway, so the body is left unread
  26181. // with a redirect, such as one to a login page.
  26182. static void serve_redirects(Server &svr,
  26183. const std::function<void(int)> &client) {
  26184. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26185. res.set_redirect("/login");
  26186. return Server::HandlerResponse::Handled;
  26187. });
  26188. auto port = svr.bind_to_any_port(HOST);
  26189. ASSERT_GT(port, 0);
  26190. thread t = thread([&] { svr.listen_after_bind(); });
  26191. auto se = detail::scope_exit([&] {
  26192. svr.stop();
  26193. t.join();
  26194. ASSERT_FALSE(svr.is_running());
  26195. });
  26196. svr.wait_until_ready();
  26197. client(port);
  26198. }
  26199. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26200. Server svr;
  26201. serve_redirects(svr, [](int port) {
  26202. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26203. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26204. std::to_string(body.size()) + "\r\n\r\n" + body +
  26205. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26206. std::string resp;
  26207. ASSERT_TRUE(send_request(1, req, &resp, port));
  26208. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26209. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26210. });
  26211. }
  26212. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26213. Server svr;
  26214. svr.set_read_timeout(0, 200000);
  26215. serve_redirects(svr, [](int port) {
  26216. // A byte every 100 ms keeps each read within the read timeout, but not the
  26217. // body as a whole, so the server closes and the bytes sent after that fail.
  26218. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26219. "Content-Length: 10\r\n\r\n"};
  26220. parts.resize(11, "x");
  26221. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26222. });
  26223. }
  26224. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26225. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26226. // must be rejected with 400 Bad Request.
  26227. Server svr;
  26228. svr.Post("/test", [&](const Request &, Response &res) {
  26229. res.set_content("ok", "text/plain");
  26230. });
  26231. thread t = thread([&] { svr.listen(HOST, PORT); });
  26232. auto se = detail::scope_exit([&] {
  26233. svr.stop();
  26234. t.join();
  26235. ASSERT_FALSE(svr.is_running());
  26236. });
  26237. svr.wait_until_ready();
  26238. // Exact "chunked"
  26239. {
  26240. auto req = "POST /test HTTP/1.1\r\n"
  26241. "Host: localhost\r\n"
  26242. "Content-Length: 5\r\n"
  26243. "Transfer-Encoding: chunked\r\n"
  26244. "Connection: close\r\n"
  26245. "\r\n"
  26246. "hello";
  26247. std::string response;
  26248. ASSERT_TRUE(send_request(1, req, &response));
  26249. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26250. response.substr(0, response.find("\r\n")));
  26251. }
  26252. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26253. {
  26254. auto req = "POST /test HTTP/1.1\r\n"
  26255. "Host: localhost\r\n"
  26256. "Content-Length: 5\r\n"
  26257. "Transfer-Encoding: gzip, chunked\r\n"
  26258. "Connection: close\r\n"
  26259. "\r\n"
  26260. "hello";
  26261. std::string response;
  26262. ASSERT_TRUE(send_request(1, req, &response));
  26263. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26264. response.substr(0, response.find("\r\n")));
  26265. }
  26266. }
  26267. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26268. Server svr;
  26269. svr.Post("/test", [&](const Request &, Response &res) {
  26270. res.set_content("ok", "text/plain");
  26271. });
  26272. thread t = thread([&] { svr.listen(HOST, PORT); });
  26273. auto se = detail::scope_exit([&] {
  26274. svr.stop();
  26275. t.join();
  26276. ASSERT_FALSE(svr.is_running());
  26277. });
  26278. svr.wait_until_ready();
  26279. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26280. // length cannot be determined, so the server must answer 400 and close
  26281. // rather than treat the request as bodyless and leave the body in the
  26282. // socket for the next request to pick up.
  26283. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26284. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26285. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26286. std::string response;
  26287. ASSERT_TRUE(send_request(1, req, &response));
  26288. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26289. response.substr(0, response.find("\r\n")))
  26290. << transfer_encoding;
  26291. }
  26292. // RFC 9110 5.3: the codings may also be split across several
  26293. // Transfer-Encoding lines, which combine in the order they were received.
  26294. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26295. // just like the single-line "chunked, gzip" above.
  26296. {
  26297. auto req = "POST /test HTTP/1.1\r\n"
  26298. "Host: localhost\r\n"
  26299. "Transfer-Encoding: chunked\r\n"
  26300. "Transfer-Encoding: gzip\r\n"
  26301. "\r\n"
  26302. "0\r\n\r\n";
  26303. std::string response;
  26304. ASSERT_TRUE(send_request(1, req, &response));
  26305. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26306. response.substr(0, response.find("\r\n")));
  26307. }
  26308. }
  26309. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26310. Server svr;
  26311. svr.Post("/test", [&](const Request &, Response &res) {
  26312. res.set_content("ok", "text/plain");
  26313. });
  26314. auto port = svr.bind_to_any_port(HOST);
  26315. ASSERT_GT(port, 0);
  26316. thread t = thread([&] { svr.listen_after_bind(); });
  26317. auto se = detail::scope_exit([&] {
  26318. svr.stop();
  26319. t.join();
  26320. ASSERT_FALSE(svr.is_running());
  26321. });
  26322. svr.wait_until_ready();
  26323. for (auto transfer_encoding :
  26324. {"Transfer-Encoding: gzip, chunked\r\n",
  26325. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26326. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26327. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26328. transfer_encoding + "\r\n0\r\n\r\n";
  26329. std::string response;
  26330. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26331. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26332. response.substr(0, response.find("\r\n")))
  26333. << transfer_encoding;
  26334. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26335. << transfer_encoding;
  26336. }
  26337. }
  26338. // Regression for issue #2450: a DELETE without Content-Length on a
  26339. // keep-alive connection must not let the post-response drain consume the
  26340. // next request's bytes.
  26341. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26342. Server svr;
  26343. std::atomic<int> delete_count(0);
  26344. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26345. delete_count++;
  26346. res.status = StatusCode::NoContent_204;
  26347. });
  26348. auto port = svr.bind_to_any_port(HOST);
  26349. thread t = thread([&] { svr.listen_after_bind(); });
  26350. auto se = detail::scope_exit([&] {
  26351. svr.stop();
  26352. t.join();
  26353. });
  26354. svr.wait_until_ready();
  26355. auto error = Error::Success;
  26356. auto sock = detail::create_client_socket(
  26357. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26358. /*connection_timeout_sec=*/2, 0,
  26359. /*read_timeout_sec=*/2, 0,
  26360. /*write_timeout_sec=*/2, 0, std::string(), error);
  26361. ASSERT_NE(INVALID_SOCKET, sock);
  26362. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26363. auto send_request_and_read_response = [&](const std::string &req,
  26364. std::string &out) -> bool {
  26365. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26366. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26367. char buf[4096];
  26368. for (;;) {
  26369. auto n = recv(sock, buf, sizeof(buf), 0);
  26370. if (n <= 0) { return !out.empty(); }
  26371. out.append(buf, static_cast<size_t>(n));
  26372. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26373. }
  26374. };
  26375. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26376. "Host: localhost\r\n"
  26377. "\r\n";
  26378. std::string resp1;
  26379. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26380. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26381. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26382. "Host: localhost\r\n"
  26383. "Connection: close\r\n"
  26384. "\r\n";
  26385. std::string resp2;
  26386. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26387. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26388. EXPECT_EQ(2, delete_count.load());
  26389. }
  26390. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26391. Server svr;
  26392. svr.Post("/ingest", [&](const Request &, Response &res,
  26393. const ContentReader &content_reader) {
  26394. auto consumed = content_reader([](const char *, size_t) { return false; });
  26395. EXPECT_FALSE(consumed);
  26396. res.status = StatusCode::Conflict_409;
  26397. res.set_header("Connection", "close");
  26398. });
  26399. auto port = svr.bind_to_any_port(HOST);
  26400. thread t = thread([&] { svr.listen_after_bind(); });
  26401. auto se = detail::scope_exit([&] {
  26402. svr.stop();
  26403. t.join();
  26404. });
  26405. svr.wait_until_ready();
  26406. auto error = Error::Success;
  26407. auto sock = detail::create_client_socket(
  26408. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26409. /*connection_timeout_sec=*/2, 0,
  26410. /*read_timeout_sec=*/1, 0,
  26411. /*write_timeout_sec=*/2, 0, std::string(), error);
  26412. ASSERT_NE(INVALID_SOCKET, sock);
  26413. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26414. std::string request = "POST /ingest HTTP/1.1\r\n"
  26415. "Host: localhost\r\n"
  26416. "Transfer-Encoding: chunked\r\n"
  26417. "\r\n"
  26418. "4\r\n"
  26419. "data\r\n";
  26420. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26421. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26422. std::string response;
  26423. ssize_t received = 0;
  26424. do {
  26425. char buf[4096];
  26426. received = recv(sock, buf, sizeof(buf), 0);
  26427. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26428. } while (received > 0);
  26429. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26430. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26431. EXPECT_EQ(0, received);
  26432. }
  26433. namespace no_proxy_test {
  26434. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26435. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26436. // calling listen().
  26437. class ScopedServer {
  26438. public:
  26439. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26440. ~ScopedServer() {
  26441. svr_.stop();
  26442. if (th_.joinable()) { th_.join(); }
  26443. }
  26444. Server &svr() { return svr_; }
  26445. int port() const { return port_; }
  26446. void listen() {
  26447. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26448. svr_.wait_until_ready();
  26449. }
  26450. private:
  26451. Server svr_;
  26452. std::thread th_;
  26453. int port_ = 0;
  26454. };
  26455. class ProxyAndTargetServers {
  26456. public:
  26457. ProxyAndTargetServers() {
  26458. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26459. proxy_hits_++;
  26460. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26461. res.set_content("via-proxy", "text/plain");
  26462. });
  26463. target_.Get(".*", [this](const Request &req, Response &res) {
  26464. target_hits_++;
  26465. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26466. res.set_content("direct", "text/plain");
  26467. });
  26468. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26469. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26470. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26471. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26472. proxy_mock_.wait_until_ready();
  26473. target_.wait_until_ready();
  26474. }
  26475. ~ProxyAndTargetServers() {
  26476. proxy_mock_.stop();
  26477. target_.stop();
  26478. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26479. if (target_thread_.joinable()) { target_thread_.join(); }
  26480. }
  26481. Server &proxy_mock() { return proxy_mock_; }
  26482. Server &target() { return target_; }
  26483. int proxy_port() const { return proxy_port_; }
  26484. int target_port() const { return target_port_; }
  26485. int proxy_hits() const { return proxy_hits_.load(); }
  26486. int target_hits() const { return target_hits_.load(); }
  26487. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26488. void reset_counters() {
  26489. proxy_hits_ = 0;
  26490. target_hits_ = 0;
  26491. last_had_proxy_authz_ = false;
  26492. }
  26493. private:
  26494. Server proxy_mock_;
  26495. Server target_;
  26496. std::thread proxy_thread_;
  26497. std::thread target_thread_;
  26498. int proxy_port_ = 0;
  26499. int target_port_ = 0;
  26500. std::atomic<int> proxy_hits_{0};
  26501. std::atomic<int> target_hits_{0};
  26502. std::atomic<bool> last_had_proxy_authz_{false};
  26503. };
  26504. inline std::unique_ptr<Client> make_client(const std::string &host,
  26505. ProxyAndTargetServers &s) {
  26506. auto cli = detail::make_unique<Client>(host, s.target_port());
  26507. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26508. cli->set_proxy("127.0.0.1", s.proxy_port());
  26509. return cli;
  26510. }
  26511. } // namespace no_proxy_test
  26512. using no_proxy_test::make_client;
  26513. using no_proxy_test::ProxyAndTargetServers;
  26514. // A stream request carries the credentials a buffered request does
  26515. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26516. no_proxy_test::ScopedServer origin;
  26517. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26518. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26519. });
  26520. origin.listen();
  26521. Client cli("127.0.0.1", origin.port());
  26522. cli.set_basic_auth("user", "pass");
  26523. auto handle = cli.open_stream("GET", "/x");
  26524. ASSERT_TRUE(handle.is_valid());
  26525. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26526. Client bearer("127.0.0.1", origin.port());
  26527. bearer.set_bearer_token_auth("tok");
  26528. auto handle2 = bearer.open_stream("GET", "/x");
  26529. ASSERT_TRUE(handle2.is_valid());
  26530. EXPECT_EQ("Bearer tok", read_all(handle2));
  26531. }
  26532. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26533. // takes its own credentials, as for a buffered request
  26534. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26535. std::string target, authz, proxy_authz;
  26536. no_proxy_test::ScopedServer proxy;
  26537. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26538. target = req.target;
  26539. authz = req.get_header_value("Authorization");
  26540. proxy_authz = req.get_header_value("Proxy-Authorization");
  26541. res.set_content("ok", "text/plain");
  26542. });
  26543. proxy.listen();
  26544. Client cli("origin.example", 8080);
  26545. cli.set_proxy("127.0.0.1", proxy.port());
  26546. cli.set_proxy_basic_auth("puser", "ppass");
  26547. cli.set_basic_auth("user", "pass");
  26548. auto handle = cli.open_stream("GET", "/x");
  26549. ASSERT_TRUE(handle.is_valid());
  26550. EXPECT_EQ("ok", read_all(handle));
  26551. EXPECT_EQ("http://origin.example:8080/x", target);
  26552. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26553. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26554. }
  26555. // In absolute-form the path follows the authority, so a path that does not
  26556. // begin with '/' would make the proxy connect to another host
  26557. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26558. std::vector<std::string> targets;
  26559. no_proxy_test::ScopedServer proxy;
  26560. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26561. targets.push_back(req.target);
  26562. res.set_content("ok", "text/plain");
  26563. });
  26564. proxy.listen();
  26565. Client cli("origin.example", 8080);
  26566. cli.set_proxy("127.0.0.1", proxy.port());
  26567. cli.set_basic_auth("user", "pass");
  26568. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26569. auto res = cli.Get(path);
  26570. EXPECT_FALSE(res) << path;
  26571. auto handle = cli.open_stream("GET", path);
  26572. EXPECT_FALSE(handle.is_valid()) << path;
  26573. }
  26574. EXPECT_TRUE(targets.empty());
  26575. auto res = cli.Get("/x");
  26576. ASSERT_TRUE(res);
  26577. ASSERT_EQ(1u, targets.size());
  26578. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26579. }
  26580. TEST(NoProxyTest, ExactHostnameBypasses) {
  26581. ProxyAndTargetServers s;
  26582. auto cli = make_client("example.com", s);
  26583. cli->set_no_proxy({"example.com"});
  26584. auto res = cli->Get("/");
  26585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26586. EXPECT_EQ(0, s.proxy_hits());
  26587. EXPECT_EQ(1, s.target_hits());
  26588. }
  26589. TEST(NoProxyTest, SubdomainBypasses) {
  26590. ProxyAndTargetServers s;
  26591. auto cli = make_client("foo.example.com", s);
  26592. cli->set_no_proxy({"example.com"});
  26593. auto res = cli->Get("/");
  26594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26595. EXPECT_EQ(0, s.proxy_hits());
  26596. EXPECT_EQ(1, s.target_hits());
  26597. }
  26598. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26599. // Regression guard: "evilexample.com" must not be considered a subdomain
  26600. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26601. // check would let traffic bypass the proxy and leak credentials direct
  26602. // to the attacker host.
  26603. ProxyAndTargetServers s;
  26604. auto cli = make_client("evilexample.com", s);
  26605. cli->set_no_proxy({"example.com"});
  26606. auto res = cli->Get("/");
  26607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26608. EXPECT_GE(s.proxy_hits(), 1);
  26609. EXPECT_EQ(0, s.target_hits());
  26610. }
  26611. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26612. ProxyAndTargetServers s;
  26613. auto cli = make_client("example.com.evil.com", s);
  26614. cli->set_no_proxy({"example.com"});
  26615. auto res = cli->Get("/");
  26616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26617. EXPECT_GE(s.proxy_hits(), 1);
  26618. EXPECT_EQ(0, s.target_hits());
  26619. }
  26620. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26621. ProxyAndTargetServers s;
  26622. auto cli = make_client("example.com", s);
  26623. cli->set_no_proxy({".example.com"});
  26624. auto res = cli->Get("/");
  26625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26626. EXPECT_EQ(0, s.proxy_hits());
  26627. EXPECT_EQ(1, s.target_hits());
  26628. }
  26629. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26630. ProxyAndTargetServers s;
  26631. auto cli = make_client("Example.COM", s);
  26632. cli->set_no_proxy({"EXAMPLE.com"});
  26633. auto res = cli->Get("/");
  26634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26635. EXPECT_EQ(0, s.proxy_hits());
  26636. EXPECT_EQ(1, s.target_hits());
  26637. }
  26638. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26639. ProxyAndTargetServers s;
  26640. auto cli = make_client("example.com.", s);
  26641. cli->set_no_proxy({"example.com"});
  26642. auto res = cli->Get("/");
  26643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26644. EXPECT_EQ(0, s.proxy_hits());
  26645. EXPECT_EQ(1, s.target_hits());
  26646. }
  26647. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26648. // Trailing dots must be normalized on BOTH sides — host and entry.
  26649. // An implementation that only strips the host-side trailing dot would
  26650. // fail to match host "example.com" against entry "example.com." because
  26651. // a literal substring search would compare 11 chars against 12.
  26652. ProxyAndTargetServers s;
  26653. auto cli = make_client("example.com", s);
  26654. cli->set_no_proxy({"example.com."});
  26655. auto res = cli->Get("/");
  26656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26657. EXPECT_EQ(0, s.proxy_hits());
  26658. EXPECT_EQ(1, s.target_hits());
  26659. }
  26660. TEST(NoProxyTest, WildcardBypassesEverything) {
  26661. ProxyAndTargetServers s;
  26662. auto cli = make_client("anything.invalid.test", s);
  26663. cli->set_no_proxy({"*"});
  26664. auto res = cli->Get("/");
  26665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26666. EXPECT_EQ(0, s.proxy_hits());
  26667. EXPECT_EQ(1, s.target_hits());
  26668. }
  26669. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26670. ProxyAndTargetServers s;
  26671. Client cli("127.0.0.1", s.target_port());
  26672. cli.set_proxy("127.0.0.1", s.proxy_port());
  26673. cli.set_no_proxy({"127.0.0.1"});
  26674. auto res = cli.Get("/");
  26675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26676. EXPECT_EQ(0, s.proxy_hits());
  26677. EXPECT_EQ(1, s.target_hits());
  26678. }
  26679. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26680. ProxyAndTargetServers s;
  26681. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26682. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26683. cli.set_proxy("127.0.0.1", s.proxy_port());
  26684. cli.set_no_proxy({"::1"});
  26685. auto res = cli.Get("/");
  26686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26687. EXPECT_EQ(0, s.proxy_hits());
  26688. EXPECT_EQ(1, s.target_hits());
  26689. }
  26690. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26691. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26692. // must still be recognized as IPv6 for CIDR matching. Implementations
  26693. // that detect IPv6 only when the host begins with '[' would parse the
  26694. // host as a hostname and miss the match.
  26695. ProxyAndTargetServers s;
  26696. Client cli("fe80::1", s.target_port());
  26697. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26698. cli.set_proxy("127.0.0.1", s.proxy_port());
  26699. cli.set_no_proxy({"fe80::/10"});
  26700. auto res = cli.Get("/");
  26701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26702. EXPECT_EQ(0, s.proxy_hits());
  26703. EXPECT_EQ(1, s.target_hits());
  26704. }
  26705. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26706. ProxyAndTargetServers s;
  26707. Client cli("::1", s.target_port());
  26708. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26709. cli.set_proxy("127.0.0.1", s.proxy_port());
  26710. cli.set_no_proxy({"[::1]"});
  26711. auto res = cli.Get("/");
  26712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26713. EXPECT_EQ(0, s.proxy_hits());
  26714. EXPECT_EQ(1, s.target_hits());
  26715. }
  26716. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26717. ProxyAndTargetServers s;
  26718. Client cli("fe80::1", s.target_port());
  26719. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26720. cli.set_proxy("127.0.0.1", s.proxy_port());
  26721. cli.set_no_proxy({"[fe80::]/10"});
  26722. auto res = cli.Get("/");
  26723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26724. EXPECT_EQ(0, s.proxy_hits());
  26725. EXPECT_EQ(1, s.target_hits());
  26726. }
  26727. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26728. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26729. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26730. // tricks via address-family conversion.
  26731. ProxyAndTargetServers s;
  26732. Client cli("::ffff:127.0.0.1", s.target_port());
  26733. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26734. cli.set_proxy("127.0.0.1", s.proxy_port());
  26735. cli.set_no_proxy({"127.0.0.1"});
  26736. auto res = cli.Get("/");
  26737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26738. EXPECT_GE(s.proxy_hits(), 1);
  26739. EXPECT_EQ(0, s.target_hits());
  26740. }
  26741. TEST(NoProxyTest, IPv4CidrMatch) {
  26742. ProxyAndTargetServers s;
  26743. Client cli("127.0.0.1", s.target_port());
  26744. cli.set_proxy("127.0.0.1", s.proxy_port());
  26745. cli.set_no_proxy({"127.0.0.0/8"});
  26746. auto res = cli.Get("/");
  26747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26748. EXPECT_EQ(0, s.proxy_hits());
  26749. EXPECT_EQ(1, s.target_hits());
  26750. }
  26751. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26752. ProxyAndTargetServers s;
  26753. Client cli("127.0.0.1", s.target_port());
  26754. cli.set_proxy("127.0.0.1", s.proxy_port());
  26755. cli.set_no_proxy({"10.0.0.0/8"});
  26756. auto res = cli.Get("/");
  26757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26758. EXPECT_GE(s.proxy_hits(), 1);
  26759. EXPECT_EQ(0, s.target_hits());
  26760. }
  26761. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26762. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26763. // IPv4 target matches.
  26764. ProxyAndTargetServers s;
  26765. Client cli("127.0.0.1", s.target_port());
  26766. cli.set_proxy("127.0.0.1", s.proxy_port());
  26767. cli.set_no_proxy({"0.0.0.0/0"});
  26768. auto res = cli.Get("/");
  26769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26770. EXPECT_EQ(0, s.proxy_hits());
  26771. EXPECT_EQ(1, s.target_hits());
  26772. }
  26773. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26774. ProxyAndTargetServers s;
  26775. Client cli("127.0.0.1", s.target_port());
  26776. cli.set_proxy("127.0.0.1", s.proxy_port());
  26777. cli.set_no_proxy({"127.0.0.1"});
  26778. auto res = cli.Get("/");
  26779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26780. EXPECT_EQ(0, s.proxy_hits());
  26781. EXPECT_EQ(1, s.target_hits());
  26782. }
  26783. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26784. ProxyAndTargetServers s;
  26785. Client cli("127.0.0.1", s.target_port());
  26786. cli.set_proxy("127.0.0.1", s.proxy_port());
  26787. cli.set_no_proxy({"127.0.0.0/33"});
  26788. auto res = cli.Get("/");
  26789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26790. EXPECT_GE(s.proxy_hits(), 1);
  26791. EXPECT_EQ(0, s.target_hits());
  26792. }
  26793. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26794. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26795. ProxyAndTargetServers s;
  26796. Client cli("127.0.0.1", s.target_port());
  26797. cli.set_proxy("127.0.0.1", s.proxy_port());
  26798. cli.set_no_proxy({"127.0.0.1/"});
  26799. auto res = cli.Get("/");
  26800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26801. EXPECT_GE(s.proxy_hits(), 1);
  26802. EXPECT_EQ(0, s.target_hits());
  26803. }
  26804. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26805. ProxyAndTargetServers s;
  26806. auto cli = make_client("internal.corp", s);
  26807. cli->set_proxy_basic_auth("u", "p");
  26808. cli->set_no_proxy({"internal.corp"});
  26809. auto res = cli->Get("/");
  26810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26811. EXPECT_EQ(1, s.target_hits());
  26812. EXPECT_EQ(0, s.proxy_hits());
  26813. EXPECT_FALSE(s.last_had_proxy_authz())
  26814. << "Proxy-Authorization must not be sent direct to the target";
  26815. }
  26816. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26817. ProxyAndTargetServers s;
  26818. auto cli = make_client("public.example", s);
  26819. cli->set_proxy_basic_auth("u", "p");
  26820. cli->set_no_proxy({"internal.corp"}); // does not match
  26821. auto res = cli->Get("/");
  26822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26823. EXPECT_GE(s.proxy_hits(), 1);
  26824. EXPECT_TRUE(s.last_had_proxy_authz());
  26825. }
  26826. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26827. std::atomic<int> hits{0};
  26828. std::atomic<int> hits_with_authz{0};
  26829. no_proxy_test::ScopedServer proxy_mock;
  26830. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26831. hits++;
  26832. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26833. if (req.target.find("/redir") != std::string::npos) {
  26834. res.set_redirect("http://other.example/landed");
  26835. } else {
  26836. res.set_content("via-proxy", "text/plain");
  26837. }
  26838. });
  26839. proxy_mock.listen();
  26840. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26841. hits = 0;
  26842. hits_with_authz = 0;
  26843. Client cli("public.example", 80);
  26844. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26845. cli.set_proxy_basic_auth(c.first, c.second);
  26846. cli.set_follow_location(true);
  26847. // The redirect to another host goes through the proxy as well
  26848. auto res = cli.Get("/redir");
  26849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26850. EXPECT_EQ(2, hits.load());
  26851. EXPECT_EQ(2, hits_with_authz.load());
  26852. }
  26853. }
  26854. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26855. ProxyAndTargetServers s;
  26856. auto cli = make_client("anything.test", s);
  26857. auto res = cli->Get("/");
  26858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26859. EXPECT_GE(s.proxy_hits(), 1);
  26860. EXPECT_EQ(0, s.target_hits());
  26861. }
  26862. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26863. ProxyAndTargetServers s;
  26864. auto cli = make_client("example.com", s);
  26865. cli->set_no_proxy({"example.com:8080"});
  26866. auto res = cli->Get("/");
  26867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26868. EXPECT_GE(s.proxy_hits(), 1);
  26869. EXPECT_EQ(0, s.target_hits());
  26870. }
  26871. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26872. ProxyAndTargetServers s;
  26873. auto cli = make_client("anything.test", s);
  26874. cli->set_no_proxy({"", " ", "\t"});
  26875. auto res = cli->Get("/");
  26876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26877. EXPECT_GE(s.proxy_hits(), 1);
  26878. EXPECT_EQ(0, s.target_hits());
  26879. }
  26880. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26881. // An entry with leading/trailing whitespace must still match — env-style
  26882. // values are commonly pasted with stray spaces and an implementation
  26883. // that feeds the raw token directly to inet_pton would fail to match
  26884. // valid CIDRs because of the spaces.
  26885. ProxyAndTargetServers s;
  26886. Client cli("127.0.0.1", s.target_port());
  26887. cli.set_proxy("127.0.0.1", s.proxy_port());
  26888. cli.set_no_proxy({" 127.0.0.0/8 "});
  26889. auto res = cli.Get("/");
  26890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26891. EXPECT_EQ(0, s.proxy_hits());
  26892. EXPECT_EQ(1, s.target_hits());
  26893. }
  26894. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26895. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26896. // go direct and must NOT carry Proxy-Authorization.
  26897. std::atomic<int> proxy_hits{0};
  26898. std::atomic<int> target_hits{0};
  26899. std::atomic<bool> target_saw_authz{false};
  26900. no_proxy_test::ScopedServer proxy_mock, target;
  26901. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26902. proxy_hits++;
  26903. res.status = 302;
  26904. res.set_header("Location", "http://127.0.0.1:" +
  26905. std::to_string(target.port()) + "/landed");
  26906. });
  26907. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26908. target_hits++;
  26909. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26910. res.set_content("direct", "text/plain");
  26911. });
  26912. proxy_mock.listen();
  26913. target.listen();
  26914. Client cli("public.example", target.port());
  26915. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26916. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26917. cli.set_proxy_basic_auth("u", "p");
  26918. cli.set_no_proxy({"127.0.0.1"});
  26919. cli.set_follow_location(true);
  26920. auto res = cli.Get("/redir");
  26921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26922. EXPECT_GE(proxy_hits.load(), 1);
  26923. EXPECT_GE(target_hits.load(), 1);
  26924. EXPECT_FALSE(target_saw_authz.load());
  26925. }
  26926. #ifdef CPPHTTPLIB_SSL_ENABLED
  26927. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26928. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26929. // proxy creds would be sent to the (possibly hostile) origin.
  26930. std::atomic<int> target_hits{0};
  26931. std::atomic<bool> target_saw_proxy_authz{false};
  26932. no_proxy_test::ScopedServer target;
  26933. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26934. target_hits++;
  26935. if (req.has_header("Proxy-Authorization")) {
  26936. target_saw_proxy_authz = true;
  26937. }
  26938. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26939. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26940. "nonce=\"abc\", algorithm=MD5");
  26941. });
  26942. target.listen();
  26943. // The proxy address is set to the target's port: the bypass MUST kick in;
  26944. // if it doesn't, the test still routes "via proxy" to the same server and
  26945. // the Proxy-Authorization assertion below catches the leak.
  26946. Client cli("evil.example", target.port());
  26947. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26948. cli.set_proxy("127.0.0.1", target.port());
  26949. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26950. cli.set_no_proxy({"evil.example"});
  26951. auto res = cli.Get("/x");
  26952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26953. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26954. EXPECT_EQ(1, target_hits.load());
  26955. EXPECT_FALSE(target_saw_proxy_authz.load());
  26956. }
  26957. #endif
  26958. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26959. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26960. std::atomic<int> proxy_hits{0};
  26961. std::atomic<int> bypass_hits{0};
  26962. std::atomic<bool> proxy_saw_c_url{false};
  26963. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26964. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26965. proxy_hits++;
  26966. if (req.path.find("/start") != std::string::npos) {
  26967. res.status = 302;
  26968. res.set_header("Location", "http://127.0.0.1:" +
  26969. std::to_string(bypass_server.port()) +
  26970. "/middle");
  26971. return;
  26972. }
  26973. if (req.path.find("/end") != std::string::npos) {
  26974. proxy_saw_c_url = true;
  26975. res.set_content("c-via-proxy", "text/plain");
  26976. return;
  26977. }
  26978. res.set_content("unexpected", "text/plain");
  26979. });
  26980. // public.example's "advertised" port is arbitrary (the request never lands
  26981. // there — it goes through the proxy), but use a dynamic value to stay
  26982. // friendly with sharded parallel runs.
  26983. int public_port = bypass_server.port();
  26984. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26985. bypass_hits++;
  26986. res.status = 302;
  26987. res.set_header("Location", "http://public.example:" +
  26988. std::to_string(public_port) + "/end");
  26989. });
  26990. proxy_mock.listen();
  26991. bypass_server.listen();
  26992. Client cli("public.example", public_port);
  26993. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26994. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26995. cli.set_no_proxy({"127.0.0.1"});
  26996. cli.set_follow_location(true);
  26997. auto res = cli.Get("/start");
  26998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26999. EXPECT_EQ(StatusCode::OK_200, res->status);
  27000. EXPECT_EQ("c-via-proxy", res->body);
  27001. EXPECT_GE(proxy_hits.load(), 2);
  27002. EXPECT_GE(bypass_hits.load(), 1);
  27003. EXPECT_TRUE(proxy_saw_c_url.load());
  27004. }
  27005. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27006. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27007. // request reconnects to the correct endpoint.
  27008. std::atomic<int> proxy_hits{0};
  27009. std::atomic<int> target_hits{0};
  27010. no_proxy_test::ScopedServer proxy_mock, target;
  27011. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27012. proxy_hits++;
  27013. res.set_content("via-proxy", "text/plain");
  27014. });
  27015. target.svr().Get(".*", [&](const Request &, Response &res) {
  27016. target_hits++;
  27017. res.set_content("direct", "text/plain");
  27018. });
  27019. proxy_mock.listen();
  27020. target.listen();
  27021. Client cli("public.example", target.port());
  27022. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27023. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27024. cli.set_keep_alive(true);
  27025. auto res1 = cli.Get("/a");
  27026. ASSERT_TRUE(res1);
  27027. EXPECT_EQ("via-proxy", res1->body);
  27028. EXPECT_EQ(1, proxy_hits.load());
  27029. EXPECT_EQ(0, target_hits.load());
  27030. cli.set_no_proxy({"public.example"});
  27031. auto res2 = cli.Get("/b");
  27032. ASSERT_TRUE(res2);
  27033. EXPECT_EQ("direct", res2->body);
  27034. EXPECT_EQ(1, proxy_hits.load());
  27035. EXPECT_EQ(1, target_hits.load());
  27036. }
  27037. // Forward declarations (see the base64_encode note).
  27038. namespace httplib {
  27039. namespace detail {
  27040. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27041. int shutdown_socket(socket_t sock) noexcept;
  27042. } // namespace detail
  27043. } // namespace httplib
  27044. namespace proxy_tunnel_test {
  27045. const char *const kTunnelEstablished =
  27046. "HTTP/1.1 200 Connection established\r\n\r\n";
  27047. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27048. using ConnectReply = std::function<std::string(const std::string &head)>;
  27049. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27050. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27051. class ScopedConnectProxy {
  27052. public:
  27053. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27054. : forward_port_(forward_port), reply_(std::move(reply)) {
  27055. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27056. if (listen_sock_ == INVALID_SOCKET) { return; }
  27057. auto a = loopback(0);
  27058. auto addr = reinterpret_cast<sockaddr *>(&a);
  27059. socklen_t alen = sizeof(a);
  27060. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27061. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27062. ::listen(listen_sock_, 4) != 0) {
  27063. return;
  27064. }
  27065. port_ = ntohs(a.sin_port);
  27066. th_ = std::thread([this] { run(); });
  27067. }
  27068. ~ScopedConnectProxy() {
  27069. if (th_.joinable()) {
  27070. stop_ = true;
  27071. auto wake = connect_to(port_);
  27072. th_.join();
  27073. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27074. }
  27075. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27076. }
  27077. int port() const { return port_; }
  27078. int connect_hits() const { return connect_hits_.load(); }
  27079. // Head of the last CONNECT request, as the proxy saw it on the wire.
  27080. std::string connect_request() const {
  27081. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27082. return connect_request_;
  27083. }
  27084. private:
  27085. static sockaddr_in loopback(int port) {
  27086. sockaddr_in a{};
  27087. a.sin_family = AF_INET;
  27088. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  27089. a.sin_port = htons(static_cast<unsigned short>(port));
  27090. return a;
  27091. }
  27092. static socket_t connect_to(int port) {
  27093. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  27094. if (sock == INVALID_SOCKET) { return sock; }
  27095. auto a = loopback(port);
  27096. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  27097. detail::close_socket(sock);
  27098. return INVALID_SOCKET;
  27099. }
  27100. return sock;
  27101. }
  27102. static bool send_all(socket_t sock, const char *data, size_t size) {
  27103. while (size > 0) {
  27104. auto n = detail::send_socket(sock, data, size, 0);
  27105. if (n <= 0) { return false; }
  27106. data += n;
  27107. size -= static_cast<size_t>(n);
  27108. }
  27109. return true;
  27110. }
  27111. void run() {
  27112. for (;;) {
  27113. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27114. if (stop_) {
  27115. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27116. return;
  27117. }
  27118. if (client == INVALID_SOCKET) { continue; }
  27119. serve(client);
  27120. detail::close_socket(client);
  27121. }
  27122. }
  27123. void serve(socket_t client) {
  27124. std::string head;
  27125. char buf[2048];
  27126. while (head.find("\r\n\r\n") == std::string::npos) {
  27127. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27128. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27129. if (n <= 0) { return; }
  27130. head.append(buf, static_cast<size_t>(n));
  27131. }
  27132. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27133. connect_hits_++;
  27134. {
  27135. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27136. connect_request_ = head;
  27137. }
  27138. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27139. if (!send_all(client, res.data(), res.size()) ||
  27140. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27141. return;
  27142. }
  27143. auto origin = connect_to(forward_port_);
  27144. if (origin == INVALID_SOCKET) { return; }
  27145. // When either side stops, shut both down so the other pump returns too.
  27146. auto pump = [&](socket_t from, socket_t to) {
  27147. char b[8192];
  27148. for (;;) {
  27149. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27150. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27151. }
  27152. detail::shutdown_socket(client);
  27153. detail::shutdown_socket(origin);
  27154. };
  27155. std::thread up([&] { pump(client, origin); });
  27156. pump(origin, client);
  27157. up.join();
  27158. detail::close_socket(origin);
  27159. }
  27160. int forward_port_;
  27161. ConnectReply reply_;
  27162. socket_t listen_sock_ = INVALID_SOCKET;
  27163. int port_ = 0;
  27164. std::thread th_;
  27165. std::atomic<bool> stop_{false};
  27166. std::atomic<int> connect_hits_{0};
  27167. mutable std::mutex connect_request_mutex_;
  27168. std::string connect_request_;
  27169. };
  27170. } // namespace proxy_tunnel_test
  27171. #ifdef CPPHTTPLIB_SSL_ENABLED
  27172. namespace proxy_tunnel_test {
  27173. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27174. class ScopedSSLServer {
  27175. public:
  27176. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27177. port_ = svr_.bind_to_any_port("127.0.0.1");
  27178. }
  27179. ~ScopedSSLServer() {
  27180. svr_.stop();
  27181. if (th_.joinable()) { th_.join(); }
  27182. }
  27183. SSLServer &svr() { return svr_; }
  27184. int port() const { return port_; }
  27185. void listen() {
  27186. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27187. svr_.wait_until_ready();
  27188. }
  27189. private:
  27190. SSLServer svr_;
  27191. std::thread th_;
  27192. int port_ = 0;
  27193. };
  27194. // Sends one request through the CONNECT proxy to the TLS origin with a
  27195. // credential configured for each hop, and checks that each credential reaches
  27196. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27197. // origin's (every header in origin_headers) on the tunnelled request.
  27198. void CredentialsStayWithTheirHop(
  27199. const std::function<void(SSLClient &)> &set_credentials,
  27200. const std::string &scheme,
  27201. const std::vector<std::string> &origin_headers = {"Authorization"},
  27202. bool stream = false) {
  27203. std::atomic<int> origin_hits{0};
  27204. std::atomic<bool> origin_saw_proxy_authz{false};
  27205. std::atomic<bool> origin_saw_headers{false};
  27206. ScopedSSLServer origin;
  27207. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27208. origin_hits++;
  27209. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27210. origin_saw_headers =
  27211. std::all_of(origin_headers.begin(), origin_headers.end(),
  27212. [&](const std::string &h) { return req.has_header(h); });
  27213. res.set_content("ok", "text/plain");
  27214. });
  27215. origin.listen();
  27216. ScopedConnectProxy proxy(origin.port());
  27217. ASSERT_NE(0, proxy.port());
  27218. // Pinned to 127.0.0.1 for the same reason as the test below.
  27219. SSLClient cli("127.0.0.1", origin.port());
  27220. cli.enable_server_certificate_verification(false);
  27221. cli.set_proxy("127.0.0.1", proxy.port());
  27222. set_credentials(cli);
  27223. if (stream) {
  27224. auto handle = cli.open_stream("GET", "/x");
  27225. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27226. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27227. } else {
  27228. auto res = cli.Get("/x");
  27229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27230. EXPECT_EQ(StatusCode::OK_200, res->status);
  27231. }
  27232. EXPECT_EQ(1, origin_hits.load());
  27233. EXPECT_EQ(1, proxy.connect_hits());
  27234. EXPECT_TRUE(origin_saw_headers.load());
  27235. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27236. << "Proxy-Authorization must not be sent inside the tunnel";
  27237. auto connect_req = proxy.connect_request();
  27238. EXPECT_NE(std::string::npos,
  27239. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27240. for (const auto &h : origin_headers) {
  27241. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27242. << h << " must not be sent to the proxy on CONNECT";
  27243. }
  27244. }
  27245. } // namespace proxy_tunnel_test
  27246. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27247. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27248. [](SSLClient &cli) {
  27249. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27250. cli.set_basic_auth("origin-user", "origin-pass");
  27251. },
  27252. "Basic");
  27253. }
  27254. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27255. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27256. [](SSLClient &cli) {
  27257. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27258. cli.set_basic_auth("origin-user", "origin-pass");
  27259. },
  27260. "Basic", {"Authorization"}, true);
  27261. }
  27262. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27263. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27264. [](SSLClient &cli) {
  27265. cli.set_proxy_bearer_token_auth("proxy-token");
  27266. cli.set_bearer_token_auth("origin-token");
  27267. },
  27268. "Bearer");
  27269. }
  27270. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27271. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27272. [](SSLClient &cli) {
  27273. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27274. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27275. {"Cookie", "sid=origin-session"},
  27276. {"X-Api-Key", "origin-key"}});
  27277. },
  27278. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27279. }
  27280. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27281. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27282. // retry; otherwise proxy creds would be sent to the origin.
  27283. std::atomic<int> origin_hits{0};
  27284. std::atomic<bool> origin_saw_proxy_authz{false};
  27285. proxy_tunnel_test::ScopedSSLServer origin;
  27286. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27287. origin_hits++;
  27288. if (req.has_header("Proxy-Authorization")) {
  27289. origin_saw_proxy_authz = true;
  27290. }
  27291. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27292. res.set_header("Proxy-Authenticate",
  27293. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27294. "algorithm=MD5");
  27295. });
  27296. origin.listen();
  27297. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27298. ASSERT_NE(0, proxy.port());
  27299. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27300. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27301. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27302. // and answer with its own status, making this test flaky.
  27303. SSLClient cli("127.0.0.1", origin.port());
  27304. cli.enable_server_certificate_verification(false);
  27305. cli.set_proxy("127.0.0.1", proxy.port());
  27306. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27307. auto res = cli.Get("/x");
  27308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27309. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27310. EXPECT_EQ(1, origin_hits.load());
  27311. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27312. EXPECT_EQ(1, proxy.connect_hits());
  27313. }
  27314. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27315. std::string origin_sni;
  27316. std::string origin_host;
  27317. proxy_tunnel_test::ScopedSSLServer origin;
  27318. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27319. origin_sni = req.sni();
  27320. origin_host = req.get_header_value("Host");
  27321. res.set_content("ok", "text/plain");
  27322. });
  27323. origin.listen();
  27324. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27325. ASSERT_NE(0, proxy.port());
  27326. SSLClient cli("origin.example", origin.port());
  27327. cli.enable_server_certificate_verification(false);
  27328. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27329. cli.set_proxy("127.0.0.1", proxy.port());
  27330. auto res = cli.Get("/x");
  27331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27332. EXPECT_EQ(StatusCode::OK_200, res->status);
  27333. auto port = std::to_string(origin.port());
  27334. auto target = "127.0.0.1:" + port;
  27335. auto connect_req = proxy.connect_request();
  27336. EXPECT_EQ(1, proxy.connect_hits());
  27337. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27338. EXPECT_NE(std::string::npos,
  27339. connect_req.find("\r\nHost: " + target + "\r\n"));
  27340. EXPECT_EQ("origin.example", origin_sni);
  27341. EXPECT_EQ("origin.example:" + port, origin_host);
  27342. }
  27343. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27344. proxy_tunnel_test::ScopedSSLServer origin;
  27345. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27346. res.set_content("ok", "text/plain");
  27347. });
  27348. origin.listen();
  27349. proxy_tunnel_test::ScopedConnectProxy proxy(
  27350. origin.port(), [](const std::string &head) -> std::string {
  27351. if (head.find(
  27352. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27353. std::string::npos) {
  27354. return proxy_tunnel_test::kTunnelEstablished;
  27355. }
  27356. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27357. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27358. "nonce=\"abc\", algorithm=MD5\r\n"
  27359. "Content-Length: 0\r\n\r\n";
  27360. });
  27361. ASSERT_NE(0, proxy.port());
  27362. SSLClient cli("origin.example", origin.port());
  27363. cli.enable_server_certificate_verification(false);
  27364. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27365. cli.set_proxy("127.0.0.1", proxy.port());
  27366. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27367. auto res = cli.Get("/x");
  27368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27369. EXPECT_EQ(StatusCode::OK_200, res->status);
  27370. // The retried CONNECT is the one the proxy saw last.
  27371. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27372. auto connect_req = proxy.connect_request();
  27373. EXPECT_EQ(2, proxy.connect_hits());
  27374. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27375. EXPECT_NE(std::string::npos,
  27376. connect_req.find("\r\nHost: " + target + "\r\n"));
  27377. }
  27378. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27379. proxy_tunnel_test::ScopedSSLServer origin;
  27380. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27381. res.set_content("ok", "text/plain");
  27382. });
  27383. origin.listen();
  27384. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27385. ASSERT_NE(0, proxy.port());
  27386. SSLClient cli("origin.example", origin.port());
  27387. cli.enable_server_certificate_verification(false);
  27388. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27389. cli.set_proxy("127.0.0.1", proxy.port());
  27390. auto res = cli.Get("/x");
  27391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27392. EXPECT_EQ(StatusCode::OK_200, res->status);
  27393. auto target = "origin.example:" + std::to_string(origin.port());
  27394. auto connect_req = proxy.connect_request();
  27395. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27396. EXPECT_NE(std::string::npos,
  27397. connect_req.find("\r\nHost: " + target + "\r\n"));
  27398. }
  27399. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27400. proxy_tunnel_test::ScopedSSLServer origin;
  27401. auto port = std::to_string(origin.port());
  27402. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27403. res.set_redirect("https://next.example:" + port + "/y");
  27404. });
  27405. origin.svr().Get("/y", [](const Request &, Response &res) {
  27406. res.set_content("ok", "text/plain");
  27407. });
  27408. origin.listen();
  27409. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27410. ASSERT_NE(0, proxy.port());
  27411. SSLClient cli("origin.example", origin.port());
  27412. cli.enable_server_certificate_verification(false);
  27413. cli.set_tunnel_hostname_addr_map(
  27414. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27415. cli.set_proxy("127.0.0.1", proxy.port());
  27416. cli.set_follow_location(true);
  27417. auto res = cli.Get("/x");
  27418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27419. EXPECT_EQ("ok", res->body);
  27420. // The last CONNECT is the redirect client's.
  27421. ASSERT_EQ(2, proxy.connect_hits());
  27422. auto target = "127.0.0.1:" + port;
  27423. auto connect_req = proxy.connect_request();
  27424. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27425. EXPECT_NE(std::string::npos,
  27426. connect_req.find("\r\nHost: " + target + "\r\n"));
  27427. }
  27428. #endif
  27429. namespace proxy_tunnel_test {
  27430. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27431. // anything else gets a 407 with `challenge`.
  27432. ConnectReply require_proxy_auth(const std::string &expected,
  27433. const std::string &challenge) {
  27434. return [=](const std::string &head) -> std::string {
  27435. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27436. std::string::npos) {
  27437. return kTunnelEstablished;
  27438. }
  27439. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27440. "Proxy-Authenticate: " +
  27441. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27442. };
  27443. }
  27444. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27445. // request, then echoes.
  27446. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27447. ws.send(
  27448. "authorization:" + req.get_header_value("Authorization") +
  27449. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27450. std::string msg;
  27451. while (ws.read(msg)) {
  27452. ws.send(msg);
  27453. }
  27454. }
  27455. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27456. class ScopedWebSocketOrigin {
  27457. public:
  27458. ScopedWebSocketOrigin() {
  27459. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27460. server_.listen();
  27461. }
  27462. int port() const { return server_.port(); }
  27463. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27464. std::string url() const {
  27465. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27466. }
  27467. private:
  27468. no_proxy_test::ScopedServer server_;
  27469. };
  27470. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27471. // passed as a constructor header, and checks that each reaches only its hop.
  27472. void WebSocketCredentialsStayWithTheirHop(
  27473. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27474. const std::string &proxy_authz, const std::string &origin_authz) {
  27475. ScopedWebSocketOrigin origin;
  27476. ScopedConnectProxy proxy(
  27477. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27478. ASSERT_NE(0, proxy.port());
  27479. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27480. client.set_proxy("127.0.0.1", proxy.port());
  27481. set_proxy_credentials(client);
  27482. auto res = client.connect();
  27483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27484. std::string msg;
  27485. ASSERT_TRUE(client.read(msg));
  27486. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27487. client.close();
  27488. EXPECT_EQ(1, proxy.connect_hits());
  27489. EXPECT_EQ(std::string::npos,
  27490. proxy.connect_request().find("\r\nAuthorization: "))
  27491. << "origin credentials must not be sent to the proxy";
  27492. }
  27493. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  27494. void WebSocketSetterCredentialsStayWithTheirHop(
  27495. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  27496. const std::string &proxy_authz, const std::string &origin_authz) {
  27497. ScopedWebSocketOrigin origin;
  27498. ScopedConnectProxy proxy(
  27499. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27500. ASSERT_NE(0, proxy.port());
  27501. ws::WebSocketClient client(origin.url());
  27502. client.set_proxy("127.0.0.1", proxy.port());
  27503. set_credentials(client);
  27504. auto res = client.connect();
  27505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27506. std::string msg;
  27507. ASSERT_TRUE(client.read(msg));
  27508. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27509. client.close();
  27510. EXPECT_EQ(1, proxy.connect_hits());
  27511. EXPECT_EQ(std::string::npos,
  27512. proxy.connect_request().find("\r\nAuthorization: "))
  27513. << "origin credentials must not be sent to the proxy";
  27514. }
  27515. } // namespace proxy_tunnel_test
  27516. namespace {
  27517. // Connects `client` and returns the Authorization header its upgrade
  27518. // request carried, or "<failed>" when the connection could not be opened.
  27519. std::string websocket_authorization(ws::WebSocketClient &client) {
  27520. if (!client.connect()) { return "<failed>"; }
  27521. std::string msg;
  27522. if (!client.read(msg)) { return "<failed>"; }
  27523. client.close();
  27524. auto prefix = std::string("authorization:");
  27525. auto end = msg.find("|proxy-authorization:");
  27526. return msg.substr(prefix.size(), end - prefix.size());
  27527. }
  27528. } // namespace
  27529. TEST(WebSocketClientAuthTest, BasicAuth) {
  27530. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27531. ws::WebSocketClient client(origin.url());
  27532. client.set_basic_auth("user", "pass");
  27533. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27534. websocket_authorization(client));
  27535. }
  27536. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  27537. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27538. ws::WebSocketClient client(origin.url());
  27539. client.set_basic_auth("user", "");
  27540. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  27541. websocket_authorization(client));
  27542. }
  27543. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  27544. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27545. ws::WebSocketClient client(origin.url());
  27546. client.set_bearer_token_auth("token123");
  27547. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  27548. }
  27549. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  27550. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27551. ws::WebSocketClient client(origin.url());
  27552. client.set_bearer_token_auth("token123");
  27553. client.set_basic_auth("user", "pass");
  27554. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27555. websocket_authorization(client));
  27556. }
  27557. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  27558. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27559. ws::WebSocketClient client(origin.url(),
  27560. {{"Authorization", "Bearer from-header"}});
  27561. client.set_bearer_token_auth("from-setter");
  27562. client.set_basic_auth("user", "pass");
  27563. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  27564. }
  27565. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  27566. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27567. ws::WebSocketClient client(origin.url());
  27568. EXPECT_EQ("", websocket_authorization(client));
  27569. client.set_bearer_token_auth("first");
  27570. EXPECT_EQ("Bearer first", websocket_authorization(client));
  27571. client.set_bearer_token_auth("second");
  27572. EXPECT_EQ("Bearer second", websocket_authorization(client));
  27573. client.set_bearer_token_auth("");
  27574. EXPECT_EQ("", websocket_authorization(client));
  27575. }
  27576. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27577. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27578. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27579. ASSERT_NE(0, proxy.port());
  27580. ws::WebSocketClient client(origin.url());
  27581. client.set_proxy("127.0.0.1", proxy.port());
  27582. auto res = client.connect();
  27583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27584. std::string msg;
  27585. ASSERT_TRUE(client.read(msg));
  27586. ASSERT_TRUE(client.send("hello"));
  27587. ASSERT_TRUE(client.read(msg));
  27588. EXPECT_EQ("hello", msg);
  27589. client.close();
  27590. EXPECT_EQ(1, proxy.connect_hits());
  27591. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27592. auto connect_req = proxy.connect_request();
  27593. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27594. EXPECT_NE(std::string::npos,
  27595. connect_req.find("\r\nHost: " + target + "\r\n"));
  27596. }
  27597. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27598. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27599. [](ws::WebSocketClient &cli) {
  27600. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27601. },
  27602. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27603. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27604. }
  27605. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27606. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27607. [](ws::WebSocketClient &cli) {
  27608. cli.set_proxy_bearer_token_auth("proxy-token");
  27609. },
  27610. "Bearer proxy-token", "Bearer origin-token");
  27611. }
  27612. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  27613. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27614. [](ws::WebSocketClient &cli) {
  27615. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27616. cli.set_basic_auth("origin-user", "origin-pass");
  27617. },
  27618. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27619. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27620. }
  27621. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  27622. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27623. [](ws::WebSocketClient &cli) {
  27624. cli.set_proxy_bearer_token_auth("proxy-token");
  27625. cli.set_bearer_token_auth("origin-token");
  27626. },
  27627. "Bearer proxy-token", "Bearer origin-token");
  27628. }
  27629. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27630. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27631. proxy_tunnel_test::ScopedConnectProxy proxy(
  27632. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27633. "Basic " + detail::base64_encode("proxy-user:"),
  27634. "Basic realm=\"proxy\""));
  27635. ASSERT_NE(0, proxy.port());
  27636. ws::WebSocketClient client(origin.url());
  27637. client.set_proxy("127.0.0.1", proxy.port());
  27638. client.set_proxy_basic_auth("proxy-user", "");
  27639. auto res = client.connect();
  27640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27641. client.close();
  27642. EXPECT_EQ(1, proxy.connect_hits());
  27643. }
  27644. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27645. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27646. proxy_tunnel_test::ScopedConnectProxy proxy(
  27647. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27648. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27649. ASSERT_NE(0, proxy.port());
  27650. ws::WebSocketClient client(origin.url());
  27651. client.set_proxy("127.0.0.1", proxy.port());
  27652. auto res = client.connect();
  27653. EXPECT_FALSE(res);
  27654. EXPECT_EQ(Error::ProxyConnection, res.error());
  27655. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27656. EXPECT_EQ("Basic realm=\"proxy\"",
  27657. res.get_header_value("Proxy-Authenticate"));
  27658. EXPECT_FALSE(client.is_open());
  27659. }
  27660. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27661. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27662. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27663. ASSERT_NE(0, proxy.port());
  27664. ws::WebSocketClient client(origin.url());
  27665. client.set_proxy("127.0.0.1", proxy.port());
  27666. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27667. client.set_no_proxy({"127.0.0.1"});
  27668. auto res = client.connect();
  27669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27670. std::string msg;
  27671. ASSERT_TRUE(client.read(msg));
  27672. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27673. << "proxy credentials must not reach a bypassed origin";
  27674. client.close();
  27675. EXPECT_EQ(0, proxy.connect_hits());
  27676. }
  27677. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27678. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27679. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27680. ASSERT_NE(0, proxy.port());
  27681. ws::WebSocketClient client(origin.url());
  27682. client.set_proxy("127.0.0.1", proxy.port());
  27683. ASSERT_TRUE(client.connect());
  27684. ASSERT_TRUE(client.connect());
  27685. client.close();
  27686. EXPECT_EQ(2, proxy.connect_hits());
  27687. }
  27688. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27689. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27690. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27691. ASSERT_NE(0, proxy.port());
  27692. auto port = std::to_string(origin.port());
  27693. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27694. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27695. client.set_proxy("127.0.0.1", proxy.port());
  27696. auto res = client.connect();
  27697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27698. std::string msg;
  27699. ASSERT_TRUE(client.read(msg));
  27700. client.close();
  27701. EXPECT_EQ(1, proxy.connect_hits());
  27702. auto target = "127.0.0.1:" + port;
  27703. auto connect_req = proxy.connect_request();
  27704. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27705. EXPECT_NE(std::string::npos,
  27706. connect_req.find("\r\nHost: " + target + "\r\n"));
  27707. }
  27708. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27709. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27710. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27711. ASSERT_NE(0, proxy.port());
  27712. auto port = std::to_string(origin.port());
  27713. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27714. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27715. client.set_proxy("127.0.0.1", proxy.port());
  27716. auto res = client.connect();
  27717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27718. client.close();
  27719. auto target = "origin.example:" + port;
  27720. auto connect_req = proxy.connect_request();
  27721. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27722. EXPECT_NE(std::string::npos,
  27723. connect_req.find("\r\nHost: " + target + "\r\n"));
  27724. }
  27725. #ifdef CPPHTTPLIB_SSL_ENABLED
  27726. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27727. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27728. proxy_tunnel_test::ScopedConnectProxy proxy(
  27729. origin.port(), [](const std::string &head) -> std::string {
  27730. if (head.find(
  27731. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27732. std::string::npos) {
  27733. return proxy_tunnel_test::kTunnelEstablished;
  27734. }
  27735. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27736. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27737. "nonce=\"abc\", algorithm=MD5\r\n"
  27738. "Content-Length: 0\r\n\r\n";
  27739. });
  27740. ASSERT_NE(0, proxy.port());
  27741. ws::WebSocketClient client(origin.url());
  27742. client.set_proxy("127.0.0.1", proxy.port());
  27743. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27744. auto res = client.connect();
  27745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27746. std::string msg;
  27747. ASSERT_TRUE(client.read(msg));
  27748. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27749. client.close();
  27750. EXPECT_EQ(2, proxy.connect_hits());
  27751. }
  27752. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27753. proxy_tunnel_test::ScopedSSLServer origin;
  27754. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27755. origin.listen();
  27756. proxy_tunnel_test::ScopedConnectProxy proxy(
  27757. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27758. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27759. ASSERT_NE(0, proxy.port());
  27760. ws::WebSocketClient client(
  27761. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27762. client.enable_server_certificate_verification(false);
  27763. client.set_proxy("127.0.0.1", proxy.port());
  27764. client.set_proxy_bearer_token_auth("proxy-token");
  27765. auto res = client.connect();
  27766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27767. std::string msg;
  27768. ASSERT_TRUE(client.read(msg));
  27769. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27770. << "Proxy-Authorization must not be sent inside the tunnel";
  27771. client.close();
  27772. EXPECT_EQ(1, proxy.connect_hits());
  27773. }
  27774. #endif